From 6932789453551e1b6803926724f2721c083f1b18 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 5 Nov 2018 16:49:01 +0000 Subject: [PATCH 001/361] extended advertising scanning and connecting API --- features/FEATURE_BLE/ble/BLETypes.h | 101 + features/FEATURE_BLE/ble/Gap.h | 2945 +++++++++-------- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 265 +- features/FEATURE_BLE/ble/GapScanningParams.h | 28 +- .../FEATURE_BLE/source/GapScanningParams.cpp | 4 +- 5 files changed, 1964 insertions(+), 1379 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 0aed57d9c0..aa7a171262 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -120,6 +120,107 @@ static inline attribute_handle_range_t attribute_handle_range( return result; } +/** + * Encapsulates the peripheral advertising modes. + * + * It determine how the device appears to other scanner and peripheral + * devices in the scanning range. + */ +enum advertising_type_t { + /** + * Device is connectable, scannable and doesn't expect connection from a + * specific peer. + * + * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. + */ + ADV_CONNECTABLE_UNDIRECTED, + + /** + * Device is connectable and expects connection from a specific peer. + * + * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. + */ + ADV_CONNECTABLE_DIRECTED, + + /** + * Device is scannable but not connectable. + * + * @see Vol 6, Part B, Section 2.3.1.4. + */ + ADV_SCANNABLE_UNDIRECTED, + + /** + * Device is not connectable and not scannable. + * + * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. + */ + ADV_NON_CONNECTABLE_UNDIRECTED, + + + /* extended advertising */ + EXT_ADV_CONNECTABLE_UNDIRECTED, + + EXT_ADV_NON_CONNECTABLE_DIRECTED, + + EXT_ADV_SCANNABLE_DIRECTED, + + EXT_ADV_HIGH_DUTY_CYCLE_CONNECTABLE_DIRECTED +}; + +struct advertising_event_t { + uint8_t connectable_advertising:1; + uint8_t scannable_advertising:1; + uint8_t directed_advertising:1; + uint8_t scan_response:1; + uint8_t legacy:1; + uint8_t complete:1; + uint8_t last:1; +}; + +/** + * Advertising policy filter modes. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. + */ +enum advertising_policy_mode_t { + /** + * The whitelist is not used to filter peer request during advertising. + */ + ADV_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter peer scan requests. + */ + ADV_POLICY_FILTER_SCAN_REQS = 1, + + /** + * The whitelist is used to filter peer connection requests. + */ + ADV_POLICY_FILTER_CONN_REQS = 2, + + /** + * The whitelist is used to filter peer scan and connection requests. + */ + ADV_POLICY_FILTER_ALL_REQS = 3, +}; + +/** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ +enum scanning_policy_mode_t { + /** + * The whitelist is not used for scanning operations. + */ + SCAN_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter incoming advertising. + */ + SCAN_POLICY_FILTER_ALL_ADV = 1, +}; + /** * Type that describes link's encryption state. */ diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 2c7e9168d3..dc0c7944c4 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -26,6 +26,7 @@ #include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" +#include "platform/NonCopyable.h" /* Forward declarations for classes that are only used for pointers or references. */ @@ -321,58 +322,6 @@ class GapAdvertisingData; * controller or by the peer. */ class Gap { - /* - * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated. - * They have been relocated to the class BLEProtocol. - */ -public: - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. - */ - typedef BLEProtocol::AddressType_t AddressType_t; - - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. - */ - typedef BLEProtocol::AddressType_t addr_type_t; - - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. The following - * constants have been left in their deprecated state to transparently - * support existing applications that may have used Gap::ADDR_TYPE_*. - */ - enum DeprecatedAddressType_t { - ADDR_TYPE_PUBLIC = BLEProtocol::AddressType::PUBLIC, - ADDR_TYPE_RANDOM_STATIC = BLEProtocol::AddressType::RANDOM_STATIC, - ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE, - ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE - }; - - /** - * Length (in octets) of the BLE MAC address. - */ - static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN; - - /** - * 48-bit address, LSB format. - * - * @deprecated Use BLEProtocol::AddressBytes_t instead. - */ - typedef BLEProtocol::AddressBytes_t Address_t; - - /** - * 48-bit address, LSB format. - * - * @deprecated Use BLEProtocol::AddressBytes_t instead. - */ - typedef BLEProtocol::AddressBytes_t address_t; - public: /** * Enumeration of possible timeout sources. @@ -450,49 +399,9 @@ public: CONN_INTERVAL_UNACCEPTABLE = 0x3B, }; - /** - * Advertising policy filter modes. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. - */ - enum AdvertisingPolicyMode_t { - /** - * The whitelist is not used to filter peer request during advertising. - */ - ADV_POLICY_IGNORE_WHITELIST = 0, + typedef ble::advertising_policy_mode_t AdvertisingPolicyMode_t; - /** - * The whitelist is used to filter peer scan requests. - */ - ADV_POLICY_FILTER_SCAN_REQS = 1, - - /** - * The whitelist is used to filter peer connection requests. - */ - ADV_POLICY_FILTER_CONN_REQS = 2, - - /** - * The whitelist is used to filter peer scan and connection requests. - */ - ADV_POLICY_FILTER_ALL_REQS = 3, - }; - - /** - * Scanning policy filter mode. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. - */ - enum ScanningPolicyMode_t { - /** - * The whitelist is not used for scanning operations. - */ - SCAN_POLICY_IGNORE_WHITELIST = 0, - - /** - * The whitelist is used to filter incoming advertising. - */ - SCAN_POLICY_FILTER_ALL_ADV = 1, - }; + typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; /** * Connection initiation policy filter mode. @@ -532,21 +441,6 @@ public: uint8_t capacity; }; - /** - * Description of the states of the device. - */ - struct GapState_t { - /** - * If set, the device is currently advertising. - */ - unsigned advertising : 1; - - /** - * If set, the device is connected to at least one other peer. - */ - unsigned connected : 1; - }; - /** * Opaque value type representing a connection handle. * @@ -585,7 +479,7 @@ public: /** * Parameters of a BLE connection. */ - typedef struct { + struct ConnectionParams_t { /** * Minimum interval between two connection events allowed for a * connection. @@ -627,7 +521,7 @@ public: * @note maxConnectionInterval is in ms in the formulae above. */ uint16_t connectionSupervisionTimeout; - } ConnectionParams_t; + }; /** * Enumeration of GAP roles. @@ -688,7 +582,7 @@ public: /** * Type of advertisement. */ - GapAdvertisingParams::AdvertisingType_t type; + ble::advertising_type_t type; /** * Length of the advertisement data. @@ -714,7 +608,7 @@ public: "addressType won't work in connect when privacy is enabled; please" "use peerAddrType" ) - AddressType_t addressType; + BLEProtocol::AddressType_t addressType; /** * Type of the address received. @@ -773,7 +667,7 @@ public: /** * Address type of the local device. */ - BLEProtocol::AddressType_t ownAddrType; + BLEProtocol::AddressType_t ownAddrType; /** * Address of the local device. @@ -794,7 +688,7 @@ public: /** * Connection parameters. */ - const ConnectionParams_t *connectionParams; + const ConnectionParams_t *connectionParams; /** * Resolvable address used by the peer. @@ -1120,11 +1014,64 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; + typedef uint8_t AdvHandle_t; + + static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; + + struct AdvReportOptionalInformation { + PeerAddressType_t directAddressType; + BLEProtocol::AddressBytes_t directAddress; + Phy_t primaryPhy; + Phy_t secondaryPhy; + uint16_t periodicInterval; + uint8_t SID; + int8_t txPower; + int8_t rssi; + }; /** * Definition of the general handler of Gap related events. */ struct EventHandler { + + virtual void onScanRequest( + AdvHandle_t advHandle, + const BLEProtocol::AddressBytes_t peerAddres, + PeerAddressType_t peerAddresType + ) { + (void) advHandle; + (void) peerAddres; + (void) peerAddresType; + } + + virtual void onAdvertisingEnd( + AdvHandle_t advHandle, + Handle_t connection, + uint8_t completed_events, + bool connected + ) { + (void) advHandle; + (void) connection; + (void) completed_events; + (void) connected; + } + + void onAdvertisingReport( + ble::advertising_event_t type, + PeerAddressType_t peerAddrType, + BLEProtocol::AddressBytes_t peerAddr, + uint8_t advertisingDataLen, + const uint8_t *advertisingData, + AdvReportOptionalInformation *extraInfo + ) { + (void) type; + (void) peerAddrType; + (void) peerAddr; + (void) advertisingDataLen; + (void) advertisingData; + (void) extraInfo; + } + /** * Function invoked when the current transmitter and receiver PHY have * been read for a given connection. @@ -1192,100 +1139,91 @@ public: ~EventHandler() { } }; - /* - * The following functions are meant to be overridden in the platform-specific subclass. - */ + /* The following functions are meant to be overridden in the platform-specific subclass. */ + public: - /** - * Set the device MAC address and type. - * - * The address set is used in subsequent GAP operations: scanning, - * advertising and connection initiation. - * - * @param[in] type Type of the address to set. - * @param[in] address Value of the address to set. It is ordered in - * little endian. This parameter is not considered if the address type - * is RANDOM_PRIVATE_RESOLVABLE or RANDOM_PRIVATE_NON_RESOLVABLE. For those - * types of address, the BLE API itself generates the address. - * - * @note Some implementation may refuse to set a new PUBLIC address. - * @note Random static address set does not change. - * - * @deprecated Starting with mbed-os-5.9.0 this function is deprecated and - * address management is delegated to implementation. Implementations may or - * may not continue to support this function. Compliance with the Bluetooth - * specification and unification of behaviour between implementations are - * the key reasons behind this change: - * - Many implementations do not allow changing of the public address. - * Therefore programs relying on this function are not portable across BLE - * implementations. - * - The Bluetooth specification forbid replacement of the random static - * address; this address can be set once and only once: at startup. - * Depending on the underlying implementation the random address may or - * may not have been set automatically at startup; therefore update of the - * Random Static address after ble initialisation may be a fault. As a - * result calls to this function were not portable. - * Furthermore replacement of the random static address silently - * invalidates the bond stored in the secure database. - * @return BLE_ERROR_NONE on success. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "Non portable API, use enablePrivacy to enable use of private addresses" - ) - virtual ble_error_t setAddress( - BLEProtocol::AddressType_t type, - const BLEProtocol::AddressBytes_t address - ) { - /* avoid compiler warnings about unused variables */ - (void)type; - (void)address; + /* advertising */ - /* Requesting action from porter(s): override this API if this capability - is supported. */ + uint8_t getMaxAdvertisingSetNumber() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 1; + } + + uint8_t getMaxAdvertisingDataLength() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0x1F; + } + + ble_error_t createAdvertisingSet(AdvHandle_t* handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * Fetch the current address and its type. - * - * @param[out] typeP Type of the current address set. - * @param[out] address Value of the current address. - * - * @note If privacy is enabled the device address may be unavailable to - * application code. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t getAddress( - BLEProtocol::AddressType_t *typeP, - BLEProtocol::AddressBytes_t address - ) { - /* Avoid compiler warnings about unused variables. */ - (void)typeP; - (void)address; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ + ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * Return the type of a random address. - * - * @param[in] address The random address to retrieve the type from. The - * address must be ordered in little endian. - * - * @param[out] addressType Type of the address to fill. - * - * @return BLE_ERROR_NONE in case of success or BLE_ERROR_INVALID_PARAM if - * the address in input was not identifiable as a random address. - */ - static ble_error_t getRandomAddressType( - const BLEProtocol::AddressBytes_t address, - RandomAddressType_t* addressType - ); + ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { + (void) handle; + (void) params; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { + (void) handle; + (void) params; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { + (void) handle; + (void) payload; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { + (void) handle; + (void) response; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + ble_error_t startAdvertising(AdvHandle_t handle) { + /* deprecation compatibility */ + if (handle != LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + ble_error_t status = setAdvertisingData(getLegacyAdvertisingPayload(), getLegacyAdvertisingScanResponse()); + if (status != BLE_ERROR_NONE) { + return status; + } + status = startAdvertising(getLegacyAdvertisingParams()); + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return status; + } + + ble_error_t stopAdvertising(AdvHandle_t handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + bool isAdvertisingActive(AdvHandle_t handle) const { + if (handle != LEGACY_ADVERTISING_HANDLE) { + return false; + } + /* Requesting action from porter(s): override this API if this capability is supported. */ + return state.advertising; + } /** * Get the minimum advertising interval in milliseconds, which can be used @@ -1296,8 +1234,7 @@ public: */ virtual uint16_t getMinAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability - is supported. */ + /* Requesting action from porter(s): override this API if this capability is supported. */ return 0; } @@ -1310,8 +1247,7 @@ public: */ virtual uint16_t getMinNonConnectableAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability - is supported. */ + /* Requesting action from porter(s): override this API if this capability is supported. */ return 0; } @@ -1322,26 +1258,38 @@ public: */ virtual uint16_t getMaxAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability - is supported. */ + /* Requesting action from porter(s): override this API if this capability is supported. */ return 0xFFFF; } /** - * Stop the ongoing advertising procedure. + * Query the underlying stack for allowed Tx power values. * - * @note The current advertising parameters remain in effect. - * - * @retval BLE_ERROR_NONE if the advertising procedure has been successfully - * stopped. + * @param[out] valueArrayPP Receive the immutable array of Tx values. + * @param[out] countP Receive the array's size. */ - virtual ble_error_t stopAdvertising(void) - { - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; + virtual void getPermittedTxPowerValues( + const int8_t **valueArrayPP, + size_t *countP + ) { + /* Avoid compiler warnings about unused variables. */ + (void)valueArrayPP; + (void)countP; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + *countP = 0; } + /* scanning */ + + ble_error_t startScan(const GapScanningParams params) { + return startRadioScan(params); + }; + + ble_error_t startScan() { + return startRadioScan(_scanningParams); + }; + /** * Stop the ongoing scanning procedure. * @@ -1351,894 +1299,12 @@ public: */ virtual ble_error_t stopScan() { - /* Requesting action from porter(s): override this API if this capability - is supported. */ + /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * Initiate a connection to a peer. - * - * Once the connection is established, a ConnectionCallbackParams_t event is - * emitted to handlers that have been registered with onConnection(). - * - * @param[in] peerAddr MAC address of the peer. It must be in LSB format. - * @param[in] peerAddrType Address type of the peer. It is usually obtained - * from advertising frames. - * @param[in] connectionParams Connection parameters to use. - * @param[in] scanParams Scan parameters used to find the peer. - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallChain (if set) is invoked upon - * a connection event. - */ - virtual ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - PeerAddressType_t peerAddrType, - const ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams - ) { - /* Avoid compiler warnings about unused variables. */ - (void)peerAddr; - (void)peerAddrType; - (void)connectionParams; - (void)scanParams; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a connection to a peer. - * - * Once the connection is established, a ConnectionCallbackParams_t event is - * emitted to handlers that have been registered with onConnection(). - * - * @param[in] peerAddr MAC address of the peer. It must be in LSB format. - * @param[in] peerAddrType Address type of the peer. - * @param[in] connectionParams Connection parameters to use. - * @param[in] scanParams Scan parameters used to find the peer. - * - * @deprecated BLEProtocol::AddressType_t is not able to to carry accurate - * meaning when privacy is in use. Please Uses the connect overload that - * accept a PeerAddressType_t as the peer address type. - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallChain (if set) is invoked upon - * a connection event. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "This function won't work if privacy is enabled; You must use the overload " - "accepting PeerAddressType_t." - ) - virtual ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t peerAddrType, - const ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams - ) { - /* Avoid compiler warnings about unused variables. */ - (void)peerAddr; - (void)peerAddrType; - (void)connectionParams; - (void)scanParams; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a connection to a peer. - * - * @see connect() - * - * @deprecated This funtion overloads Gap::connect( - * const BLEProtocol::Address_t peerAddr, - * BLEProtocol::AddressType_t peerAddrType, - * const ConnectionParams_t *connectionParams, - * const GapScanningParams *scanParams - * ) - * to maintain backward compatibility for changes from Gap::AddressType_t to - * BLEProtocol::AddressType_t. - */ - MBED_DEPRECATED("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead") - ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - DeprecatedAddressType_t peerAddrType, - const ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams - ); - - /** - * Read the PHY used by the transmitter and the receiver on a connection. - * - * Once the PHY has been read, it is reported back via the function onPhyRead - * of the event handler registered by the application. - * - * @param connection Handle of the connection for which the PHY being used is - * queried. - * - * @return BLE_ERROR_NONE if the read PHY procedure has been started or an - * appropriate error code. - */ - virtual ble_error_t readPhy(Handle_t connection) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the preferred PHYs to use in a connection. - * - * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no - * preferred PHYs are set and the default value of the subsytem is used. - * - * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no - * preferred PHYs are set and the default value of the subsytem is used. - * - * @return BLE_ERROR_NONE if the preferences have been set or an appropriate - * error code. - */ - virtual ble_error_t setPreferredPhys( - const PhySet_t* txPhys, - const PhySet_t* rxPhys - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Update the PHY used by a connection. - * - * Once the update process has been completed, it is reported back to the - * application via the function onPhyUpdateComplete of the event handler - * registered by the application. - * - * @param connection Handle of the connection to update. - * - * @param txPhys Set of PHYs preferred for tx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param codedSymbol Number of symbols used to code a bit when le coded is - * used. If the value is UNDEFINED then the choice is up to the Bluetooth - * subsystem. - * - * @return BLE_ERROR_NONE if the update PHY procedure has been successfully - * started or an error code. - */ - virtual ble_error_t setPhy( - Handle_t connection, - const PhySet_t* txPhys, - const PhySet_t* rxPhys, - CodedSymbolPerBit_t codedSymbol - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a disconnection procedure. - * - * Once the disconnection procedure has completed a - * DisconnectionCallbackParams_t, the event is emitted to handlers that - * have been registered with onDisconnection(). - * - * @param[in] reason Reason of the disconnection transmitted to the peer. - * @param[in] connectionHandle Handle of the connection to end. - * - * @return BLE_ERROR_NONE if the disconnection procedure successfully - * started. - */ - virtual ble_error_t disconnect( - Handle_t connectionHandle, DisconnectionReason_t reason - ) { - /* avoid compiler warnings about unused variables */ - (void)connectionHandle; - (void)reason; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a disconnection procedure. - * - * @deprecated This version of disconnect() doesn't take a connection handle. - * It works reliably only for stacks that are limited to a single connection. - * Use Gap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) - * instead. - * - * @param[in] reason The reason for disconnection; to be sent back to the peer. - * - * @return BLE_ERROR_NONE if disconnection was successful. - */ - MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") - virtual ble_error_t disconnect(DisconnectionReason_t reason) { - /* Avoid compiler warnings about unused variables. */ - (void)reason; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Returned the preferred connection parameters exposed in the GATT Generic - * Access Service. - * - * @param[out] params Structure where the parameters are stored. - * - * @return BLE_ERROR_NONE if the parameters were successfully filled into - * @p params. - */ - virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) - { - /* Avoid compiler warnings about unused variables. */ - (void)params; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the preferred connection parameters exposed in the GATT - * Generic Access Service. - * - * A connected peer may read the characteristic exposing these parameters - * and request an update of the connection parameters to accomodate the - * local device. - * - * @param[in] params Value of the preferred connection parameters. - * - * @return BLE_ERROR_NONE if the preferred connection params were set - * correctly. - */ - virtual ble_error_t setPreferredConnectionParams( - const ConnectionParams_t *params - ) { - /* Avoid compiler warnings about unused variables. */ - (void)params; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Update connection parameters of an existing connection. - * - * In the central role, this initiates a Link Layer connection parameter - * update procedure. In the peripheral role, this sends the corresponding - * L2CAP request and waits for the central to perform the procedure. - * - * @param[in] handle Connection Handle. - * @param[in] params Pointer to desired connection parameters. - * - * @return BLE_ERROR_NONE if the connection parameters were updated correctly. - */ - virtual ble_error_t updateConnectionParams( - Handle_t handle, - const ConnectionParams_t *params - ) { - /* avoid compiler warnings about unused variables */ - (void)handle; - (void)params; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the device name characteristic in the Generic Access - * Service. - * - * @param[in] deviceName The new value for the device-name. This is a - * UTF-8 encoded, NULL-terminated string. - * - * @return BLE_ERROR_NONE if the device name was set correctly. - */ - virtual ble_error_t setDeviceName(const uint8_t *deviceName) { - /* Avoid compiler warnings about unused variables. */ - (void)deviceName; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the value of the device name characteristic in the Generic Access - * Service. - * - * To obtain the length of the deviceName value, this function is - * invoked with the @p deviceName parameter set to NULL. - * - * @param[out] deviceName Pointer to an empty buffer where the UTF-8 - * non NULL-terminated string is placed. - * - * @param[in,out] lengthP Length of the @p deviceName buffer. If the device - * name is successfully copied, then the length of the device name - * string (excluding the null terminator) replaces this value. - * - * @return BLE_ERROR_NONE if the device name was fetched correctly from the - * underlying BLE stack. - * - * @note If the device name is longer than the size of the supplied buffer, - * length returns the complete device name length and not the number of - * bytes actually returned in deviceName. The application may use this - * information to retry with a suitable buffer size. - */ - virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) - { - /* avoid compiler warnings about unused variables */ - (void)deviceName; - (void)lengthP; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the appearance characteristic in the GAP service. - * - * @param[in] appearance The new value for the device-appearance. - * - * @return BLE_ERROR_NONE if the new appearance was set correctly. - */ - virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) - { - /* Avoid compiler warnings about unused variables. */ - (void)appearance; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the value of the appearance characteristic in the GAP service. - * - * @param[out] appearanceP The current device-appearance value. - * - * @return BLE_ERROR_NONE if the device-appearance was fetched correctly - * from the underlying BLE stack. - */ - virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) - { - /* Avoid compiler warnings about unused variables. */ - (void)appearanceP; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the radio's transmit power. - * - * @param[in] txPower Radio's transmit power in dBm. - * - * @return BLE_ERROR_NONE if the new radio's transmit power was set - * correctly. - */ - virtual ble_error_t setTxPower(int8_t txPower) - { - /* Avoid compiler warnings about unused variables. */ - (void)txPower; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Query the underlying stack for allowed Tx power values. - * - * @param[out] valueArrayPP Receive the immutable array of Tx values. - * @param[out] countP Receive the array's size. - */ - virtual void getPermittedTxPowerValues( - const int8_t **valueArrayPP, size_t *countP - ) { - /* Avoid compiler warnings about unused variables. */ - (void)valueArrayPP; - (void)countP; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - *countP = 0; - } - - /** - * Get the maximum size of the whitelist. - * - * @return Maximum size of the whitelist. - * - * @note If using Mbed OS, you can configure the size of the whitelist by - * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. - */ - virtual uint8_t getMaxWhitelistSize(void) const - { - return 0; - } - - /** - * Get the Link Layer to use the internal whitelist when scanning, - * advertising or initiating a connection depending on the filter policies. - * - * @param[in,out] whitelist Define the whitelist instance which is used - * to store the whitelist requested. In input, the caller provisions memory. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * copied into the supplied reference. - */ - virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the whitelist to be used during GAP procedures. - * - * @param[in] whitelist A reference to a whitelist containing the addresses - * to be copied to the internal whitelist. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * populated with the addresses in the given whitelist. - * - * @note The whitelist must not contain addresses of type @ref - * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This - * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might - * change its private address at any time, and it is not possible to resolve - * it. - * - * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), - * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. - */ - virtual ble_error_t setWhitelist(const Whitelist_t &whitelist) - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the advertising policy filter mode to be used during the next - * advertising procedure. - * - * @param[in] mode New advertising policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - */ - virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the scan policy filter mode to be used during the next scan procedure. - * - * @param[in] mode New scan policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - */ - virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the initiator policy filter mode to be used during the next connection - * initiation. - * - * @param[in] mode New initiator policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - */ - virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the current advertising policy filter mode. - * - * @return The current advertising policy filter mode. - */ - virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const - { - return ADV_POLICY_IGNORE_WHITELIST; - } - - /** - * Get the current scan policy filter mode. - * - * @return The current scan policy filter mode. - */ - virtual ScanningPolicyMode_t getScanningPolicyMode(void) const - { - return SCAN_POLICY_IGNORE_WHITELIST; - } - - /** - * Get the current initiator policy filter mode. - * - * @return The current scan policy filter mode. - */ - virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const - { - return INIT_POLICY_IGNORE_WHITELIST; - } - -protected: - /* Override the following in the underlying adaptation layer to provide the - functionality of scanning. */ - - /** - * Start scanning procedure in the underlying BLE stack. - * - * @param[in] scanningParams Parameters of the scan procedure. - * - * @return BLE_ERROR_NONE if the scan procedure was successfully started. - */ - virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) - { - (void)scanningParams; - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /* - * APIs with nonvirtual implementations. - */ + /* this block contains non-virtual helper functions for setting scan parameters */ public: - /** - * Get the current advertising and connection states of the device. - * - * @return The current GAP state of the device. - */ - GapState_t getState(void) const - { - return state; - } - - /** - * Set the advertising type to use during the advertising procedure. - * - * @param[in] advType New type of advertising to use. - */ - void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType) - { - _advParams.setAdvertisingType(advType); - } - - /** - * Set the advertising interval. - * - * @param[in] interval Advertising interval in units of milliseconds. - * Advertising is disabled if interval is 0. If interval is smaller than - * the minimum supported value, then the minimum supported value is used - * instead. This minimum value can be discovered using - * getMinAdvertisingInterval(). - * - * This field must be set to 0 if connectionMode is equal - * to ADV_CONNECTABLE_DIRECTED. - * - * @note Decreasing this value allows central devices to detect a - * peripheral faster, at the expense of the radio using more power - * due to the higher data transmit rate. - */ - void setAdvertisingInterval(uint16_t interval) - { - if (interval == 0) { - stopAdvertising(); - } else if (interval < getMinAdvertisingInterval()) { - interval = getMinAdvertisingInterval(); - } - _advParams.setInterval(interval); - } - - /** - * Set the advertising duration. - * - * A timeout event is genenerated once the advertising period expired. - * - * @param[in] timeout Advertising timeout (in seconds) between 0x1 and 0x3FFF. - * The special value 0 may be used to disable the advertising timeout. - */ - void setAdvertisingTimeout(uint16_t timeout) - { - _advParams.setTimeout(timeout); - } - - /** - * Start the advertising procedure. - * - * @return BLE_ERROR_NONE if the device started advertising successfully. - */ - ble_error_t startAdvertising(void) - { - ble_error_t rc; - if ((rc = startAdvertising(_advParams)) == BLE_ERROR_NONE) { - state.advertising = 1; - } - return rc; - } - - /** - * Reset the value of the advertising payload advertised. - */ - void clearAdvertisingPayload(void) - { - _advPayload.clear(); - setAdvertisingData(_advPayload, _scanResponse); - } - - /** - * Set gap flags in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addFlags(flags); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] flags The flags to be added. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - */ - ble_error_t accumulateAdvertisingPayload(uint8_t flags) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addFlags(flags)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } - - /** - * Set the appearance field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addAppearance(app); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] app The appearance to advertise. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - */ - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addAppearance(app)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } - - /** - * Set the Tx Power field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addTxPower(power); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] power Transmit power in dBm used by the controller to advertise. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - */ - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addTxPower(power)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } - - /** - * Add a new field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addData(type, data, len); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] type Identity of the field being added. - * @param[in] data Buffer containing the value of the field. - * @param[in] len Length of the data buffer. - * - * @return BLE_ERROR_NONE if the advertisement payload was updated based on - * matching AD type; otherwise, an appropriate error. - * - * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the - * supplied value is appended to the values previously added to the payload. - */ - ble_error_t accumulateAdvertisingPayload( - GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } - - /** - * Update a particular field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.updateData(type, data, len); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * - * @param[in] type Id of the field to update. - * @param[in] data data buffer containing the new value of the field. - * @param[in] len Length of the data buffer. - * - * @note If advertisements are enabled, then the update takes effect - * immediately. - * - * @return BLE_ERROR_NONE if the advertisement payload was updated based on - * matching AD type; otherwise, an appropriate error. - */ - ble_error_t updateAdvertisingPayload( - GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } - - /** - * Set the value of the payload advertised. - * - * @param[in] payload A reference to a user constructed advertisement - * payload to set. - * - * @return BLE_ERROR_NONE if the advertisement payload was successfully - * set. - */ - ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) - { - ble_error_t rc = setAdvertisingData(payload, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = payload; - } - - return rc; - } - - /** - * Get a reference to the current advertising payload. - * - * @return A reference to the current advertising payload. - */ - const GapAdvertisingData &getAdvertisingPayload(void) const - { - return _advPayload; - } - - /** - * Add a new field in the advertising payload. - * - * @param[in] type AD type identifier. - * @param[in] data buffer containing AD data. - * @param[in] len Length of the data buffer. - * - * @return BLE_ERROR_NONE if the data was successfully added to the scan - * response payload. - */ - ble_error_t accumulateScanResponse( - GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData scanResponseCopy = _scanResponse; - ble_error_t rc; - if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(_advPayload, scanResponseCopy); - if (rc == BLE_ERROR_NONE) { - _scanResponse = scanResponseCopy; - } - - return rc; - } - - /** - * Reset the content of the scan response. - * - * @note This should be followed by a call to Gap::setAdvertisingPayload() - * or Gap::startAdvertising() before the update takes effect. - */ - void clearScanResponse(void) { - _scanResponse.clear(); - setAdvertisingData(_advPayload, _scanResponse); - } /** * Set the parameters used during a scan procedure. @@ -2398,65 +1464,442 @@ public: return BLE_ERROR_NONE; } - /** - * Start the scanning procedure. - * - * Packets received during the scan procedure are forwarded to the - * scan packet handler passed as argument to this function. - * - * @param[in] callback Advertisement packet event handler. Upon reception - * of an advertising packet, the packet is forwarded to @p callback. - * - * @return BLE_ERROR_NONE if the device successfully started the scan - * procedure. - * - * @note The parameters used by the procedure are defined by setScanParams(). - */ - ble_error_t startScan( - void (*callback)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (callback) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(callback); - } - } +protected: + /* Override the following in the underlying adaptation layer to provide the + * functionality of scanning. */ - return err; + /** + * Start scanning procedure in the underlying BLE stack. + * + * @param[in] scanningParams Parameters of the scan procedure. + * + * @return BLE_ERROR_NONE if the scan procedure was successfully started. + */ + virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) + { + (void)scanningParams; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + +public: + /* filtering policy */ + + /** + * Get the maximum size of the whitelist. + * + * @return Maximum size of the whitelist. + * + * @note If using Mbed OS, you can configure the size of the whitelist by + * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. + */ + virtual uint8_t getMaxWhitelistSize(void) const + { + return 0; } /** - * Start the scanning procedure. + * Get the Link Layer to use the internal whitelist when scanning, + * advertising or initiating a connection depending on the filter policies. * - * Packets received during the scan procedure are forwarded to the - * scan packet handler passed as argument to this function. + * @param[in,out] whitelist Define the whitelist instance which is used + * to store the whitelist requested. In input, the caller provisions memory. * - * @param[in] object Instance used to invoke @p callbackMember. - * - * @param[in] callbackMember Advertisement packet event handler. Upon - * reception of an advertising packet, the packet is forwarded to @p - * callback invoked from @p object. - * - * @return BLE_ERROR_NONE if the device successfully started the scan - * procedure. - * - * @note The parameters used by the procedure are defined by setScanParams(). + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * copied into the supplied reference. */ - template - ble_error_t startScan( - T *object, - void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (object && callbackMember) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(object, callbackMember); - } - } + virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const + { + (void) whitelist; + return BLE_ERROR_NOT_IMPLEMENTED; + } - return err; + /** + * Set the value of the whitelist to be used during GAP procedures. + * + * @param[in] whitelist A reference to a whitelist containing the addresses + * to be copied to the internal whitelist. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * populated with the addresses in the given whitelist. + * + * @note The whitelist must not contain addresses of type @ref + * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This + * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might + * change its private address at any time, and it is not possible to resolve + * it. + * + * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), + * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. + */ + virtual ble_error_t setWhitelist(const Whitelist_t &whitelist) + { + (void) whitelist; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the current scan policy filter mode. + * + * @return The current scan policy filter mode. + */ + virtual ScanningPolicyMode_t getScanningPolicyMode(void) const + { + return ble::SCAN_POLICY_IGNORE_WHITELIST; + } + + /** + * Set the scan policy filter mode to be used during the next scan procedure. + * + * @param[in] mode New scan policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + */ + virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the initiator policy filter mode to be used during the next connection + * initiation. + * + * @param[in] mode New initiator policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + */ + virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the current initiator policy filter mode. + * + * @return The current scan policy filter mode. + */ + virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const + { + return INIT_POLICY_IGNORE_WHITELIST; + } + + /* connecting */ + + uint8_t getConnectionCount() { + return connectionCount; + } + + /** + * Initiate a connection to a peer. + * + * Once the connection is established, a ConnectionCallbackParams_t event is + * emitted to handlers that have been registered with onConnection(). + * + * @param[in] peerAddr MAC address of the peer. It must be in LSB format. + * @param[in] peerAddrType Address type of the peer. It is usually obtained + * from advertising frames. + * @param[in] connectionParams Connection parameters to use. + * @param[in] scanParams Scan parameters used to find the peer. + * + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. + */ + virtual ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + PeerAddressType_t peerAddrType, + const ConnectionParams_t *connectionParams1M, + const GapScanningParams *scanParams1M, + const ConnectionParams_t *connectionParams2M = NULL, + const GapScanningParams *scanParams2M = NULL, + const ConnectionParams_t *connectionParamsCoded = NULL, + const GapScanningParams *scanParamsCoded = NULL + ) { + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams1M; + (void)scanParams1M; + (void)connectionParams2M; + (void)scanParams2M; + (void)connectionParamsCoded; + (void)scanParamsCoded; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Initiate a disconnection procedure. + * + * Once the disconnection procedure has completed a + * DisconnectionCallbackParams_t, the event is emitted to handlers that + * have been registered with onDisconnection(). + * + * @param[in] reason Reason of the disconnection transmitted to the peer. + * @param[in] connectionHandle Handle of the connection to end. + * + * @return BLE_ERROR_NONE if the disconnection procedure successfully + * started. + */ + virtual ble_error_t disconnect( + Handle_t connectionHandle, + DisconnectionReason_t reason + ) { + (void)connectionHandle; + (void)reason; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Returned the preferred connection parameters exposed in the GATT Generic + * Access Service. + * + * @param[out] params Structure where the parameters are stored. + * + * @return BLE_ERROR_NONE if the parameters were successfully filled into + * @p params. + */ + virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) + { + (void)params; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the value of the preferred connection parameters exposed in the GATT + * Generic Access Service. + * + * A connected peer may read the characteristic exposing these parameters + * and request an update of the connection parameters to accomodate the + * local device. + * + * @param[in] params Value of the preferred connection parameters. + * + * @return BLE_ERROR_NONE if the preferred connection params were set + * correctly. + */ + virtual ble_error_t setPreferredConnectionParams( + const ConnectionParams_t *params + ) { + (void)params; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Update connection parameters of an existing connection. + * + * In the central role, this initiates a Link Layer connection parameter + * update procedure. In the peripheral role, this sends the corresponding + * L2CAP request and waits for the central to perform the procedure. + * + * @param[in] handle Connection Handle. + * @param[in] params Pointer to desired connection parameters. + * + * @return BLE_ERROR_NONE if the connection parameters were updated correctly. + */ + virtual ble_error_t updateConnectionParams( + Handle_t handle, + const ConnectionParams_t *params + ) { + (void)handle; + (void)params; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Read the PHY used by the transmitter and the receiver on a connection. + * + * Once the PHY has been read, it is reported back via the function onPhyRead + * of the event handler registered by the application. + * + * @param connection Handle of the connection for which the PHY being used is + * queried. + * + * @return BLE_ERROR_NONE if the read PHY procedure has been started or an + * appropriate error code. + */ + virtual ble_error_t readPhy(Handle_t connection) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the preferred PHYs to use in a connection. + * + * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no + * preferred PHYs are set and the default value of the subsytem is used. + * + * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no + * preferred PHYs are set and the default value of the subsytem is used. + * + * @return BLE_ERROR_NONE if the preferences have been set or an appropriate + * error code. + */ + virtual ble_error_t setPreferredPhys( + const PhySet_t* txPhys, + const PhySet_t* rxPhys + ) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Update the PHY used by a connection. + * + * Once the update process has been completed, it is reported back to the + * application via the function onPhyUpdateComplete of the event handler + * registered by the application. + * + * @param connection Handle of the connection to update. + * + * @param txPhys Set of PHYs preferred for tx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param codedSymbol Number of symbols used to code a bit when le coded is + * used. If the value is UNDEFINED then the choice is up to the Bluetooth + * subsystem. + * + * @return BLE_ERROR_NONE if the update PHY procedure has been successfully + * started or an error code. + */ + virtual ble_error_t setPhy( + Handle_t connection, + const PhySet_t* txPhys, + const PhySet_t* rxPhys, + CodedSymbolPerBit_t codedSymbol + ) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /* device configuration */ + + /** + * Fetch the current address and its type. + * + * @param[out] typeP Type of the current address set. + * @param[out] address Value of the current address. + * + * @note If privacy is enabled the device address may be unavailable to + * application code. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t getAddress( + BLEProtocol::AddressType_t *typeP, + BLEProtocol::AddressBytes_t address + ) { + (void)typeP; + (void)address; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Return the type of a random address. + * + * @param[in] address The random address to retrieve the type from. The + * address must be ordered in little endian. + * + * @param[out] addressType Type of the address to fill. + * + * @return BLE_ERROR_NONE in case of success or BLE_ERROR_INVALID_PARAM if + * the address in input was not identifiable as a random address. + */ + static ble_error_t getRandomAddressType( + const BLEProtocol::AddressBytes_t address, + RandomAddressType_t* addressType + ); + + /** + * Set the value of the device name characteristic in the Generic Access + * Service. + * + * @param[in] deviceName The new value for the device-name. This is a + * UTF-8 encoded, NULL-terminated string. + * + * @return BLE_ERROR_NONE if the device name was set correctly. + */ + virtual ble_error_t setDeviceName(const uint8_t *deviceName) { + (void)deviceName; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the value of the device name characteristic in the Generic Access + * Service. + * + * To obtain the length of the deviceName value, this function is + * invoked with the @p deviceName parameter set to NULL. + * + * @param[out] deviceName Pointer to an empty buffer where the UTF-8 + * non NULL-terminated string is placed. + * + * @param[in,out] lengthP Length of the @p deviceName buffer. If the device + * name is successfully copied, then the length of the device name + * string (excluding the null terminator) replaces this value. + * + * @return BLE_ERROR_NONE if the device name was fetched correctly from the + * underlying BLE stack. + * + * @note If the device name is longer than the size of the supplied buffer, + * length returns the complete device name length and not the number of + * bytes actually returned in deviceName. The application may use this + * information to retry with a suitable buffer size. + */ + virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) + { + (void)deviceName; + (void)lengthP; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the value of the appearance characteristic in the GAP service. + * + * @param[in] appearance The new value for the device-appearance. + * + * @return BLE_ERROR_NONE if the new appearance was set correctly. + */ + virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) + { + (void)appearance; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the value of the appearance characteristic in the GAP service. + * + * @param[out] appearanceP The current device-appearance value. + * + * @return BLE_ERROR_NONE if the device-appearance was fetched correctly + * from the underlying BLE stack. + */ + virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) + { + (void)appearanceP; + + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; } /** @@ -2474,13 +1917,14 @@ public: * * @return BLE_ERROR_NONE on successful initialization, otherwise an error code. */ - virtual ble_error_t initRadioNotification(void) + virtual ble_error_t initRadioNotification() { - /* Requesting action from porter(s): override this API if this capability - is supported. */ + /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /* privacy */ + /** * Enable or disable privacy mode of the local device. * @@ -2572,66 +2016,7 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } -private: - /** - * Set the advertising data and scan response in the vendor subsytem. - * - * @param[in] advData Advertising data to set. - * @param[in] scanResponse Scan response to set. - * - * @return BLE_ERROR_NONE if the advertising data was set successfully. - * - * @note Must be implemented in vendor port. - */ - virtual ble_error_t setAdvertisingData( - const GapAdvertisingData &advData, - const GapAdvertisingData &scanResponse - ) = 0; - - /** - * Start the advertising procedure. - * - * @param[in] params Advertising parameters to use. - * - * @return BLE_ERROR_NONE if the advertising procedure successfully - * started. - * - * @note Must be implemented in vendor port. - */ - virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) = 0; - -public: - /** - * Get the current advertising parameters. - * - * @return A reference to the current advertising parameters. - */ - GapAdvertisingParams &getAdvertisingParams(void) - { - return _advParams; - } - - /** - * Const alternative to Gap::getAdvertisingParams(). - * - * @return A const reference to the current advertising parameters. - */ - const GapAdvertisingParams &getAdvertisingParams(void) const - { - return _advParams; - } - - /** - * Set the advertising parameters. - * - * @param[in] newParams The new advertising parameters. - */ - void setAdvertisingParams(const GapAdvertisingParams &newParams) - { - _advParams = newParams; - } - - /* Event handlers. */ + /* event handlers */ public: /** @@ -2855,16 +2240,17 @@ public: shutdownCallChain.clear(); /* Clear Gap state */ - state.advertising = 0; - state.connected = 0; - connectionCount = 0; + connectionCount = 0; /* Clear scanning state */ scanningActive = false; + state.advertising = false; + state.connected = false; /* Clear advertising and scanning data */ - _advPayload.clear(); - _scanResponse.clear(); + legacyAdvertisingReset(); + GapScanningParams default_scan_params; + _scanningParams = default_scan_params; /* Clear callbacks */ timeoutCallbackChain.clear(); @@ -2882,21 +2268,19 @@ protected: * Construct a Gap instance. */ Gap() : - _advParams(), - _advPayload(), - _scanningParams(), - _scanResponse(), connectionCount(0), - state(), scanningActive(false), + _scanningParams(), + _advParams(NULL), + _advPayload(NULL), + _scanResponse(NULL), + state(), timeoutCallbackChain(), radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), disconnectionCallChain(), _eventHandler(NULL) { - _advPayload.clear(); - _scanResponse.clear(); } /* Entry points for the underlying stack to report events back to the user. */ @@ -2931,44 +2315,6 @@ public: const uint8_t *localResolvableAddr = NULL ); - /** - * Notify all registered connection event handlers of a connection event. - * - * @attention This function is meant to be called from the BLE stack specific - * implementation when a connection event occurs. - * - * @param[in] handle Handle of the new connection. - * @param[in] role Role of this BLE device in the connection. - * @param[in] peerAddrType Address type of the connected peer. - * @param[in] peerAddr Address of the connected peer. - * @param[in] ownAddrType Address type this device uses for this - * connection. - * @param[in] ownAddr Address this device uses for this connection. - * @param[in] connectionParams Parameters of the connection. - * @param[in] peerResolvableAddr Resolvable address used by the peer. - * @param[in] localResolvableAddr resolvable address used by the local device. - * - * @deprecated The type BLEProtocol::AddressType_t is not suitable when - * privacy is enabled. Use the overload that accepts a PeerAddressType_t - * instead. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." - ) - void processConnectionEvent( - Handle_t handle, - Role_t role, - BLEProtocol::AddressType_t peerAddrType, - const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t ownAddrType, - const BLEProtocol::AddressBytes_t ownAddr, - const ConnectionParams_t *connectionParams, - const uint8_t *peerResolvableAddr = NULL, - const uint8_t *localResolvableAddr = NULL - ); - /** * Notify all registered disconnection event handlers of a disconnection event. * @@ -2982,9 +2328,6 @@ public: { /* Update Gap state */ --connectionCount; - if (!connectionCount) { - state.connected = 0; - } DisconnectionCallbackParams_t callbackParams(handle, reason); disconnectionCallChain.call(&callbackParams); @@ -3011,47 +2354,12 @@ public: const BLEProtocol::AddressBytes_t peerAddr, int8_t rssi, bool isScanResponse, - GapAdvertisingParams::AdvertisingType_t type, + ble::advertising_type_t type, uint8_t advertisingDataLen, const uint8_t *advertisingData, PeerAddressType_t addressType ); - /** - * Forward a received advertising packet to all registered event handlers - * listening for scanned packet events. - * - * @attention This function is meant to be called from the BLE stack specific - * implementation when a disconnection event occurs. - * - * @param[in] peerAddr Address of the peer that has emitted the packet. - * @param[in] rssi Value of the RSSI measured for the received packet. - * @param[in] isScanResponse If true, then the packet is a response to a scan - * request. - * @param[in] type Advertising type of the packet. - * @param[in] advertisingDataLen Length of the advertisement data received. - * @param[in] advertisingData Pointer to the advertisement packet's data. - * @param[in] addressType Type of the address of the peer that has emitted the packet. - * - * @deprecated The type BLEProtocol::AddressType_t is not suitable when - * privacy is enabled. Use the overload that accepts a PeerAddressType_t - * instead. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." - ) - void processAdvertisementReport( - const BLEProtocol::AddressBytes_t peerAddr, - int8_t rssi, - bool isScanResponse, - GapAdvertisingParams::AdvertisingType_t type, - uint8_t advertisingDataLen, - const uint8_t *advertisingData, - BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC - ); - /** * Notify the occurrence of a timeout event to all registered timeout events * handler. @@ -3065,7 +2373,7 @@ public: { if (source == TIMEOUT_SRC_ADVERTISING) { /* Update gap state if the source is an advertising timeout */ - state.advertising = 0; + state.advertising = false; } if (timeoutCallbackChain) { timeoutCallbackChain(source); @@ -3073,41 +2381,20 @@ public: } protected: - /** - * Current advertising parameters. - */ - GapAdvertisingParams _advParams; - - /** - * Current advertising data. - */ - GapAdvertisingData _advPayload; - - /** - * Current scanning parameters. - */ - GapScanningParams _scanningParams; - - /** - * Current scan response. - */ - GapAdvertisingData _scanResponse; /** * Number of open connections. */ uint8_t connectionCount; - /** - * Current GAP state. - */ - GapState_t state; - /** * Active scanning flag. */ bool scanningActive; + /** Current scanning parameters. */ + GapScanningParams _scanningParams; + protected: /** * Callchain containing all registered callback handlers for timeout @@ -3154,6 +2441,1008 @@ private: /* Disallow copy and assignment. */ Gap(const Gap &); Gap& operator=(const Gap &); + + /* ----------------------- anything beyond this line is deprecated ------------------------- */ + + /* backwards compatibility with deprecated functions */ + +protected: + GapAdvertisingParams& getLegacyAdvertisingParams() { + if (!_advParams) { + _advParams = new GapAdvertisingParams(); + } + MBED_ASSERT(_advParams); + return *_advParams; + } + + GapAdvertisingData& getLegacyAdvertisingPayload() { + if (!_advPayload) { + _advPayload = new GapAdvertisingData(); + } + MBED_ASSERT(_advPayload); + return *_advPayload; + } + + GapAdvertisingData& getLegacyAdvertisingScanResponse() { + if (!_scanResponse) { + _scanResponse = new GapAdvertisingData(); + } + MBED_ASSERT(_scanResponse); + return *_scanResponse; + } + + void legacyAdvertisingReset() { + delete _advParams; + _advParams = NULL; + delete _advPayload; + _advPayload = NULL; + delete _scanResponse; + _scanResponse = NULL; + } + + /** Current advertising parameters. */ + GapAdvertisingParams* _advParams; + + /** Current advertising data. */ + GapAdvertisingData* _advPayload; + + /** Current scan response. */ + GapAdvertisingData* _scanResponse; + + /* deprecated types */ + +public: + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::advertising_policy_mode_t ADV_POLICY_IGNORE_WHITELIST = ble::ADV_POLICY_IGNORE_WHITELIST; + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_SCAN_REQS = ble::ADV_POLICY_FILTER_SCAN_REQS; + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_CONN_REQS = ble::ADV_POLICY_FILTER_CONN_REQS; + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_ALL_REQS = ble::ADV_POLICY_FILTER_ALL_REQS; + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::scanning_policy_mode_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; + /** @deprecated Enum have been moved to BLETypes.h */ + static const ble::scanning_policy_mode_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; + + /** + * Description of the states of the device. + * @deprecated This is not meaningful when extended advertising is used, please use + * isAdvertisingActive() and getConnectionCount(). + */ + struct GapState_t { + /** + * If set, the device is currently advertising. + */ + unsigned advertising : 1; + + /** + * If set, the device is connected to at least one other peer. + */ + unsigned connected : 1; + }; + + /* These have been relocated to the class BLEProtocol. */ +public: + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. + */ + typedef BLEProtocol::AddressType_t AddressType_t; + + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. + */ + typedef BLEProtocol::AddressType_t addr_type_t; + + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. The following + * constants have been left in their deprecated state to transparently + * support existing applications that may have used Gap::ADDR_TYPE_*. + */ + enum DeprecatedAddressType_t { + ADDR_TYPE_PUBLIC = BLEProtocol::AddressType::PUBLIC, + ADDR_TYPE_RANDOM_STATIC = BLEProtocol::AddressType::RANDOM_STATIC, + ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE, + ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE + }; + + /** + * Length (in octets) of the BLE MAC address. + */ + static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN; + + /** + * 48-bit address, LSB format. + * + * @deprecated Use BLEProtocol::AddressBytes_t instead. + */ + typedef BLEProtocol::AddressBytes_t Address_t; + + /** + * 48-bit address, LSB format. + * + * @deprecated Use BLEProtocol::AddressBytes_t instead. + */ + typedef BLEProtocol::AddressBytes_t address_t; + + /* deprecated data */ + +protected: + GapState_t state; + + /* deprecated functions */ + +public: + /** + * Start the scanning procedure. + * + * Packets received during the scan procedure are forwarded to the + * scan packet handler passed as argument to this function. + * + * @param[in] callback Advertisement packet event handler. Upon reception + * of an advertising packet, the packet is forwarded to @p callback. + * + * @return BLE_ERROR_NONE if the device successfully started the scan + * procedure. + * + * @note The parameters used by the procedure are defined by setScanParams(). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t startScan( + void (*callback)(const AdvertisementCallbackParams_t *params) + ) { + ble_error_t err = BLE_ERROR_NONE; + if (callback) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(callback); + } + } + + return err; + } + + /** + * Start the scanning procedure. + * + * Packets received during the scan procedure are forwarded to the + * scan packet handler passed as argument to this function. + * + * @param[in] object Instance used to invoke @p callbackMember. + * + * @param[in] callbackMember Advertisement packet event handler. Upon + * reception of an advertising packet, the packet is forwarded to @p + * callback invoked from @p object. + * + * @return BLE_ERROR_NONE if the device successfully started the scan + * procedure. + * + * @note The parameters used by the procedure are defined by setScanParams(). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ); + template + ble_error_t startScan( + T *object, + void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) + ) { + ble_error_t err = BLE_ERROR_NONE; + if (object && callbackMember) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(object, callbackMember); + } + } + + return err; + } + + /** + * Set the device MAC address and type. + * + * The address set is used in subsequent GAP operations: scanning, + * advertising and connection initiation. + * + * @param[in] type Type of the address to set. + * @param[in] address Value of the address to set. It is ordered in + * little endian. This parameter is not considered if the address type + * is RANDOM_PRIVATE_RESOLVABLE or RANDOM_PRIVATE_NON_RESOLVABLE. For those + * types of address, the BLE API itself generates the address. + * + * @note Some implementation may refuse to set a new PUBLIC address. + * @note Random static address set does not change. + * + * @deprecated Starting with mbed-os-5.9.0 this function is deprecated and + * address management is delegated to implementation. Implementations may or + * may not continue to support this function. Compliance with the Bluetooth + * specification and unification of behaviour between implementations are + * the key reasons behind this change: + * - Many implementations do not allow changing of the public address. + * Therefore programs relying on this function are not portable across BLE + * implementations. + * - The Bluetooth specification forbid replacement of the random static + * address; this address can be set once and only once: at startup. + * Depending on the underlying implementation the random address may or + * may not have been set automatically at startup; therefore update of the + * Random Static address after ble initialisation may be a fault. As a + * result calls to this function were not portable. + * Furthermore replacement of the random static address silently + * invalidates the bond stored in the secure database. + + * @return BLE_ERROR_NONE on success. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "Non portable API, use enablePrivacy to enable use of private addresses" + ) + virtual ble_error_t setAddress( + BLEProtocol::AddressType_t type, + const BLEProtocol::AddressBytes_t address + ) { + (void)type; + (void)address; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Initiate a connection to a peer. + * + * Once the connection is established, a ConnectionCallbackParams_t event is + * emitted to handlers that have been registered with onConnection(). + * + * @param[in] peerAddr MAC address of the peer. It must be in LSB format. + * @param[in] peerAddrType Address type of the peer. + * @param[in] connectionParams Connection parameters to use. + * @param[in] scanParams Scan parameters used to find the peer. + * + * @deprecated BLEProtocol::AddressType_t is not able to to carry accurate + * meaning when privacy is in use. Please Uses the connect overload that + * accept a PeerAddressType_t as the peer address type. + * + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "This function won't work if privacy is enabled; You must use the overload " + "accepting PeerAddressType_t." + ) + virtual ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams + ) { + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams; + (void)scanParams; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Initiate a connection to a peer. + * + * @see connect() + * + * @deprecated This funtion overloads Gap::connect( + * const BLEProtocol::Address_t peerAddr, + * BLEProtocol::AddressType_t peerAddrType, + * const ConnectionParams_t *connectionParams, + * const GapScanningParams *scanParams + * ) + * to maintain backward compatibility for changes from Gap::AddressType_t to + * BLEProtocol::AddressType_t. + */ + MBED_DEPRECATED("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead") + ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + DeprecatedAddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams + ); + + /** + * Initiate a disconnection procedure. + * + * @deprecated This version of disconnect() doesn't take a connection handle. + * It works reliably only for stacks that are limited to a single connection. + * Use Gap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) + * instead. + * + * @param[in] reason The reason for disconnection; to be sent back to the peer. + * + * @return BLE_ERROR_NONE if disconnection was successful. + */ + MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") + virtual ble_error_t disconnect(DisconnectionReason_t reason) { + (void)reason; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Notify all registered connection event handlers of a connection event. + * + * @attention This function is meant to be called from the BLE stack specific + * implementation when a connection event occurs. + * + * @param[in] handle Handle of the new connection. + * @param[in] role Role of this BLE device in the connection. + * @param[in] peerAddrType Address type of the connected peer. + * @param[in] peerAddr Address of the connected peer. + * @param[in] ownAddrType Address type this device uses for this + * connection. + * @param[in] ownAddr Address this device uses for this connection. + * @param[in] connectionParams Parameters of the connection. + * @param[in] peerResolvableAddr Resolvable address used by the peer. + * @param[in] localResolvableAddr resolvable address used by the local device. + * + * @deprecated The type BLEProtocol::AddressType_t is not suitable when + * privacy is enabled. Use the overload that accepts a PeerAddressType_t + * instead. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." + ) + void processConnectionEvent( + Handle_t handle, + Role_t role, + BLEProtocol::AddressType_t peerAddrType, + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t ownAddrType, + const BLEProtocol::AddressBytes_t ownAddr, + const ConnectionParams_t *connectionParams, + const uint8_t *peerResolvableAddr = NULL, + const uint8_t *localResolvableAddr = NULL + ); + + /** + * Forward a received advertising packet to all registered event handlers + * listening for scanned packet events. + * + * @attention This function is meant to be called from the BLE stack specific + * implementation when a disconnection event occurs. + * + * @param[in] peerAddr Address of the peer that has emitted the packet. + * @param[in] rssi Value of the RSSI measured for the received packet. + * @param[in] isScanResponse If true, then the packet is a response to a scan + * request. + * @param[in] type Advertising type of the packet. + * @param[in] advertisingDataLen Length of the advertisement data received. + * @param[in] advertisingData Pointer to the advertisement packet's data. + * @param[in] addressType Type of the address of the peer that has emitted the packet. + * + * @deprecated The type BLEProtocol::AddressType_t is not suitable when + * privacy is enabled. Use the overload that accepts a PeerAddressType_t + * instead. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." + ) + void processAdvertisementReport( + const BLEProtocol::AddressBytes_t peerAddr, + int8_t rssi, + bool isScanResponse, + ble::advertising_type_t type, + uint8_t advertisingDataLen, + const uint8_t *advertisingData, + BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC + ); + + /** + * Stop the ongoing advertising procedure. + * + * @note The current advertising parameters remain in effect. + * + * @retval BLE_ERROR_NONE if the advertising procedure has been successfully + * stopped. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t stopAdvertising(void) + { + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the advertising policy filter mode to be used during the next + * advertising procedure. + * + * @param[in] mode New advertising policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the current advertising policy filter mode. + * + * @return The current advertising policy filter mode. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const + { + return ble::ADV_POLICY_IGNORE_WHITELIST; + } + + /** + * Get the current advertising and connection states of the device. + * + * @return The current GAP state of the device. + * + * @deprecated Deprecated since addition of extended advertising support. + * This is not meaningful when extended advertising is used, please use + * isAdvertisingActive() and getConnectionCount(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use isAdvertisingActive() and getConnectionCount()." + ) + GapState_t getState(void) const + { + return state; + } + + /** + * Get the current advertising parameters. + * + * @return A reference to the current advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + GapAdvertisingParams &getAdvertisingParams(void) + { + return getLegacyAdvertisingParams(); + } + + /** + * Const alternative to Gap::getAdvertisingParams(). + * + * @return A const reference to the current advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + const GapAdvertisingParams &getAdvertisingParams(void) const + { + Gap* self = const_cast(this); + return self->getLegacyAdvertisingParams(); + } + + /** + * Set the advertising parameters. + * + * @param[in] newParams The new advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingParams(const GapAdvertisingParams &newParams) + { + getLegacyAdvertisingParams() = newParams; + } + + /** + * Set the advertising type to use during the advertising procedure. + * + * @param[in] advType New type of advertising to use. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingType(ble::advertising_type_t advType) + { + getLegacyAdvertisingParams().setAdvertisingType(advType); + } + + /** + * Set the advertising interval. + * + * @param[in] interval Advertising interval in units of milliseconds. + * Advertising is disabled if interval is 0. If interval is smaller than + * the minimum supported value, then the minimum supported value is used + * instead. This minimum value can be discovered using + * getMinAdvertisingInterval(). + * + * This field must be set to 0 if connectionMode is equal + * to ADV_CONNECTABLE_DIRECTED. + * + * @note Decreasing this value allows central devices to detect a + * peripheral faster, at the expense of the radio using more power + * due to the higher data transmit rate. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingInterval(uint16_t interval) + { + if (interval == 0) { + stopAdvertising(LEGACY_ADVERTISING_HANDLE); + } else if (interval < getMinAdvertisingInterval()) { + interval = getMinAdvertisingInterval(); + } + getLegacyAdvertisingParams().setInterval(interval); + } + + /** + * Set the advertising duration. + * + * A timeout event is genenerated once the advertising period expired. + * + * @param[in] timeout Advertising timeout (in seconds) between 0x1 and 0x3FFF. + * The special value 0 may be used to disable the advertising timeout. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingTimeout(uint16_t timeout) + { + getLegacyAdvertisingParams().setTimeout(timeout); + } + + /** + * Start the advertising procedure. + * + * @return BLE_ERROR_NONE if the device started advertising successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t startAdvertising(void) + { + ble_error_t status = startAdvertising(LEGACY_ADVERTISING_HANDLE); + if (status == BLE_ERROR_NONE) { + state.advertising = true; + } + return status; + } + + /** + * Reset the value of the advertising payload advertised. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void clearAdvertisingPayload(void) + { + getLegacyAdvertisingPayload().clear(); + } + + /** + * Set gap flags in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addFlags(flags); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] flags The flags to be added. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload(uint8_t flags) + { + return getLegacyAdvertisingPayload().addFlags(flags); + } + + /** + * Set the appearance field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addAppearance(app); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] app The appearance to advertise. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) + { + return getLegacyAdvertisingPayload().addAppearance(app); + } + + /** + * Set the Tx Power field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addTxPower(power); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] power Transmit power in dBm used by the controller to advertise. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) + { + return getLegacyAdvertisingPayload().addTxPower(power); + } + + /** + * Add a new field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addData(type, data, len); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] type Identity of the field being added. + * @param[in] data Buffer containing the value of the field. + * @param[in] len Length of the data buffer. + * + * @return BLE_ERROR_NONE if the advertisement payload was updated based on + * matching AD type; otherwise, an appropriate error. + * + * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the + * supplied value is appended to the values previously added to the payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len + ) { + return getLegacyAdvertisingPayload().addData(type, data, len); + } + + /** + * Update a particular field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.updateData(type, data, len); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * + * @param[in] type Id of the field to update. + * @param[in] data data buffer containing the new value of the field. + * @param[in] len Length of the data buffer. + * + * @note If advertisements are enabled, then the update takes effect + * immediately. + * + * @return BLE_ERROR_NONE if the advertisement payload was updated based on + * matching AD type; otherwise, an appropriate error. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t updateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len + ) { + return getLegacyAdvertisingPayload().updateData(type, data, len); + } + + /** + * Set the value of the payload advertised. + * + * @param[in] payload A reference to a user constructed advertisement + * payload to set. + * + * @return BLE_ERROR_NONE if the advertisement payload was successfully + * set. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) + { + getLegacyAdvertisingPayload() = payload; + return BLE_ERROR_NONE; + } + + /** + * Get a reference to the current advertising payload. + * + * @return A reference to the current advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + const GapAdvertisingData &getAdvertisingPayload(void) const + { + Gap* self = const_cast(this); + return self->getLegacyAdvertisingPayload(); + } + + /** + * Add a new field in the advertising payload. + * + * @param[in] type AD type identifier. + * @param[in] data buffer containing AD data. + * @param[in] len Length of the data buffer. + * + * @return BLE_ERROR_NONE if the data was successfully added to the scan + * response payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateScanResponse( + GapAdvertisingData::DataType type, + const uint8_t *data, + uint8_t len + ) { + return getLegacyAdvertisingScanResponse().addData(type, data, len); + } + + /** + * Reset the content of the scan response. + * + * @note This should be followed by a call to Gap::setAdvertisingPayload() + * or Gap::startAdvertising() before the update takes effect. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void clearScanResponse(void) { + getLegacyAdvertisingScanResponse().clear(); + } + + /** + * Set the radio's transmit power. + * + * @param[in] txPower Radio's transmit power in dBm. + * + * @return BLE_ERROR_NONE if the new radio's transmit power was set + * correctly. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t setTxPower(int8_t txPower) + { + (void)txPower; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + +private: + /** + * Set the advertising data and scan response in the vendor subsytem. + * + * @param[in] advData Advertising data to set. + * @param[in] scanResponse Scan response to set. + * + * @return BLE_ERROR_NONE if the advertising data was set successfully. + * + * @note Must be implemented in vendor port. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t setAdvertisingData( + const GapAdvertisingData &advData, + const GapAdvertisingData &scanResponse + ) { + (void) advData; + (void) scanResponse; + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + /** + * Start the advertising procedure. + * + * @param[in] params Advertising parameters to use. + * + * @return BLE_ERROR_NONE if the advertising procedure successfully + * started. + * + * @note Must be implemented in vendor port. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) { + (void) params; + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } }; /** diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 2b8e74d94f..11fd7e452c 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -17,6 +17,9 @@ #ifndef MBED_GAP_ADVERTISING_PARAMS_H__ #define MBED_GAP_ADVERTISING_PARAMS_H__ +#include "BLETypes.h" +#include "BLEProtocol.h" + /** * @addtogroup ble * @{ @@ -28,7 +31,7 @@ * Parameters defining the advertising process. * * Advertising parameters are a triplet of three value: - * - The Advertising mode modeled after AdvertisingType_t. It defines + * - The Advertising mode modeled after ble::advertising_type_t. It defines * if the device is connectable and scannable. This value can be set at * construction time, updated with setAdvertisingType() and queried by * getAdvertisingType(). @@ -69,48 +72,18 @@ public: static const unsigned GAP_ADV_PARAMS_TIMEOUT_MAX = 0x3FFF; /** - * Encapsulates the peripheral advertising modes. - * - * It determine how the device appears to other scanner and peripheral - * devices in the scanning range. - */ - enum AdvertisingType_t { - /** - * Device is connectable, scannable and doesn't expect connection from a - * specific peer. - * - * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. - */ - ADV_CONNECTABLE_UNDIRECTED, - - /** - * Device is connectable and expects connection from a specific peer. - * - * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. - */ - ADV_CONNECTABLE_DIRECTED, - - /** - * Device is scannable but not connectable. - * - * @see Vol 6, Part B, Section 2.3.1.4. - */ - ADV_SCANNABLE_UNDIRECTED, - - /** - * Device is not connectable and not scannable. - * - * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. - */ - ADV_NON_CONNECTABLE_UNDIRECTED - }; - - /** - * Alias for GapAdvertisingParams::AdvertisingType_t. + * Alias for GapAdvertisingParams::ble::advertising_type_t. * * @deprecated Future releases will drop this type alias. */ - typedef enum AdvertisingType_t AdvertisingType; + typedef ble::advertising_type_t AdvertisingType; + + typedef ble::advertising_type_t AdvertisingType_t; + + static const ble::advertising_type_t ADV_CONNECTABLE_UNDIRECTED = ble::ADV_CONNECTABLE_UNDIRECTED; + static const ble::advertising_type_t ADV_CONNECTABLE_DIRECTED = ble::ADV_CONNECTABLE_DIRECTED; + static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; + static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; public: /** @@ -125,7 +98,7 @@ public: * @note If value in input are out of range, they will be normalized. */ GapAdvertisingParams( - AdvertisingType_t advType = ADV_CONNECTABLE_UNDIRECTED, + ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, uint16_t interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, uint16_t timeout = 0 ) : @@ -134,10 +107,10 @@ public: _timeout(timeout) { /* Interval checks. */ - if (_advType == ADV_CONNECTABLE_DIRECTED) { + if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { /* Interval must be 0 in directed connectable mode. */ _interval = 0; - } else if (_advType == ADV_NON_CONNECTABLE_UNDIRECTED) { + } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { /* Min interval is slightly larger than in other modes. */ if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) { _interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; @@ -198,7 +171,7 @@ public: * * @return The advertising type. */ - AdvertisingType_t getAdvertisingType(void) const + ble::advertising_type_t getAdvertisingType(void) const { return _advType; } @@ -239,7 +212,7 @@ public: * * @param[in] newAdvType The new advertising type. */ - void setAdvertisingType(AdvertisingType_t newAdvType) + void setAdvertisingType(ble::advertising_type_t newAdvType) { _advType = newAdvType; } @@ -270,7 +243,7 @@ private: /** * The advertising type. */ - AdvertisingType_t _advType; + ble::advertising_type_t _advType; /** * The advertising interval in ADV duration units (in other words, 0.625ms). @@ -283,6 +256,206 @@ private: uint16_t _timeout; }; +class GapExtendedAdvertisingParams : public GapAdvertisingParams { + GapExtendedAdvertisingParams() + : GapAdvertisingParams(), + _minInterval(0), + _maxInterval(0), + _maxDuration(0), + _peerAddressType(), + _ownAddressType(), + _policy(ble::ADV_POLICY_IGNORE_WHITELIST), + _primaryPhy(ble::phy_t::LE_1M), + _secondaryPhy(ble::phy_t::LE_1M), + _peerAddress(), + _maxEvents(0), + _txPower(0), + _eventNumber(0), + _channel37(1), + _channel38(1), + _channel39(1), + _anonymous(0), + _notifyOnScan(1) { + + } + + bool getAnonymousAdvertising() { + return _anonymous; + } + + void setAnonymousAdvertising( + bool enable + ) { + _anonymous = enable; + } + + ble_error_t getPrimaryAdvertisingInterval( + uint32_t *min /* ms */, + uint32_t *max /* ms */ + ) { + if (!min || !max) { + return BLE_ERROR_INVALID_PARAM; + } + *min = _minInterval; + *max = _maxInterval; + return BLE_ERROR_NONE; + } + + void setPrimaryAdvertisingInterval( + uint32_t min /* ms */, + uint32_t max /* ms */ + ) { + _minInterval = min; + _maxInterval = max; + } + + ble_error_t getPrimaryAdvertisingChannels( + bool *channel37, + bool *channel38, + bool *channel39 + ) { + if (!channel37 || !channel38 || !channel39) { + return BLE_ERROR_INVALID_PARAM; + } + *channel37 = _channel37; + *channel38 = _channel38; + *channel39 = _channel39; + return BLE_ERROR_NONE; + } + + void setPrimaryAdvertisingChannels( + bool channel37, + bool channel38, + bool channel39 + ) { + _channel37 = channel37; + _channel38 = channel38; + _channel39 = channel39; + } + + BLEProtocol::AddressType::Type getOwnAddressType() { + return _ownAddressType; + } + + void setOwnAddressType( + BLEProtocol::AddressType::Type addressType + ) { + _ownAddressType = addressType; + } + + ble_error_t getPeer( + BLEProtocol::AddressBytes_t *address, + ble::peer_address_type_t *addressType + ) { + if (!address || !addressType) { + return BLE_ERROR_INVALID_PARAM; + } + memcpy(address, _peerAddress, sizeof(BLEProtocol::AddressBytes_t)); + *addressType = _peerAddressType; + return BLE_ERROR_NONE; + }; + + void setPeer( + const BLEProtocol::AddressBytes_t address, + ble::peer_address_type_t addressType + ) { + memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); + _peerAddressType = addressType; + }; + + ble::advertising_policy_mode_t getAdvertisingPolicyMode() { + return _policy; + } + + void setAdvertisingPolicyMode( + ble::advertising_policy_mode_t mode + ) { + _policy = mode; + } + + int8_t getAdvertisingTxPower() { + return _txPower; + } + + void setAdvertisingTxPower( + int8_t txPower + ) { + _txPower = txPower; + } + + ble_error_t getAdvertisingPhy( + ble::phy_t *primaryPhy, + ble::phy_t *secondaryPhy + ) { + if (!primaryPhy || !secondaryPhy) { + return BLE_ERROR_INVALID_PARAM; + } + *primaryPhy = _primaryPhy; + *secondaryPhy = _secondaryPhy; + return BLE_ERROR_NONE; + } + + void setAdvertisingPhy( + ble::phy_t primaryPhy, + ble::phy_t secondaryPhy + ) { + _primaryPhy = primaryPhy; + _secondaryPhy = secondaryPhy; + } + + uint8_t getSecondaryAdvertisingMaxSkip() { + return _eventNumber; + } + + void setSecondaryAdvertisingMaxSkip( + uint8_t eventNumber + ) { + _eventNumber = eventNumber; + } + + void enableScanRequestNotification( + bool enable + ) { + _notifyOnScan = enable; + } + + ble_error_t getDuration( + uint32_t *maxDuration /* ms */, + uint8_t *maxEvents + ) { + if (!maxDuration || !maxEvents) { + return BLE_ERROR_INVALID_PARAM; + } + return BLE_ERROR_NONE; + } + + void setDuration( + uint32_t maxDuration /* ms */, + uint8_t maxEvents = 0 + ) { + _maxDuration = maxDuration; + _maxEvents = maxEvents; + } +private: + uint32_t _minInterval; + uint32_t _maxInterval; + uint32_t _maxDuration; + ble::peer_address_type_t _peerAddressType; + BLEProtocol::AddressType_t _ownAddressType; + ble::advertising_policy_mode_t _policy; + ble::phy_t _primaryPhy; + ble::phy_t _secondaryPhy; + BLEProtocol::AddressBytes_t _peerAddress; + uint8_t _maxEvents; + uint8_t _txPower; + uint8_t _eventNumber; + uint8_t _channel37:1; + uint8_t _channel38:1; + uint8_t _channel39:1; + uint8_t _anonymous:1; + uint8_t _notifyOnScan:1; +}; + /** * @} * @} diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 7ff43295c0..70e7247cde 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -206,6 +206,26 @@ public: return _activeScanning; } + /** + * + * @param phy LE_2m is illegal + */ + void setScanningPhy(ble::phy_t phy) { + _phy = phy; + } + + ble::phy_t getScanningPhy() { + return _phy; + } + + ble::scanning_policy_mode_t getScanningPolicy() { + return _mode; + } + + void setScanningPolicy(ble::scanning_policy_mode_t mode) { + _mode = mode; + } + private: /** * Scan interval in units of 625us (between 2.5ms and 10.24s). @@ -227,10 +247,10 @@ private: */ bool _activeScanning; -private: - /* Disallow copy constructor. */ - GapScanningParams(const GapScanningParams &); - GapScanningParams& operator =(const GapScanningParams &in); + /** Primary channel PHY. */ + ble::phy_t _phy; + + ble::scanning_policy_mode_t _mode; }; /** diff --git a/features/FEATURE_BLE/source/GapScanningParams.cpp b/features/FEATURE_BLE/source/GapScanningParams.cpp index 1d9f1cb26f..d0ca1acc58 100644 --- a/features/FEATURE_BLE/source/GapScanningParams.cpp +++ b/features/FEATURE_BLE/source/GapScanningParams.cpp @@ -21,7 +21,9 @@ GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_ _interval(MSEC_TO_SCAN_DURATION_UNITS(interval)), _window(MSEC_TO_SCAN_DURATION_UNITS(window)), _timeout(timeout), - _activeScanning(activeScanning) { + _activeScanning(activeScanning), + _phy(ble::phy_t::LE_1M), + _mode(ble::SCAN_POLICY_IGNORE_WHITELIST) { /* stay within limits */ if (_interval < SCAN_INTERVAL_MIN) { _interval = SCAN_INTERVAL_MIN; From 1f2ee0d8738becc45ac7bb0d50b7df69cfefe0c2 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 6 Nov 2018 10:57:19 +0000 Subject: [PATCH 002/361] missing include --- features/FEATURE_BLE/ble/GapAdvertisingParams.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 11fd7e452c..16f9970b56 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -19,6 +19,7 @@ #include "BLETypes.h" #include "BLEProtocol.h" +#include "blecommon.h" /** * @addtogroup ble From ff68c94ec277804f349e07fceae4080a515a9598 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 6 Nov 2018 13:53:44 +0000 Subject: [PATCH 003/361] update state on disconnect fix --- features/FEATURE_BLE/ble/Gap.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index dc0c7944c4..c8ed0e7075 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -2328,6 +2328,7 @@ public: { /* Update Gap state */ --connectionCount; + state.connected = false; DisconnectionCallbackParams_t callbackParams(handle, reason); disconnectionCallChain.call(&callbackParams); From 74cf30545294f1eda3a9ddbe939a5f0e856c4f29 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 6 Nov 2018 14:11:08 +0000 Subject: [PATCH 004/361] Add PAL declaration for extended and periodic advertising --- features/FEATURE_BLE/ble/pal/GapTypes.h | 414 +++++++++++- features/FEATURE_BLE/ble/pal/PalGap.h | 835 ++++++++++++++++++++++++ 2 files changed, 1248 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 2dc6c0deff..e3843bd011 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -409,7 +409,6 @@ struct initiator_policy_t : SafeEnum { SafeEnum(value) { } }; - /** * Hold advertising data. */ @@ -531,6 +530,419 @@ struct connection_role_t : SafeEnum { connection_role_t(type value) : SafeEnum(value) { } }; +/** + * Handle of an advertising set. + * + * @note Range of valid handle is comprised between 0x00 and 0xEF. + */ +typedef uint8_t advertising_handle_t; + +/** + * Properties of an advertising event. + */ +struct advertising_event_properties_t { + /** + * Default constructor, all fields sets to 0. + */ + advertising_event_properties_t() : + connectable(false), + scannable(false), + directed(false), + high_duty_cycle(false), + use_legacy_pdu(false), + omit_advertisser_address(false), + include_tx_power(false) + { } + + /** + * Construct an advertising_event_properties_t with all fields defined by + * user. + * @param connectable @see advertising_event_properties_t::connectable + * @param scannable @see advertising_event_properties_t::scannable + * @param directed @see advertising_event_properties_t::directed + * @param high_duty_cycle @see advertising_event_properties_t::high_duty_cycle + * @param use_legacy_pdu @see advertising_event_properties_t::use_legacy_pdu + * @param omit_advertisser_address @see + * advertising_event_properties_t::omit_advertiser_address + * @param include_tx_power + * @see advertising_event_properties_t::include_tx_power + */ + advertising_event_properties_t( + bool connectable, + bool scannable, + bool directed, + bool high_duty_cycle, + bool use_legacy_pdu, + bool omit_advertisser_address, + bool include_tx_power + ) : + connectable(connectable), + scannable(scannable), + directed(directed), + high_duty_cycle(high_duty_cycle), + use_legacy_pdu(use_legacy_pdu), + omit_advertisser_address(omit_advertisser_address), + include_tx_power(include_tx_power) + { } + + /** + * Construct an advertising_event_property_t from a legacy advertising_type_t. + * + * @param adv_type The legacy advertising type to convert into an + * advertising_event_properties_t. + * + * @note Conversion table can be found in table 7.2 of BLUETOOTH + * SPECIFICATION Version 5.0 | Vol 2, Part E - 7.8.53 . + */ + advertising_event_properties_t(advertising_type_t adv_type) + { + switch ((advertising_type_t::type) adv_type.value()) { + case advertising_type_t::ADV_IND: + connectable = true; + scannable = true; + use_legacy_pdu = true; + break; + case advertising_type_t::ADV_DIRECT_IND: + connectable = true; + directed = true; + use_legacy_pdu = true; + break; + case advertising_type_t::ADV_DIRECT_IND_LOW_DUTY_CYCLE: + connectable = true; + directed = true; + high_duty_cycle = true; + use_legacy_pdu = true; + break; + case advertising_type_t::ADV_SCAN_IND: + scannable = true; + use_legacy_pdu = true; + break; + case advertising_type_t::ADV_NONCONN_IND: + use_legacy_pdu = true; + break; + } + } + + /** + * If set the advertising event is connectable. + */ + bool connectable :1; + + /** + * If set the advertising event is scannable. + */ + bool scannable :1; + + /** + * If set the advertising event targets a specific device. + */ + bool directed :1; + + /** + * If set the directed advertising event operate at a high duty cycle. + */ + bool high_duty_cycle :1; + + /** + * If set advertising packets use legacy advertising PDU format and the + * members omit_advertisser_address and include_tx_power are ignored. + * If not set then: + * - The advertisement can't be both connectable and scannable. + * - High duty cycle directed connectable advertising can't be use. + */ + bool use_legacy_pdu :1; + + /** + * If set omit the advertiser address in all PDUs. + */ + bool omit_advertisser_address :1; + + /** + * If set include the Tx power in the extended advertising header. + */ + bool include_tx_power :1; + + /** + * Construct the value expected by a BT controller. + * @return All fields in a uint16_t understandable by BT stacks. + */ + uint16_t value() { + uint16_t result = 0; + result |= connectable << 0; + result |= scannable << 1; + result |= directed << 2; + result |= high_duty_cycle << 3; + result |= use_legacy_pdu << 4; + result |= omit_advertisser_address << 5; + result |= include_tx_power << 6; + return result; + } +}; + +/** + * Describe advertising interval for undirected and low duty cycle directed + * advertising. + * + * The value is not expressed in seconds; one unit is equal to 0.625ms. + * + * The value range is comprised between 0x20 and 0xFFFFFF which translate into + * 20ms to 10,485.759375s . + */ +typedef uint32_t advertising_interval_t; + +/** + * Describe the advertising power. + * + * Value comprised between -127 and +126 are considered power values in dBm while + * the special value 127 can be used as a wildcard to indicates that the host + * has no preference or if the power informtion is not available. + */ +typedef int8_t advertising_power_t; + +/** + * Describe advertising interval for periodic advertising + * + * The value is not expressed in seconds; one unit is equal to 1.25ms. + * + * The value range is comprised between 0x6 and 0xFFFF which translate into + * 7.5ms to 81.91875 s . + */ +typedef uint16_t periodic_advertising_interval_t; + + +// Range -127 <= N <= +20 +// Special value: 127 +// - RSSI not available. +typedef int8_t rssi_t; + +/** + * Description of an advertising fragment. + */ +struct advertising_fragment_description_t : + SafeEnum{ + + enum type { + /** + * Intermediate fragment of fragmented extended advertising data. + */ + INTERMEDIATE_FRAGMENT = 0x00, + + /** + * First fragment of fragmented extended advertising data. + * + * @note If use, it discard existing fragments. + */ + FIRST_FRAGMENT = 0x01, + + /** + * Last fragment of fragmented extended advertising data. + */ + LAST_FRAGMENT = 0x02, + + /** + * Complete extended advertising data. This is also used for legacy + * advertising data. + * + * @note If use, it discard existing fragments. + */ + COMPLETE_FRAGMENT = 0x03, + + /** + * Used to update the advertising DID. + * + * @note should not be used if advertising is disabled o + */ + UNCHANGED_DATA = 0x04 + }; + + /** + * Construct a new advertising_fragment_description_t value. + */ + advertising_fragment_description_t(type value) : + SafeEnum(value) { } +}; + +struct duplicates_filter_t : SafeEnum{ + enum type { + /** + * Disable duplicate filtering. + */ + DISABLE, + + /** + * Enable duplicate filtering. + */ + ENABLE, + + /** + * Enable duplicate filtering, reset the cache periodicaly. + */ + PERIODIC_RESET + }; + + /** + * Construct a new duplicates_filter_t value. + */ + duplicates_filter_t(type value) : + SafeEnum(value) { } +}; + +/** + * Identify a periodic advertising sync. + */ +typedef uint16_t sync_handle_t; + +/** + * Identify an advertising SID. Range: [0x00, 0x0F] + */ +typedef uint8_t advertising_sid_t; + +struct advertising_data_status_t : SafeEnum{ + enum type { + COMPLETE = 0x00, + INCOMPLETE_MORE_DATA = 0x01, + INCOMPLETE_DATA_TRUNCATED = 0x02 + }; + + /** + * Construct a new duplicates_filter_t value. + */ + advertising_data_status_t(type value) : + SafeEnum(value) { } +}; + +struct extended_advertising_report_event_type_t { + extended_advertising_report_event_type_t(uint8_t value) : value(value) { } + + bool connectable() { + return value & (1 << 0); + } + + bool scannable_advertising() { + return value & (1 << 1); + } + + bool directed_advertising() { + return value & (1 << 2); + } + + bool scan_response() { + return value & (1 << 3); + } + + bool legacy_advertising() { + return value & (1 << 4); + } + + advertising_data_status_t data_status() { + return static_cast((value >> 5) & 0x03); + } + + bool complete() { + return data_status() == advertising_data_status_t::COMPLETE; + } + + bool more_data_to_come() { + return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; + } + + bool truncated() { + return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; + } + +private: + uint8_t value; +}; + +struct direct_address_type_t : SafeEnum { + enum type { + /** + * Public device address + */ + PUBLIC_ADDRESS = 0x00, + + /** + * Random device address + */ + RANDOM_ADDRESS = 0x01, + + /** + * Public identity address. + * @note remove once privacy mode is supported. + */ + PUBLIC_IDENTITY_ADDRESS = 0x02, + + /** + * Random (static) identity address. + * @note remove once privacy mode is supported. + */ + RANDOM_IDENTITY_ADDRESS = 0x03, + + /** + * Random device address; controller unable to resolve. + */ + RANDOM_DEVICE_ADDRESS = 0xFE + }; + + /** + * Construct a new direct_address_type_t instance. + */ + direct_address_type_t(type value) : + SafeEnum(value) { } +}; + +/** + * Accuracy of the master clock. + */ +struct clock_accuracy_t : SafeEnum{ + enum type { + /** + * 500 PPM + */ + PPM_500 = 0x00, + + /** + * 250 PPM + */ + PPM_250 = 0x01, + + /** + * 150 PPM + */ + PPM_150 = 0x02, + + /** + * 100 PPM + */ + PPM_100 = 0x03, + + /** + * 75 PPM + */ + PPM_75 = 0x04, + + /** + * 50 PPM + */ + PPM_50 = 0x05, + + /** + * 30 PPM + */ + PPM_30 = 0x06, + + /** + * 20 PPM + */ + PPM_20 = 0x07 + }; + + /** + * Construct a new clock_accuracy_t value. + */ + clock_accuracy_t(type value) : SafeEnum(value) { } +}; + } // namespace pal } // namespace ble diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index a32b0ebbf8..f9000d3073 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -80,6 +80,176 @@ struct Gap { ble::phy_t tx_phy, ble::phy_t rx_phy ) = 0; + + /** + * Should be invoked by the Gap implementation when an enhanced + * connection complete event happens. + * + * @param status hci_error_code::SUCCESS in case of success or an error + * code. + * + * @param connection_handle The handle of the connection created. + * + * @param own_role Indicate if the local device operates as slave or + * master. + * + * @param peer_address_type Type of address of the peer. + * + * @param peer_address Address of the peer connected. + * + * @param local_resolvable_private_address Resolvable private address + * being used by the controller. If not applicable, the address is full + * of zeroes. + * + * @param peer_resolvable_private_address Resolvable private address + * being used by the peer. If not applicable, the address is full of + * zeroes. + * + * @param connection_interval Interval between two connection events. + * Unit is 1.25ms. + * + * @param connection_latency Slave latency for the connection in number + * of connection events. + * + * @param supervision_timeout Connection supervision timeout. Unit is + * 10ms. + * + * @param master_clock_accuracy This parameter is only valid for a slave. + * On a master it must be set to 0x00. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.7.65.10 LE enhanced connection + * complete event. + */ + virtual void on_enhanced_connection_complete( + hci_error_code_t status, + connection_handle_t connection_handle, + connection_role_t own_role, + connection_peer_address_type_t peer_address_type, + const address_t &peer_address, + const address_t &local_resolvable_private_address, + const address_t &peer_resolvable_private_address, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout, + clock_accuracy_t master_clock_accuracy + ) = 0; + + /** + * Should be invoked by the Gap implementation when an extended + * advertising report event happens. + * + * @param event_type + * @param address_type + * @param address + * @param primary_phy + * @param secondary_phy + * @param advertising_sid + * @param tx_power + * @param rssi + * @param periodic_advertising_interval + * @param direct_address_type + * @param direct_address + * @param data_length + * @param data_size + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.7.65.13 LE extended advertising + * report event. + */ + virtual void on_extended_advertising_report( + extended_advertising_report_event_type_t event_type, + const connection_peer_address_type_t *address_type, + const address_t &address, + phy_t primary_phy, + const phy_t *secondary_phy, + advertising_sid_t advertising_sid, + advertising_power_t tx_power, + rssi_t rssi, + uint16_t periodic_advertising_interval, + direct_address_type_t direct_address_type, + const address_t &direct_address, + uint8_t data_length, + const uint8_t *data_size + ) = 0; + + /** + * TODO + * @param error + * @param sync_handle + * @param advertising_sid + * @param advertiser_address_type + * @param advertiser_address + * @param periodic_advertising_interval + * @param clock_accuracy + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.7.65.14 LE extended advertising + * report event. + */ + virtual void on_periodic_advertising_sync_established( + hci_error_code_t error, + sync_handle_t sync_handle, + advertising_sid_t advertising_sid, + connection_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint16_t periodic_advertising_interval, + clock_accuracy_t clock_accuracy + ) = 0; + + /** + * TODO + * @param sync_handle + * @param tx_power + * @param rssi + * @param data_status + * @param data_length + * @param data + */ + virtual void on_periodic_advertising_report( + sync_handle_t sync_handle, + advertising_power_t tx_power, + rssi_t rssi, + advertising_data_status_t data_status, + uint8_t data_length, + const uint8_t *data + ) = 0; + + /** + * TODO + * @param sync_handle + */ + virtual void on_periodic_advertising_sync_loss( + sync_handle_t sync_handle + ) = 0; + + /** + * TODO + */ + virtual void on_scan_timeout() = 0; + + /** + * TODO + * @param status + * @param advertising_handle + * @param connection_handle + * @param number_of_completed_extended_advertising_events + */ + virtual void on_advertising_set_terminated( + hci_error_code_t status, + advertising_handle_t advertising_handle, + connection_handle_t connection_handle, + uint8_t number_of_completed_extended_advertising_events + ) = 0; + + /** + * TODO + * @param advertising_handle + * @param scanner_address_type + * @param address + */ + virtual void on_scan_request_received( + advertising_handle_t advertising_handle, + connection_peer_address_type_t scanner_address_type, + const address_t &address + ) = 0; }; /** @@ -141,6 +311,31 @@ struct Gap { */ virtual ble_error_t set_random_address(const address_t& address) = 0; + /** + * Set the random device address used by an advertising set. + * + * @pre No connectable advertising set should be enabled. + * + * @post The new random address should be used when @p advertising_set_handle + * is enabled. + * + * @param advertising_handle Handle to the advertising set that will be + * advertised with the address @p address. + * + * @param address The random address to use when @p advertising_set_handle + * is in use. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note See Bluetooth 5 Vol 2, Part E: 7.8.52 LE Set Advertising Set Random + * Address Command + */ + virtual ble_error_t set_advertising_set_random_address( + advertising_handle_t advertising_handle, + const address_t &address + ) = 0; + /** * Set the advertising parameters which will be used during the advertising * process. @@ -209,6 +404,116 @@ struct Gap { advertising_filter_policy_t advertising_filter_policy ) = 0; + /** + * Define the advertising parameters of an advertising set. + * + * @param advertising_handle Identify the advertising set being configured. + * + * @param event_properties Describe the type of advertising event and its + * properties. + * + * @param primary_advertising_interval_min, primary_advertising_interval_max + * Advertising interval range for undirected and low duty cycle advertising. + * This parameter is not considered if @p event_properties.high_duty_cycle is + * set. + * + * @param primary_advertising_channel_map Map of the advertising channel to + * use while advertising. + * + * @param own_address_type The type of address being used by the local + * controller. If this parameter is a resolvable address then the peer + * address should be an identity address. + * + * @param peer_address_type, peer_address Address of the peer. This parameter + * is not evaluated if @p event_properties.directed is not set. + * + * @param advertising_filter_policy Filter applied to scan and connection + * requests. It is ignored for directed advertising (@p + * event_properties.directed set). + * + * @param advertising_power Maximum power level used during advertising. + * The controller select a power level lower than or equal to this value. + * The special value 127 should be used if the host as no preference towards + * the transmit power used. + * + * @param primary_advertising_phy PHY used to transmit data on the primary + * advertising channel. Accepted values are: phy_t::LE_1M and phy_t::LE_CODED. + * + * @param secondary_advertising_max_skip Maximum number of advertising events + * that can be skipped before the AUX_ADV_IND can be sent. + * + * @param secondary_phy PHY used to transmit data on the secondary advertising + * channel. + * + * @param advertising_sid 4bit value identifying the advertising set over the + * air. It is not used by legacy advertising. + * + * @param scan_request_notification Indicate if the host wants to receive + * scan request notification events. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.53 LE Set Extended Advertising + * Parameters Command. + * + * @note If the advertising set does not exist on the controller, it is + * created. + * + * @pre @p advertising_handle should not be enabled when this command is + * issued. + */ + virtual ble_error_t set_extended_advertising_parameters( + advertising_handle_t advertising_handle, + advertising_event_properties_t event_properties, + advertising_interval_t primary_advertising_interval_min, + advertising_interval_t primary_advertising_interval_max, + advertising_channel_map_t primary_advertising_channel_map, + own_address_type_t own_address_type, + advertising_peer_address_type_t peer_address_type, + const address_t &peer_address, + advertising_filter_policy_t advertising_filter_policy, + advertising_power_t advertising_power, + phy_t primary_advertising_phy, + uint8_t secondary_advertising_max_skip, + phy_t secondary_phy, + uint8_t advertising_sid, + bool scan_request_notification + ) = 0; + + /** + * Configure periodic advertising parameters of an advertising set. + * + * @pre The advertising handle must exist on the controller @see + * set_extended_advertising_parameters . + * + * @pre Periodic advertising of @p advertising_handle should not be enabled + * when this function is called. + * + * @pre The advertising set identified by @p advertising_handle should not + * be configured as anonymous advertising. + * + * @param advertising_handle The advertising set being configured. + * + * @param periodic_advertising_min, periodic_advertising_max Advertising + * interval range for periodic advertising of this set. + * + * @param advertise_power If true, the transmission power should be included + * in the advertising PDU. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.61 LE Set Periodic Advertising + * Parameters Command + */ + virtual ble_error_t set_periodic_advertising_parameters( + advertising_handle_t advertising_handle, + periodic_advertising_interval_t periodic_advertising_min, + periodic_advertising_interval_t periodic_advertising_max, + bool advertise_power + ) = 0; + /** * Set the data sends in advertising packet. If the advertising is * currently enabled, the data shall be used when a new advertising packet @@ -231,6 +536,77 @@ struct Gap { const advertising_data_t& advertising_data ) = 0; + /** + * Set data in advertising PDUs. + * + * @note this command can be called at anytime, whether the advertising set + * is enabled or not. + * + * @note the extended scan response can be set in one or more command. + * + * @pre @p advertising_handle should exist. To create it call + * set_extended_scan_parameters. + * + * @post The data inserted is used for subsequent advertising events. + * + * @param advertising_handle The handle identifying the advertising set + * associated with the data. + * + * @param operation Description of the operation to apply to @p + * advertising_handle data. + * + * @param minimize_fragmentation Hint for the controller to minimize + * fragmentation of data sent over the air. + * + * @param advertising_data_size, advertising_data The data to associate to @p + * advertising_handle. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.54 LE set extended advertising + * data command. + */ + virtual ble_error_t set_extended_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t advertising_data_size, + const uint8_t *advertising_data + ); + + /** + * Set the data used in periodic advertising PDUs. + * + * @note the extended scan response can be set in one or more command. + * + * @pre @p advertising_handle must exist. See set_extended_advertising_parameters. + * + * @pre @p advertising_handle must be configured for periodic advertising. + * See set_periodic_advertising_parameters . + * + * @param advertising_handle The handle identifying the advertising set + * associated with the data. + * + * @param fragment_description Description of the operation to apply to @p + * advertising_handle data. + * + * @param advertising_data_size, advertising_data The data to associate to @p + * advertising_handle. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.62 LE set periodic advertising + * data command. + */ + virtual ble_error_t set_periodic_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t fragment_description, + uint8_t advertising_data_size, + const uint8_t *advertising_data + ) = 0; + /** * Set the data sends in scan response packets. If the advertising is * currently enabled, the data shall be used when a new scan response is @@ -253,6 +629,39 @@ struct Gap { const advertising_data_t& scan_response_data ) = 0; + /** + * Set the data sends in extended scan response packets. If the advertising + * is currently enabled, the data shall be used when a new extended scan + * response is issued. + * + * @note the extended scan response can be set in one or more command. + * + * @param advertising_handle The advertising handle that owns the scan + * response data. + * + * @param operation Description of the operation to apply to @p + * advertising_handle data. + * + * @param minimize_fragmentation Hint for the controller to minimize + * fragmentation of data sent over the air. + * + * @param scan_response_data_size, scan_response_data The data to associate + * to @p advertising_handle. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.55 LE set extended scan response + * data command. + */ + virtual ble_error_t set_extended_scan_response_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t scan_response_data_size, + const uint8_t *scan_response_data + ); + /** * Start or stop advertising. * @@ -295,6 +704,129 @@ struct Gap { */ virtual ble_error_t advertising_enable(bool enable) = 0; + /** + * Start of stop advertising of extended advertising sets. + * + * @pre advertising handles present in @p handles must exist. + * + * @pre advertising or scan response data must be complete for advertising + * handles in @p handles. + * + * @note Disabling the advertising set identified by @p handle[i] does not + * disable any periodic advertising associated with that set. + * + * @param enable If true, start advertising of the advertising sets pointed + * by @p handles. If false stop advertising for the advertising sets pointed + * by @p handles. + * + * @param number_of_sets Number of advertising sets concerned by the operation. + * @p handles, @p durations and @p max_extended_advertising_events should + * contain @p number_of_sets elements. + * + * @param handles Handle of advertising sets to start or stop. + * + * @param durations Advertising duration for @p handle. The unit is 10ms and + * the special value 0x000 disable advertising timeout. + * + * @param max_extended_advertising_events Maximum number of extended + * advertising events the controller must attempt to send prior to + * terminating the extended advertising. The special value 0 indicate that + * there is no maximum. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.56 LE extended advertising enable + * command. + */ + virtual ble_error_t extended_advertising_enable( + bool enable, + uint8_t number_of_sets, + const advertising_handle_t* handles, + const uint16_t* durations, + const uint8_t* max_extended_advertising_events + ) = 0; + + /** + * Enable or disable periodic advertising of an advertising set. + * + * @param enable If true enable periodic advertising of @p advertising_handle + * otherwise disable it. + * + * @param advertising_handle Handle to the advertising set to enable or + * disable. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.63 LE periodic advertising enable + * command. + */ + virtual ble_error_t periodic_advertising_enable( + bool enable, + advertising_handle_t advertising_handle + ) = 0; + + /** + * Query the maximum data length the controller supports in an advertising + * set. + * + * @return The length in byte the controller can support in an advertising + * set. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.57 LE read maximum advertising + * data length command. + */ + virtual uint16_t get_maximum_advertising_data_length() = 0; + + /** + * Query the maximum number of concurrent advertising sets that is supported + * by the controller. + * + * @return The number of concurrent advertising sets supported by the + * controller. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.58 LE number of supported + * advertising sets command. + */ + virtual uint8_t get_max_number_of_advertising_sets(); + + /** + * Remove an advertising set from the controller. + * + * After this operation, configuration and data associated with @p + * advertising_handle are lost. + * + * @pre @p advertising_handle must exist. + * + * @pre Advertising of @p advertising_handle must be disabled. + * + * @param advertising_handle The advertising handle to destroy. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.59 LE remove advertising set + * command. + */ + virtual ble_error_t remove_advertising_set( + advertising_handle_t advertising_handle + ) = 0; + + /** + * Remove all advertising sets maintained by the controller. + * + * @pre Advertising of all advertising sets must be disabled. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.60 LE clear advertising sets + * command. + */ + virtual ble_error_t clear_advertising_sets() = 0; + + /** * Set the parameter of the scan process. * @@ -330,6 +862,43 @@ struct Gap { scanning_filter_policy_t filter_policy ) = 0; + /** + * Set extended scan parameters to be used on advertising channels. + * + * @param own_address_type Type of the address used in scan requests. + * + * @param filter_policy Scanning filter policy. + * + * @param scanning_phys The phy affected by the parameter change. Just + * LE_1M and LE_CODED can be set. If two phys are set then @p active_scanning, + * @p scan_interval and @p scan_window must contain two elements. The first + * being applied to LE_1M and the second being applied to LE_CODED. + * + * @param active_scanning If true, active scanning is used for the + * correcponding PHY. + * + * @param scan_interval Interval between two subsequent scan. This parameter + * shall be in the range [0x0004 : 0x4000] and is in unit of 0.625ms. + * + * @param scan_window Duration of the LE scan. It shall be less than or + * equal to scan_interval value. This parameter shall be in the range + * [0x0004 : 0x4000] and is in unit of 0.625ms. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.64 LE set extended scan parameters + * command. + */ + virtual ble_error_t set_extended_scan_parameters( + own_address_type_t own_address_type, + scanning_filter_policy_t filter_policy, + phy_set_t scanning_phys, + const bool *active_scanning, + const uint16_t *scan_interval, + const uint16_t *scan_window + ) = 0; + /** * Start/stop scanning process. * @@ -356,6 +925,179 @@ struct Gap { bool filter_duplicates ) = 0; + /** + * Enable or disable extended scanning. + * + * @param enable If true enable scanning and disable it otherwise. + * + * @param filter_duplicates If true filter out duplicate scan reports. + * + * @param duration Duration of the scan operation. The unit is 10ms and + * the special value 0 indicate continuous scan until explicitly disabled. + * + * @param period Interval between two scan operations. The unit is 1.28s and + * the special value 0 can be used to disable periodic scanning. If @p + * filter_duplicates is equal to duplicates_filter_t::PERIODIC_RESET then + * the duplicate cache is reset whenever a scan operation starts. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.65 LE set extended scan enable + * command. + */ + virtual ble_error_t extended_scan_enable( + bool enable, + duplicates_filter_t filter_duplicates, + uint16_t duration, + uint16_t period + ) = 0; + + /** + * Synchronize an observer with a periodic advertising broadcaster. + * + * One the synchronization is establish the function + * EventHandler::on_periodic_advertising_sync_established is called and for + * every periodic advertising received is reported via the function + * EventHandler::on_periodic_advertising_report . + * + * @param use_periodic_advertiser_list Determine if the periodic advertiser + * list is used or ignored. + * + * @param advertising_sid SID to sync with. + * + * @param peer_address_type, peer_address Address of the advertiser. If @p + * use_periodic_advertiser_list is true then these parameters are ignored. + * + * @param allowed_skip Number of periodic advertisement that can be skipped + * after a successful receive by the local device. + * + * @param sync_timeout Specifies the maximum permitted time between two + * successful receives. If this time is exceeded then the synchronization is + * considered lost and EventHandler::on_periodic_advertising_loss is called. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.67 LE periodic advertising create + * sync command. + */ + virtual ble_error_t periodic_advertising_create_sync( + bool use_periodic_advertiser_list, + uint8_t advertising_sid, + peer_address_type_t peer_address_type, + const address_t &peer_address, + uint16_t allowed_skip, + uint16_t sync_timeout + ) = 0; + + /** + * Cancel the establishment of synchronization with a periodic advertising + * broadcaster. + * + * @pre There should be an ongoing sync establishment operation. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.68 LE periodic advertising create + * sync cancel command. + */ + virtual ble_error_t cancel_periodic_advertising_create_sync() = 0; + + /** + * Stop reception of the periodic advertising identified by @p sync_handle. + * + * @param sync_handle The handle identifying the periodic advertiser. It is + * obtained when EventHandler::on_periodic_advertising_sync_established is + * called. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.69 LE periodic advertising + * terminate sync command. + */ + virtual ble_error_t periodic_advertising_terminate_sync( + sync_handle_t sync_handle + ) = 0; + + /** + * Add a device to the periodic advertiser list stored in the controller. + * This list may be used to create a periodic advertiser sync. + * + * @pre The device should not be in the periodic advertiser list. + * + * @pre Create sync operation should not be pending + * + * @pre The periodic advertising list of the controller should not be full. + * + * @param advertiser_address_type The address type of the device to add. + * + * @param advertiser_address The address value of the device to add. + * + * @param advertising_sid The SID field used to identify periodic advertising + * from the device. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.70 LE add device to periodic + * advertising list command. + */ + virtual ble_error_t add_device_to_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid + ) = 0; + + /** + * Remove a device from the periodic advertiser list. + * + * @pre Create sync operation should not be pending + * + * @param advertiser_address_type The address type of the device to remove. + * + * @param advertiser_address The address value of the device to remove. + * + * @param advertising_sid The SID field used to identify periodic advertising + * from the device. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.71 LE remove device from periodic + * advertising list command. + */ + virtual ble_error_t remove_device_from_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid + ) = 0; + + /** + * Clear all devices from the list of periodic advertisers. + * + * @pre Create sync operation should not be pending + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.72 LE clear periodic advertising + * list command. + */ + virtual ble_error_t clear_periodic_advertiser_list() = 0; + + /** + * Return the total number of entries that can be stored by the periodic + * advertiser list. + * + * @return The capacity of the periodic advertiser list. + * + * @note We (wrongfully) assume that value doesn't change over time. + */ + virtual uint8_t read_periodic_advertiser_list_size() = 0; + /** * Create a new le connection to a connectable advertiser. * @@ -442,6 +1184,99 @@ struct Gap { uint16_t maximum_connection_event_length ) = 0; + /** + * Create a new le connection to a connectable advertiser. + * + * @param initiator_policy Used to determine if the whitelist is used to + * determine the address to connect to. If the whitelist is not used, the + * connection shall be made against an advertiser matching the peer_address + * and the peer_address_type parameters. Otherwise those parameters are + * ignored. + * + * @param own_address_type Type of address used in the connection request + * packet. + * + * @param peer_address_type Type of address used by the advertiser. Not used + * if initiator_policy use the whitelist. + * + * @param peer_address Address used by the advertiser in its advertising + * packets. Not used if initiator_policy use the whitelist. + * + * @param initiating_phys Indicates the advertising PHYs and the controller + * may use find the target and establish the connection. Subsequent + * parameters are arrays of value associated with phys present in @p + * initiating_phys. The order of phys is 1M, 2M, Coded. + * + * @param scan_intervals Hint to the le subsystem indicating how + * frequently it should scan for the peer address. It represent the time + * interval between two subsequent scan for the peer. It shall be in the + * range [0x0004 : 0x4000] and the time is in unit of 0.625ms. + * + * @param scan_windows Hint to the le subsystem indicating for how long it + * should scan during a scan interval. The value shall be smaller or equal + * to scan_interval. If it is equal to scan_interval then scanning should + * run continuously. It shall be in the range [0x0004 : 0x4000] and the time + * is in unit of 0.625ms. + * + * @param connection_intervals_min Minimum interval between two connection + * events allowed for the connection. It shall be less than or equal to + * connection_interval_max. This value shall be in range [0x0006 : 0x0C80] + * and is in unit of 1.25ms. + * + * @param connection_intervals_max Maximum interval between two connection + * events allowed for the connection. It shall be greater than or equal to + * connection_interval_min. This value shall be in range [0x0006 : 0x0C80] + * and is in unit of 1.25ms. + * + * @param connection_latencies Number of connection events the slave can drop + * if it has nothing to communicate to the master. This value shall be in + * the range [0x0000 : 0x01F3]. + * + * @param supervision_timeouts Link supervision timeout for the connection. + * It shall be larger than: + * (1 + connection_latency) * connection_interval_max * 2 + * Note: connection_interval_max is in ms in this formulae. + * Everytime the master or the slave receive a valid packet from the peer, + * the supervision timer is reset. If the supervision timer reaches + * supervision_timeout then the connection is considered lost and a + * disconnect event shall be emmited. + * This value shall be in the range [0x000A : 0x0C80] and is in unit of 10 + * ms. + * + * @param minimum_connection_event_lengths Informative parameter of the + * minimum length a connection event. It shall be less than or equal to + * maximum_connection_event_length. It shall be in the range + * [0x0000 : 0xFFFF]. It should also be less than the expected connection + * interval. The unit is 0.625ms. + * + * @param maximum_connection_event_lengths Informative parameter of the + * maximum length a connection event. It shall be more than or equal to + * minimum_connection_event_length. It shall be in the range + * [0x0000 : 0xFFFF]. It should also be less than the expected connection + * interval. The unit is 0.625ms. + * + * @return BLE_ERROR_NONE if the request has been successfully sent or the + * appropriate error otherwise. + * + * @note: See Bluetooth 5 Vol 2 PartE: 7.8.66 LE extended create connection + * command. + */ + virtual ble_error_t extended_create_connection( + initiator_policy_t initiator_policy, + own_address_type_t own_address_type, + peer_address_type_t peer_address_type, + const address_t &peer_address, + phy_set_t initiating_phys, + const uint16_t* scan_intervals, + const uint16_t* scan_windows, + const uint16_t* connection_intervals_min, + const uint16_t* connection_intervals_max, + const uint16_t* connection_latencies, + const uint16_t* supervision_timeouts, + const uint16_t* minimum_connection_event_lengths, + const uint16_t* maximum_connection_event_lengths + ) = 0; + /** * Cancel the ongoing connection creation process. * From d836841e0f1420806df385297c8a9e33f11ad8cb Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 6 Nov 2018 14:48:57 +0000 Subject: [PATCH 005/361] Add missing pure qualifier to PAL GAP APIs. --- features/FEATURE_BLE/ble/pal/PalGap.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index f9000d3073..e9e1eb17cc 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -573,7 +573,7 @@ struct Gap { bool minimize_fragmentation, uint8_t advertising_data_size, const uint8_t *advertising_data - ); + ) = 0; /** * Set the data used in periodic advertising PDUs. @@ -660,7 +660,7 @@ struct Gap { bool minimize_fragmentation, uint8_t scan_response_data_size, const uint8_t *scan_response_data - ); + ) = 0; /** * Start or stop advertising. @@ -789,7 +789,7 @@ struct Gap { * @note: See Bluetooth 5 Vol 2 PartE: 7.8.58 LE number of supported * advertising sets command. */ - virtual uint8_t get_max_number_of_advertising_sets(); + virtual uint8_t get_max_number_of_advertising_sets() = 0; /** * Remove an advertising set from the controller. From 7d9c3d1432d21167260b409ff19487d88287914c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 6 Nov 2018 14:49:41 +0000 Subject: [PATCH 006/361] Improve advertising_event_properties_t constructor. --- features/FEATURE_BLE/ble/pal/GapTypes.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index e3843bd011..a5380052e1 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -594,18 +594,23 @@ struct advertising_event_properties_t { * @note Conversion table can be found in table 7.2 of BLUETOOTH * SPECIFICATION Version 5.0 | Vol 2, Part E - 7.8.53 . */ - advertising_event_properties_t(advertising_type_t adv_type) + advertising_event_properties_t(advertising_type_t adv_type) : + connectable(false), + scannable(false), + directed(false), + high_duty_cycle(false), + use_legacy_pdu(true), + omit_advertisser_address(false), + include_tx_power(false) { switch ((advertising_type_t::type) adv_type.value()) { case advertising_type_t::ADV_IND: connectable = true; scannable = true; - use_legacy_pdu = true; break; case advertising_type_t::ADV_DIRECT_IND: connectable = true; directed = true; - use_legacy_pdu = true; break; case advertising_type_t::ADV_DIRECT_IND_LOW_DUTY_CYCLE: connectable = true; @@ -615,10 +620,8 @@ struct advertising_event_properties_t { break; case advertising_type_t::ADV_SCAN_IND: scannable = true; - use_legacy_pdu = true; break; case advertising_type_t::ADV_NONCONN_IND: - use_legacy_pdu = true; break; } } From ca68323930c3fb0fe099781eb417d6eae47c66e4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 6 Nov 2018 14:51:06 +0000 Subject: [PATCH 007/361] Add explicit cast to bool. --- features/FEATURE_BLE/ble/pal/GapTypes.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index a5380052e1..56e83315eb 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -818,23 +818,23 @@ struct extended_advertising_report_event_type_t { extended_advertising_report_event_type_t(uint8_t value) : value(value) { } bool connectable() { - return value & (1 << 0); + return static_cast(value & (1 << 0)); } bool scannable_advertising() { - return value & (1 << 1); + return static_cast(value & (1 << 1)); } bool directed_advertising() { - return value & (1 << 2); + return static_cast(value & (1 << 2)); } bool scan_response() { - return value & (1 << 3); + return static_cast(value & (1 << 3)); } bool legacy_advertising() { - return value & (1 << 4); + return static_cast(value & (1 << 4)); } advertising_data_status_t data_status() { From 8fa62ec71977608c0f2791cbaea5e84579ded4d9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 7 Nov 2018 09:36:42 +0000 Subject: [PATCH 008/361] BLE: Add count function to phy_set_t --- features/FEATURE_BLE/ble/BLETypes.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index aa7a171262..c9ec747f51 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -816,6 +816,10 @@ public: return _value; } + uint8_t count() const { + return (get_1m() ? 1 : 0) + (get_2m() ? 1 : 0) + (get_coded() ? 1 : 0); + } + private: uint8_t _value; }; From b9d7e63911063e8c36d2f5a6e1c239bd895981a8 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 7 Nov 2018 09:40:36 +0000 Subject: [PATCH 009/361] BLE: Implement Advertising extension and Periodic Advertising on Cordio (WIP) --- .../targets/TARGET_CORDIO/CordioPalGap.h | 139 ++++++ .../TARGET_CORDIO/source/CordioPalGap.cpp | 413 ++++++++++++++++++ 2 files changed, 552 insertions(+) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h index 286fc341f5..ee3a2e8546 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h @@ -153,6 +153,145 @@ public: */ static void gap_handler(const wsfMsgHdr_t* msg); + virtual ble_error_t set_advertising_set_random_address( + advertising_handle_t advertising_handle, + const address_t &address + ); + + virtual ble_error_t set_extended_advertising_parameters( + advertising_handle_t advertising_handle, + advertising_event_properties_t event_properties, + advertising_interval_t primary_advertising_interval_min, + advertising_interval_t primary_advertising_interval_max, + advertising_channel_map_t primary_advertising_channel_map, + own_address_type_t own_address_type, + advertising_peer_address_type_t peer_address_type, + const address_t &peer_address, + advertising_filter_policy_t advertising_filter_policy, + advertising_power_t advertising_power, + phy_t primary_advertising_phy, + uint8_t secondary_advertising_max_skip, + phy_t secondary_phy, + uint8_t advertising_sid, + bool scan_request_notification + ); + + virtual ble_error_t set_periodic_advertising_parameters( + advertising_handle_t advertising_handle, + periodic_advertising_interval_t periodic_advertising_min, + periodic_advertising_interval_t periodic_advertising_max, + bool advertise_power + ); + + virtual ble_error_t set_extended_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t advertising_data_size, + const uint8_t *advertising_data + ); + + virtual ble_error_t set_periodic_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t fragment_description, + uint8_t advertising_data_size, + const uint8_t *advertising_data + ); + + virtual ble_error_t set_extended_scan_response_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t scan_response_data_size, + const uint8_t *scan_response_data + ); + + virtual ble_error_t extended_advertising_enable( + bool enable, + uint8_t number_of_sets, + const advertising_handle_t *handles, + const uint16_t *durations, + const uint8_t *max_extended_advertising_events + ); + + virtual ble_error_t periodic_advertising_enable( + bool enable, + advertising_handle_t advertising_handle + ); + + virtual uint16_t get_maximum_advertising_data_length(); + + virtual uint8_t get_max_number_of_advertising_sets(); + + virtual ble_error_t remove_advertising_set( + advertising_handle_t advertising_handle + ); + + virtual ble_error_t clear_advertising_sets(); + + virtual ble_error_t set_extended_scan_parameters( + own_address_type_t own_address_type, + scanning_filter_policy_t filter_policy, + phy_set_t scanning_phys, + const bool *active_scanning, + const uint16_t *scan_interval, + const uint16_t *scan_window + ); + + virtual ble_error_t extended_scan_enable( + bool enable, + duplicates_filter_t filter_duplicates, + uint16_t duration, + uint16_t period + ); + + virtual ble_error_t periodic_advertising_create_sync( + bool use_periodic_advertiser_list, + uint8_t advertising_sid, + peer_address_type_t peer_address_type, + const address_t &peer_address, + uint16_t allowed_skip, + uint16_t sync_timeout + ); + + virtual ble_error_t cancel_periodic_advertising_create_sync(); + + virtual ble_error_t periodic_advertising_terminate_sync( + sync_handle_t sync_handle + ); + + virtual ble_error_t add_device_to_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid + ); + + virtual ble_error_t remove_device_from_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid + ); + + virtual ble_error_t clear_periodic_advertiser_list(); + + virtual uint8_t read_periodic_advertiser_list_size(); + + virtual ble_error_t extended_create_connection( + initiator_policy_t initiator_policy, + own_address_type_t own_address_type, + peer_address_type_t peer_address_type, + const address_t &peer_address, + phy_set_t initiating_phys, + const uint16_t *scan_intervals, + const uint16_t *scan_windows, + const uint16_t *connection_intervals_min, + const uint16_t *connection_intervals_max, + const uint16_t *connection_latencies, + const uint16_t *supervision_timeouts, + const uint16_t *minimum_connection_event_lengths, + const uint16_t *maximum_connection_event_lengths + ); + private: /** * T shall define a can_convert and convert function and a type diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index ed14d1920d..0f4f94e79d 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -16,6 +16,7 @@ #include "CordioPalGap.h" #include "hci_api.h" +#include "dm_api.h" namespace ble { namespace pal { @@ -458,6 +459,418 @@ bool Gap::event_handler(const wsfMsgHdr_t* msg) { return false; } +ble_error_t Gap::set_advertising_set_random_address( + advertising_handle_t advertising_handle, + const address_t &address +) +{ + DmAdvSetRandAddr(advertising_handle, address.data()); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_extended_advertising_parameters( + advertising_handle_t advertising_handle, + advertising_event_properties_t event_properties, + advertising_interval_t primary_advertising_interval_min, + advertising_interval_t primary_advertising_interval_max, + advertising_channel_map_t primary_advertising_channel_map, + own_address_type_t own_address_type, + advertising_peer_address_type_t peer_address_type, + const address_t &peer_address, + advertising_filter_policy_t advertising_filter_policy, + advertising_power_t advertising_power, + phy_t primary_advertising_phy, + uint8_t secondary_advertising_max_skip, + phy_t secondary_phy, + uint8_t advertising_sid, + bool scan_request_notification +) +{ + DmAdvSetInterval( + advertising_handle, + primary_advertising_interval_min, + primary_advertising_interval_max + ); + + DmAdvSetAddrType(own_address_type.value()); + + DmAdvSetChannelMap( + advertising_handle, + primary_advertising_channel_map.value() + ); + + DmDevSetExtFilterPolicy( + advertising_handle, + DM_FILT_POLICY_MODE_ADV, + advertising_filter_policy.value() + ); + + DmAdvScanReqNotifEnable(advertising_handle, scan_request_notification); + + DmAdvSetPhyParam( + advertising_handle, + primary_advertising_phy.value(), + secondary_advertising_max_skip, + secondary_phy.value() + ); + + DmAdvIncTxPwr( + advertising_handle, + event_properties.include_tx_power, + advertising_power + ); + + DmAdvUseLegacyPdu(advertising_handle, event_properties.use_legacy_pdu); + DmAdvOmitAdvAddr(advertising_handle, event_properties.omit_advertisser_address); + + DmAdvConfig( + advertising_handle, + event_properties.value(), // TODO: use the raw value here ??? + peer_address_type.value(), + const_cast(peer_address.data()) + ); + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_periodic_advertising_parameters( + advertising_handle_t advertising_handle, + periodic_advertising_interval_t periodic_advertising_min, + periodic_advertising_interval_t periodic_advertising_max, + bool advertise_power +) +{ + DmPerAdvIncTxPwr(advertising_handle, advertise_power); + DmPerAdvSetInterval( + advertising_handle, + periodic_advertising_min, + periodic_advertising_max + ); + DmPerAdvConfig(advertising_handle); + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_extended_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t advertising_data_size, + const uint8_t *advertising_data +) +{ + uint8_t frag_pref = minimize_fragmentation ? + HCI_ADV_DATA_FRAG_PREF_NO_FRAG : + HCI_ADV_DATA_FRAG_PREF_FRAG; + + DmAdvSetFragPref(advertising_handle, frag_pref); + + DmAdvSetData( + advertising_handle, + operation.value(), + DM_DATA_LOC_ADV, + advertising_data_size, + const_cast(advertising_data) + ); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_periodic_advertising_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t fragment_description, + uint8_t advertising_data_size, + const uint8_t *advertising_data +) +{ + DmPerAdvSetData( + advertising_handle, + fragment_description.value(), + advertising_data_size, + const_cast(advertising_data) + ); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_extended_scan_response_data( + advertising_handle_t advertising_handle, + advertising_fragment_description_t operation, + bool minimize_fragmentation, + uint8_t scan_response_data_size, + const uint8_t *scan_response_data +) +{ + uint8_t frag_pref = minimize_fragmentation ? + HCI_ADV_DATA_FRAG_PREF_NO_FRAG : + HCI_ADV_DATA_FRAG_PREF_FRAG; + + DmAdvSetFragPref(advertising_handle, frag_pref); + + DmAdvSetData( + advertising_handle, + operation.value(), + DM_DATA_LOC_SCAN, + scan_response_data_size, + const_cast(scan_response_data) + ); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::extended_advertising_enable( + bool enable, + uint8_t number_of_sets, + const advertising_handle_t *handles, + const uint16_t *durations, + const uint8_t *max_extended_advertising_events +) +{ + if (enable) { + uint16_t* durations_ms = new uint16_t[number_of_sets]; + for (size_t i = 0; i < number_of_sets; ++i) { + uint32_t r = durations[i] * 10; + durations_ms[i] = r > 0xFFFF ? 0xFFFF : r; + } + + DmAdvStart( + number_of_sets, + const_cast(handles), + durations_ms, + const_cast(max_extended_advertising_events) + ); + + delete[] durations_ms; + } else { + DmAdvStop( + number_of_sets, + const_cast(handles) + ); + } + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::periodic_advertising_enable( + bool enable, + advertising_handle_t advertising_handle +) +{ + if (enable) { + DmPerAdvStart(advertising_handle); + } else { + DmPerAdvStop(advertising_handle); + } + + return BLE_ERROR_NONE; +} + +uint16_t Gap::get_maximum_advertising_data_length() +{ + return HciGetMaxAdvDataLen(); +} + +uint8_t Gap::get_max_number_of_advertising_sets() +{ + return HciGetNumSupAdvSets(); +} + +ble_error_t Gap::remove_advertising_set(advertising_handle_t advertising_handle) +{ + DmAdvRemoveAdvSet(advertising_handle); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::clear_advertising_sets() +{ + DmAdvClearAdvSets(); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::set_extended_scan_parameters( + own_address_type_t own_address_type, + scanning_filter_policy_t filter_policy, + phy_set_t scanning_phys, + const bool *active_scanning, + const uint16_t *scan_interval, + const uint16_t *scan_window +) +{ + DmScanSetAddrType(own_address_type.value()); + + // TODO: use/store filter policy + // TODO: use/store active scanning + // TODO: store scanning_phys + + DmScanSetInterval( + scanning_phys.value(), + const_cast(scan_interval), + const_cast(scan_window) + ); + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::extended_scan_enable( + bool enable, + duplicates_filter_t filter_duplicates, + uint16_t duration, + uint16_t period +) +{ + if (enable) { + // TODO retrieve scanning phys + phy_set_t scanning_phys; + + // TODO: retrieve scan type + uint8_t* scan_type /*= use_active_scanning ? DM_SCAN_TYPE_ACTIVE : DM_SCAN_TYPE_PASSIVE */; + + uint32_t duration_ms = duration * 10; + + DmScanModeExt(); + DmScanStart( + scanning_phys.value(), + DM_DISC_MODE_NONE, // TODO: What todo with this ???? + scan_type, + filter_duplicates.value(), // TODO: cordio API incomplete ??? + duration_ms > 0xFFFF ? 0xFFFF : duration_ms, + period + ); + } else { + DmScanStop(); + } + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::periodic_advertising_create_sync( + bool use_periodic_advertiser_list, + uint8_t advertising_sid, + peer_address_type_t peer_address_type, + const address_t &peer_address, + uint16_t allowed_skip, + uint16_t sync_timeout +) +{ + if (use_periodic_advertiser_list) { + DmDevSetExtFilterPolicy( + DM_ADV_HANDLE_DEFAULT, + DM_FILT_POLICY_MODE_SYNC, + HCI_FILT_PER_ADV_LIST + ); + } + + DmSyncStart( + advertising_sid, + peer_address_type.value(), + peer_address.data(), + allowed_skip, + sync_timeout + ); + + return BLE_ERROR_INVALID_PARAM; +} + +ble_error_t Gap::cancel_periodic_advertising_create_sync() +{ + // FIXME: Find a way to use it! + // Function not directly exposed by the cordio stack. + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::periodic_advertising_terminate_sync(sync_handle_t sync_handle) +{ + DmSyncStop(sync_handle); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::add_device_to_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid +) +{ + DmAddDeviceToPerAdvList( + advertiser_address_type.value(), + const_cast(advertiser_address.data()), + advertising_sid + ); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::remove_device_from_periodic_advertiser_list( + advertising_peer_address_type_t advertiser_address_type, + const address_t &advertiser_address, + uint8_t advertising_sid +) +{ + DmRemoveDeviceFromPerAdvList( + advertiser_address_type.value(), + const_cast(advertiser_address.data()), + advertising_sid + ); + return BLE_ERROR_NONE; +} + +ble_error_t Gap::clear_periodic_advertiser_list() +{ + DmClearPerAdvList(); + return BLE_ERROR_NONE; +} + +uint8_t Gap::read_periodic_advertiser_list_size() +{ + return HciGetPerAdvListSize(); +} + +ble_error_t Gap::extended_create_connection( + initiator_policy_t initiator_policy, + own_address_type_t own_address_type, + peer_address_type_t peer_address_type, + const address_t &peer_address, + phy_set_t initiating_phys, + const uint16_t *scan_intervals, + const uint16_t *scan_windows, + const uint16_t *connection_intervals_min, + const uint16_t *connection_intervals_max, + const uint16_t *connection_latencies, + const uint16_t *supervision_timeouts, + const uint16_t *minimum_connection_event_lengths, + const uint16_t *maximum_connection_event_lengths +) +{ + DmExtConnSetScanInterval( + initiating_phys.value(), + const_cast(scan_intervals), + const_cast(scan_windows) + ); + + DmDevSetFilterPolicy(DM_FILT_POLICY_MODE_INIT, initiator_policy.value()); + DmConnSetAddrType(own_address_type.value()); + + // At most 3 phys are in used + hciConnSpec_t conn_specs[3]; + for (size_t i = 0, count = initiating_phys.count(); i < count; ++i) { + conn_specs[i].connIntervalMin = connection_intervals_min[i]; + conn_specs[i].connIntervalMax = connection_intervals_max[i]; + conn_specs[i].connLatency = connection_latencies[i]; + conn_specs[i].supTimeout = supervision_timeouts[i]; + conn_specs[i].minCeLen = minimum_connection_event_lengths[i]; + conn_specs[i].maxCeLen = maximum_connection_event_lengths[i]; + } + + DmExtConnSetConnSpec(initiating_phys.value(), conn_specs); + + dmConnId_t connection_id = DmConnOpen( + DM_CLIENT_ID_APP, + initiating_phys.value(), + peer_address_type.value(), + const_cast(peer_address.data()) + ); + + if (connection_id == DM_CONN_ID_NONE) { + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + return BLE_ERROR_NONE; +} } // cordio } // vendor From f35ebcc9005b70516d08d1b29b9c238dc7597e63 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 7 Nov 2018 11:12:47 +0000 Subject: [PATCH 010/361] simplify params to avoid holding state --- features/FEATURE_BLE/ble/Gap.h | 28 +++--- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 90 +++++++++++-------- 2 files changed, 71 insertions(+), 47 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index c8ed0e7075..d706d52bdd 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1145,57 +1145,63 @@ public: /* advertising */ - uint8_t getMaxAdvertisingSetNumber() { + virtual uint8_t getMaxAdvertisingSetNumber() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 1; } - uint8_t getMaxAdvertisingDataLength() { + virtual uint8_t getMaxAdvertisingDataLength() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 0x1F; } - ble_error_t createAdvertisingSet(AdvHandle_t* handle) { + virtual ble_error_t createAdvertisingSet(AdvHandle_t* handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { + virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { + virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { (void) handle; (void) params; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { + virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { (void) handle; (void) params; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { + virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { (void) handle; (void) payload; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { + virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { (void) handle; (void) response; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - ble_error_t startAdvertising(AdvHandle_t handle) { + virtual ble_error_t startAdvertising( + AdvHandle_t handle, + uint8_t maxEvents = 0, + uint32_t maxDuration = 0 + ) { + (void) maxEvents; + (void) maxDuration; /* deprecation compatibility */ if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_NOT_IMPLEMENTED; @@ -1211,13 +1217,13 @@ public: return status; } - ble_error_t stopAdvertising(AdvHandle_t handle) { + virtual ble_error_t stopAdvertising(AdvHandle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - bool isAdvertisingActive(AdvHandle_t handle) const { + virtual bool isAdvertisingActive(AdvHandle_t handle) const { if (handle != LEGACY_ADVERTISING_HANDLE) { return false; } diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 16f9970b56..bfc1eaf147 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -257,29 +257,47 @@ private: uint16_t _timeout; }; -class GapExtendedAdvertisingParams : public GapAdvertisingParams { - GapExtendedAdvertisingParams() - : GapAdvertisingParams(), - _minInterval(0), - _maxInterval(0), - _maxDuration(0), - _peerAddressType(), - _ownAddressType(), - _policy(ble::ADV_POLICY_IGNORE_WHITELIST), - _primaryPhy(ble::phy_t::LE_1M), - _secondaryPhy(ble::phy_t::LE_1M), - _peerAddress(), - _maxEvents(0), - _txPower(0), - _eventNumber(0), - _channel37(1), - _channel38(1), - _channel39(1), - _anonymous(0), - _notifyOnScan(1) { +class GapExtendedAdvertisingParams { + GapExtendedAdvertisingParams() : + _advType(ble::EXT_ADV_CONNECTABLE_UNDIRECTED), + _minInterval(0), + _maxInterval(0), + _maxDuration(0), + _peerAddressType(), + _ownAddressType(), + _policy(ble::ADV_POLICY_IGNORE_WHITELIST), + _primaryPhy(ble::phy_t::LE_1M), + _secondaryPhy(ble::phy_t::LE_1M), + _peerAddress(), + _maxEvents(0), + _txPower(0), + _eventNumber(0), + _channel37(1), + _channel38(1), + _channel39(1), + _anonymous(0), + _notifyOnScan(1) { } + /** + * Update the advertising type. + * + * @param[in] newAdvType The new advertising type. + */ + void setAdvertisingType(ble::advertising_type_t newAdvType) { + _advType = newAdvType; + } + + /** + * Return advertising type. + * + * @return Advertising type. + */ + ble::advertising_type_t setAdvertisingType() { + return _advType; + } + bool getAnonymousAdvertising() { return _anonymous; } @@ -420,34 +438,34 @@ class GapExtendedAdvertisingParams : public GapAdvertisingParams { _notifyOnScan = enable; } - ble_error_t getDuration( - uint32_t *maxDuration /* ms */, - uint8_t *maxEvents - ) { - if (!maxDuration || !maxEvents) { - return BLE_ERROR_INVALID_PARAM; - } - return BLE_ERROR_NONE; + /**/ + + uint32_t getMinPrimaryAdvertisingInterval() const { + return _minInterval; } - void setDuration( - uint32_t maxDuration /* ms */, - uint8_t maxEvents = 0 - ) { - _maxDuration = maxDuration; - _maxEvents = maxEvents; + uint32_t getMinPrimaryAdvertisingInterval() const { + return _maxInterval; } + + BLEProtocol::AddressBytes_t* getPeerAddress() { + return _peerAddress; + }; + + ble::peer_address_type_t getPeerAddressType() { + return _peerAddressType; + }; + private: + ble::advertising_type_t _advType; uint32_t _minInterval; uint32_t _maxInterval; - uint32_t _maxDuration; ble::peer_address_type_t _peerAddressType; BLEProtocol::AddressType_t _ownAddressType; ble::advertising_policy_mode_t _policy; ble::phy_t _primaryPhy; ble::phy_t _secondaryPhy; BLEProtocol::AddressBytes_t _peerAddress; - uint8_t _maxEvents; uint8_t _txPower; uint8_t _eventNumber; uint8_t _channel37:1; From 6ca5041f53d5877d125fe2b0fff9378fc2183da5 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 7 Nov 2018 15:54:20 +0000 Subject: [PATCH 011/361] generic advertising --- features/FEATURE_BLE/ble/Gap.h | 1 + features/FEATURE_BLE/ble/GapAdvertisingData.h | 13 +- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 48 +++-- features/FEATURE_BLE/ble/generic/GenericGap.h | 66 +++++- .../FEATURE_BLE/source/generic/GenericGap.cpp | 190 ++++++++++++++++++ 5 files changed, 298 insertions(+), 20 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index d706d52bdd..044f4193ae 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1017,6 +1017,7 @@ public: typedef uint8_t AdvHandle_t; static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; + static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; struct AdvReportOptionalInformation { PeerAddressType_t directAddressType; diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 991c144f57..6f8563eaa8 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -537,7 +537,8 @@ public: GapAdvertisingData(void) : _payload(), _payloadLen(0), - _appearance(GENERIC_TAG) { + _appearance(GENERIC_TAG), + _minimiseFragmentation(false) { } /** @@ -724,6 +725,14 @@ public: return NULL; } + void setMinimiseFragmentation(bool enable = true) { + _minimiseFragmentation = enable; + } + + bool getMinimiseFragmentation() { + return _minimiseFragmentation; + } + private: /** * Append advertising data based on the specified type. @@ -913,6 +922,8 @@ private: * Appearance value. */ uint16_t _appearance; + + bool _minimiseFragmentation; }; /** diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index bfc1eaf147..6f438f9e7e 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -285,7 +285,7 @@ class GapExtendedAdvertisingParams { * * @param[in] newAdvType The new advertising type. */ - void setAdvertisingType(ble::advertising_type_t newAdvType) { + void setType(ble::advertising_type_t newAdvType) { _advType = newAdvType; } @@ -294,7 +294,7 @@ class GapExtendedAdvertisingParams { * * @return Advertising type. */ - ble::advertising_type_t setAdvertisingType() { + ble::advertising_type_t getType() { return _advType; } @@ -308,7 +308,7 @@ class GapExtendedAdvertisingParams { _anonymous = enable; } - ble_error_t getPrimaryAdvertisingInterval( + ble_error_t getPrimaryInterval( uint32_t *min /* ms */, uint32_t *max /* ms */ ) { @@ -320,7 +320,7 @@ class GapExtendedAdvertisingParams { return BLE_ERROR_NONE; } - void setPrimaryAdvertisingInterval( + void setPrimaryInterval( uint32_t min /* ms */, uint32_t max /* ms */ ) { @@ -328,7 +328,7 @@ class GapExtendedAdvertisingParams { _maxInterval = max; } - ble_error_t getPrimaryAdvertisingChannels( + ble_error_t getPrimaryChannels( bool *channel37, bool *channel38, bool *channel39 @@ -342,7 +342,7 @@ class GapExtendedAdvertisingParams { return BLE_ERROR_NONE; } - void setPrimaryAdvertisingChannels( + void setPrimaryChannels( bool channel37, bool channel38, bool channel39 @@ -382,27 +382,27 @@ class GapExtendedAdvertisingParams { _peerAddressType = addressType; }; - ble::advertising_policy_mode_t getAdvertisingPolicyMode() { + ble::advertising_policy_mode_t getPolicyMode() { return _policy; } - void setAdvertisingPolicyMode( + void setPolicyMode( ble::advertising_policy_mode_t mode ) { _policy = mode; } - int8_t getAdvertisingTxPower() { + int8_t getTxPower() { return _txPower; } - void setAdvertisingTxPower( + void setTxPower( int8_t txPower ) { _txPower = txPower; } - ble_error_t getAdvertisingPhy( + ble_error_t getPhy( ble::phy_t *primaryPhy, ble::phy_t *secondaryPhy ) { @@ -414,7 +414,7 @@ class GapExtendedAdvertisingParams { return BLE_ERROR_NONE; } - void setAdvertisingPhy( + void setPhy( ble::phy_t primaryPhy, ble::phy_t secondaryPhy ) { @@ -422,29 +422,33 @@ class GapExtendedAdvertisingParams { _secondaryPhy = secondaryPhy; } - uint8_t getSecondaryAdvertisingMaxSkip() { + uint8_t getSecondaryMaxSkip() { return _eventNumber; } - void setSecondaryAdvertisingMaxSkip( + void setSecondaryMaxSkip( uint8_t eventNumber ) { _eventNumber = eventNumber; } - void enableScanRequestNotification( - bool enable + void setScanRequestNotification( + bool enable = true ) { _notifyOnScan = enable; } + bool getScanRequestNotification() { + return _notifyOnScan; + } + /**/ - uint32_t getMinPrimaryAdvertisingInterval() const { + uint32_t getMinPrimaryInterval() const { return _minInterval; } - uint32_t getMinPrimaryAdvertisingInterval() const { + uint32_t getMaxPrimaryInterval() const { return _maxInterval; } @@ -456,6 +460,14 @@ class GapExtendedAdvertisingParams { return _peerAddressType; }; + ble::phy_t getPrimaryPhy() { + return _primaryPhy; + } + + ble::phy_t getSecondaryPhy() { + return _secondaryPhy; + } + private: ble::advertising_type_t _advType; uint32_t _minInterval; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 746371ebcd..7cc2fd1dcd 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -47,6 +47,8 @@ class GenericGap : public ::Gap, public pal::Gap::EventHandler { public: + /* TODO: move to config */ + static const size_t MAX_ADVERTISING_SETS = 64; /** * Construct a GenericGap instance for a given BLE instance ID. * @@ -73,6 +75,30 @@ public: */ virtual ~GenericGap(); + uint8_t getMaxAdvertisingSetNumber(); + + uint8_t getMaxAdvertisingDataLength(); + + ble_error_t createAdvertisingSet(AdvHandle_t* handle); + + ble_error_t destroyAdvertisingSet(AdvHandle_t handle); + + ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params); + + ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params); + + ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload); + + ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response); + + ble_error_t startAdvertising(AdvHandle_t handle, uint8_t maxEvents = 0, uint32_t maxDuration = 0); + + ble_error_t stopAdvertising(AdvHandle_t handle); + + bool isAdvertisingActive(AdvHandle_t handle) const; + + void init_extended_advertising(); + /** * @see Gap::setAddress */ @@ -316,7 +342,9 @@ public: /** * @see Gap::startAdvertising */ - virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms); + virtual ble_error_t startAdvertising( + const GapAdvertisingParams ¶ms + ); /** * @see Gap::reset @@ -433,6 +461,42 @@ private: mbed::Timeout _scan_timeout; mbed::Ticker _address_rotation_ticker; pal::ConnectionEventMonitor::EventHandler *_connection_event_handler; + uint8_t _existing_sets[(MAX_ADVERTISING_SETS / 8) + 1]; + uint8_t _active_sets[(MAX_ADVERTISING_SETS / 8) + 1]; + +private: + static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte; + bool value = ((*bytes) >> bit) & 0x01; + return value; + } + + static bool set_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte; + *bytes |= 0x01 >> bit; + return true; + } + + static bool clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte + *bytes &= 0x00 >> bit; + return true; + } }; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 94bddf9711..8bdb2648dd 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -427,6 +427,11 @@ GenericGap::GenericGap( _random_static_identity_address = _pal_gap.get_random_address(); _pal_gap.set_event_handler(this); + + memset(_active_sets, 0, MAX_ADVERTISING_SETS); + memset(_existing_sets, 0, MAX_ADVERTISING_SETS); + /* legacy advertising always exists */ + *_existing_sets = 0x01; } GenericGap::~GenericGap() @@ -1109,6 +1114,7 @@ ble_error_t GenericGap::reset(void) Gap::reset(); _advertising_timeout.detach(); _scan_timeout.detach(); + _pal_gap.clear_advertising_sets(); return BLE_ERROR_NONE; } @@ -1555,5 +1561,189 @@ void GenericGap::set_connection_event_handler(pal::ConnectionEventMonitor::Event _connection_event_handler = connection_event_handler; } +uint8_t GenericGap::getMaxAdvertisingSetNumber() { + uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); + set_number = MAX_ADVERTISING_SETS < set_number ? MAX_ADVERTISING_SETS : set_number; + return set_number; +} + +uint8_t GenericGap::getMaxAdvertisingDataLength() { + return _pal_gap.get_maximum_advertising_data_length(); +} + +ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) { + uint8_t new_handle = 1; + + while (get_adv_set_bit(_existing_sets, new_handle)) { + new_handle++; + } + + if (set_adv_set_bit(_existing_sets, new_handle)) { + *handle = new_handle; + return BLE_ERROR_NONE; + } + + *handle = INVALID_ADVERTISING_HANDLE; + + return BLE_ERROR_OPERATION_NOT_PERMITTED; +} + +ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { + if (get_adv_set_bit(_existing_sets, handle)) { + return BLE_ERROR_INVALID_PARAM; + } + + if (get_adv_set_bit(_active_sets, handle)) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } + + if (set_adv_set_bit(_existing_sets, handle)) { + return _pal_gap.remove_advertising_set(handle); + } + + return BLE_ERROR_INVALID_PARAM; +} + +ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { + if (handle != Gap::LEGACY_ADVERTISING_HANDLE || !params) { + return BLE_ERROR_INVALID_PARAM; + } + + pal::advertising_event_properties_t event_properties;//TODO + ble::advertising_type_t adv_type = params->getAdvertisingType(); + + AddressUseType_t use_type; + switch(adv_type) { + case ADV_SCANNABLE_UNDIRECTED: + case ADV_NON_CONNECTABLE_UNDIRECTED: + case EXT_ADV_NON_CONNECTABLE_DIRECTED: + case EXT_ADV_SCANNABLE_DIRECTED: + use_type = AddressUseType_t::PERIPHERAL_NON_CONNECTABLE + break; + default: + use_type = AddressUseType_t::PERIPHERAL_CONNECTABLE; + } + + return _pal_gap.set_extended_advertising_parameters( + (pal::advertising_handle_t)Gap::LEGACY_ADVERTISING_HANDLE, + event_properties, + (pal::advertising_interval_t)params->getIntervalInADVUnits(), + (pal::advertising_interval_t)params->getIntervalInADVUnits(), + pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, + (pal::own_address_type_t)get_own_address_type(use_type), + pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, + params->getPeerAddress(), + (pal::advertising_filter_policy_t)_advertising_filter_policy, + (pal::advertising_power_t)params->getTxPower(), + params->getPrimaryPhy(), + params->getSecondaryMaxSkip(), + params->getSecondaryPhy(), + 0, + params->getScanRequestNotification() + ); +} + +ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { + if (!get_adv_set_bit(_existing_sets, handle) || !params) { + return BLE_ERROR_INVALID_PARAM; + } + + pal::advertising_channel_map_t channel_map; /*TODO translate*/ + uint8_t sid;//TODO + pal::advertising_event_properties_t event_properties;//TODO + //params->getAdvertisingType() + + return _pal_gap.set_extended_advertising_parameters( + (pal::advertising_handle_t)handle, + event_properties, + (pal::advertising_interval_t)params->getMinPrimaryInterval(), + (pal::advertising_interval_t)params->getMaxPrimaryInterval(), + channel_map, + (pal::own_address_type_t)params->getOwnAddressType(), + (pal::advertising_peer_address_type_t)params->getPeerAddressType(), + params->getPeerAddress(), + (pal::advertising_filter_policy_t)params->getPolicyMode(), + (pal::advertising_power_t)params->getTxPower(), + params->getPrimaryPhy(), + params->getSecondaryMaxSkip(), + params->getSecondaryPhy(), + sid, + params->getScanRequestNotification() + ); +} + +ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { + if (!get_adv_set_bit(_existing_sets, handle) || !payload) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.set_extended_advertising_data( + handle, + /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, + payload->setMinimiseFragmentation, + payload->getPayloadLen(), + payload->getPayload() + ); +} + +ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { + if (!get_adv_set_bit(_existing_sets, handle) || !response) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.set_extended_scan_response_data( + handle, + /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, + response->setMinimiseFragmentation, + response->getPayloadLen(), + response->getPayload() + ); +} + +ble_error_t GenericGap::startAdvertising( + AdvHandle_t handle, + uint8_t maxEvents, + uint32_t maxDuration +) { + if (!get_adv_set_bit(_existing_sets, handle)) { + return BLE_ERROR_INVALID_PARAM; + } + + /* round up */ + uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; + + ble_error_t status = _pal_gap.extended_advertising_enable( + true, + 1, + &handle, + &duration_10ms, + &maxEvents + ); + + if (status == BLE_ERROR_NONE) { + set_adv_set_bit(_active_sets, handle); + } + + return status; +} + +ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { + if (get_adv_set_bit(_existing_sets, handle)) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.extended_advertising_enable( + true, + 1, + &handle, + NULL, + NULL + ); +} + +bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { + return get_adv_set_bit(_active_sets, handle); +} + } // namespace generic } // namespace ble From 25997d96b93c55d47fbbcffed1793fb5b8d4c3e1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 7 Nov 2018 16:00:25 +0000 Subject: [PATCH 012/361] chek for features --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 8bdb2648dd..8ff6deb1ea 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1572,12 +1572,17 @@ uint8_t GenericGap::getMaxAdvertisingDataLength() { } ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) { - uint8_t new_handle = 1; + if (_pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING)) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } + + uint8_t new_handle = LEGACY_ADVERTISING_HANDLE + 1; while (get_adv_set_bit(_existing_sets, new_handle)) { new_handle++; } + /* if we went over the limit this set will fail safely */ if (set_adv_set_bit(_existing_sets, new_handle)) { *handle = new_handle; return BLE_ERROR_NONE; From 5efac211beb558776ba154f7ba490b9c62896c7b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 7 Nov 2018 16:19:45 +0000 Subject: [PATCH 013/361] sid --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 8ff6deb1ea..a19545ae14 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1614,6 +1614,11 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return BLE_ERROR_INVALID_PARAM; } + if (_pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING)) { + // do legacy stuff + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } + pal::advertising_event_properties_t event_properties;//TODO ble::advertising_type_t adv_type = params->getAdvertisingType(); @@ -1643,7 +1648,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert params->getPrimaryPhy(), params->getSecondaryMaxSkip(), params->getSecondaryPhy(), - 0, + 0xFF, params->getScanRequestNotification() ); } @@ -1654,7 +1659,6 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend } pal::advertising_channel_map_t channel_map; /*TODO translate*/ - uint8_t sid;//TODO pal::advertising_event_properties_t event_properties;//TODO //params->getAdvertisingType() @@ -1672,7 +1676,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend params->getPrimaryPhy(), params->getSecondaryMaxSkip(), params->getSecondaryPhy(), - sid, + (handle % 0x10), params->getScanRequestNotification() ); } From 7de5d8c76339709b3d12ffedaef20eb98e747ab9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 7 Nov 2018 16:35:12 +0000 Subject: [PATCH 014/361] Merge pull request #4 from pan-/extended Last bit of PAL extended advertising implementation. --- features/FEATURE_BLE/ble/BLETypes.h | 2 + features/FEATURE_BLE/ble/pal/GapTypes.h | 29 ++- .../targets/TARGET_CORDIO/CordioPalGap.h | 2 + .../TARGET_CORDIO/source/CordioPalGap.cpp | 199 +++++++++++++++--- 4 files changed, 200 insertions(+), 32 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index c9ec747f51..74168c6ae4 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -726,6 +726,8 @@ struct phy_t : SafeEnum { */ phy_t(type value) : SafeEnum(value) { } + + explicit phy_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; /** diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 56e83315eb..6a4d71f276 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -161,6 +161,10 @@ struct connection_peer_address_type_t : */ connection_peer_address_type_t(type value) : SafeEnum(value) { } + + explicit connection_peer_address_type_t(uint8_t raw_value) : + SafeEnum(raw_value) + { } }; @@ -296,6 +300,12 @@ struct hci_error_code_t : SafeEnum { */ hci_error_code_t(type value) : SafeEnum(value) { } + + /** + * Construct a new hci_error_code_t from a raw value. + */ + explicit hci_error_code_t(uint8_t raw_value) : + SafeEnum(static_cast(raw_value)) { } }; @@ -528,6 +538,9 @@ struct connection_role_t : SafeEnum { }; connection_role_t(type value) : SafeEnum(value) { } + + explicit connection_role_t(uint8_t raw_value) : + SafeEnum(raw_value) { } }; /** @@ -808,10 +821,19 @@ struct advertising_data_status_t : SafeEnum(value) { } + + /** + * Explicit constructor from a raw value. + */ + explicit advertising_data_status_t(uint8_t raw_value) : + SafeEnum( + static_cast(value) + ) + { } }; struct extended_advertising_report_event_type_t { @@ -892,6 +914,8 @@ struct direct_address_type_t : SafeEnum { */ direct_address_type_t(type value) : SafeEnum(value) { } + + explicit direct_address_type_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; /** @@ -944,6 +968,9 @@ struct clock_accuracy_t : SafeEnum{ * Construct a new clock_accuracy_t value. */ clock_accuracy_t(type value) : SafeEnum(value) { } + + explicit clock_accuracy_t(uint8_t raw_value) : + SafeEnum(static_cast(raw_value)) { } }; } // namespace pal diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h index ee3a2e8546..1b7013ae37 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h @@ -409,6 +409,8 @@ private: private: address_t device_random_address; bool use_active_scanning; + uint8_t extended_scan_type[3]; + phy_set_t scanning_phys; }; } // cordio diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index 0f4f94e79d..72ecd033cd 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -399,32 +399,166 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { } connection_handle_t handle = (connection_handle_t)msg->param; + EventHandler *handler = get_gap()._pal_event_handler; + switch(msg->event) { - case DM_PHY_READ_IND: - if (get_gap()._pal_event_handler) { - const hciLeReadPhyCmdCmplEvt_t* evt = (const hciLeReadPhyCmdCmplEvt_t*)msg; - - get_gap()._pal_event_handler->on_read_phy( - (hci_error_code_t::type)msg->status, - handle, - (ble::phy_t::type)evt->txPhy, - (ble::phy_t::type)evt->rxPhy - ); + case DM_PHY_READ_IND: { + if (!handler) { + break; } - break; - case DM_PHY_UPDATE_IND: - if (get_gap()._pal_event_handler) { - const hciLePhyUpdateEvt_t* evt = (const hciLePhyUpdateEvt_t*)msg; + const hciLeReadPhyCmdCmplEvt_t* evt = (const hciLeReadPhyCmdCmplEvt_t*)msg; - get_gap()._pal_event_handler->on_phy_update_complete( - (hci_error_code_t::type)msg->status, - handle, - (ble::phy_t::type)evt->txPhy, - (ble::phy_t::type)evt->rxPhy - ); + handler->on_read_phy( + (hci_error_code_t::type)msg->status, + handle, + (ble::phy_t::type)evt->txPhy, + (ble::phy_t::type)evt->rxPhy + ); + } break; + + case DM_PHY_UPDATE_IND: { + if (!handler) { + break; } - break; + + const hciLePhyUpdateEvt_t* evt = (const hciLePhyUpdateEvt_t*)msg; + + handler->on_phy_update_complete( + (hci_error_code_t::type)msg->status, + handle, + (ble::phy_t::type)evt->txPhy, + (ble::phy_t::type)evt->rxPhy + ); + } break; + + case DM_PER_ADV_SYNC_EST_IND: { + if (!handler) { + break; + } + + const hciLePerAdvSyncEstEvt_t* evt = (const hciLePerAdvSyncEstEvt_t*) msg; + + handler->on_periodic_advertising_sync_established( + hci_error_code_t(evt->status), + evt->syncHandle, + evt->advSid, + connection_peer_address_type_t(evt->advAddrType), + evt->advAddr, + evt->perAdvInterval, + clock_accuracy_t(evt->clockAccuracy) + ); + } break; + + case DM_PER_ADV_REPORT_IND: { + if (!handler) { + break; + } + + const hciLePerAdvReportEvt_t* evt = (const hciLePerAdvReportEvt_t*) msg; + + handler->on_periodic_advertising_report( + evt->syncHandle, + evt->txPower, + evt->rssi, + advertising_data_status_t(evt->status), + evt->len, + evt->pData + ); + } break; + + case DM_PER_ADV_SYNC_LOST_IND: { + if (!handler) { + break; + } + + const hciLePerAdvSyncLostEvt_t* evt = (const hciLePerAdvSyncLostEvt_t*) msg; + handler->on_periodic_advertising_sync_loss(evt->syncHandle); + } break; + + case DM_CONN_OPEN_IND: { + if (!handler) { + break; + } + + // TODO: filter with old event ... + const hciLeConnCmplEvt_t* evt = (const hciLeConnCmplEvt_t*) msg; + handler->on_enhanced_connection_complete( + hci_error_code_t(evt->status), + evt->handle, + connection_role_t(evt->role), + connection_peer_address_type_t(evt->addrType), + evt->peerAddr, + evt->localRpa, + evt->peerRpa, + evt->connInterval, + evt->connLatency, + evt->supTimeout, + clock_accuracy_t(evt->clockAccuracy) + ); + } break; + + case DM_SCAN_REQ_RCVD_IND: { + if (!handler) { + break; + } + + const hciLeScanReqRcvdEvt_t* evt = (const hciLeScanReqRcvdEvt_t*) msg; + handler->on_scan_request_received( + evt->advHandle, + connection_peer_address_type_t(evt->scanAddrType), + evt->scanAddr + ); + } break; + + case DM_ADV_SET_STOP_IND: { + if (!handler) { + break; + } + + const hciLeAdvSetTermEvt_t* evt = (const hciLeAdvSetTermEvt_t*) msg; + handler->on_advertising_set_terminated( + hci_error_code_t(evt->status), + evt->advHandle, + evt->handle, + evt->numComplEvts + ); + } break; + + case DM_EXT_SCAN_STOP_IND: { + if (!handler) { + break; + } + + const hciLeScanTimeoutEvt_t* evt = (const hciLeScanTimeoutEvt_t*) msg; + handler->on_scan_timeout(); + } break; + + case DM_EXT_SCAN_REPORT_IND: { + if (!handler) { + break; + } + + const hciLeExtAdvReportEvt_t* evt = (const hciLeExtAdvReportEvt_t*) msg; + connection_peer_address_type_t addr_type(evt->addrType); + phy_t sec_phy(evt->secPhy); + + handler->on_extended_advertising_report( + evt->eventType, + (evt->addrType == HCI_ADDR_TYPE_ANONYMOUS) ? NULL : &addr_type, + evt->addr, + phy_t(evt->priPhy), + evt->secPhy == HCI_ADV_RPT_PHY_SEC_NONE ? NULL : &sec_phy, + evt->advSid, + evt->txPower, + evt->rssi, + evt->perAdvInter, + direct_address_type_t(evt->directAddrType), + evt->directAddr, + evt->len, + evt->pData + ); + } break; } // all handlers are stored in a static array @@ -695,9 +829,13 @@ ble_error_t Gap::set_extended_scan_parameters( { DmScanSetAddrType(own_address_type.value()); - // TODO: use/store filter policy - // TODO: use/store active scanning - // TODO: store scanning_phys + for (size_t i = 0, count = scanning_phys.count(); i < count; ++i) { + extended_scan_type[i] = active_scanning[i] ? + DM_SCAN_TYPE_ACTIVE : + DM_SCAN_TYPE_PASSIVE; + } + + this->scanning_phys = scanning_phys; DmScanSetInterval( scanning_phys.value(), @@ -705,6 +843,11 @@ ble_error_t Gap::set_extended_scan_parameters( const_cast(scan_window) ); + DmDevSetFilterPolicy( + DM_FILT_POLICY_MODE_SCAN, + filter_policy.value() + ); + return BLE_ERROR_NONE; } @@ -716,18 +859,12 @@ ble_error_t Gap::extended_scan_enable( ) { if (enable) { - // TODO retrieve scanning phys - phy_set_t scanning_phys; - - // TODO: retrieve scan type - uint8_t* scan_type /*= use_active_scanning ? DM_SCAN_TYPE_ACTIVE : DM_SCAN_TYPE_PASSIVE */; - uint32_t duration_ms = duration * 10; DmScanModeExt(); DmScanStart( scanning_phys.value(), - DM_DISC_MODE_NONE, // TODO: What todo with this ???? + DM_DISC_MODE_NONE, scan_type, filter_duplicates.value(), // TODO: cordio API incomplete ??? duration_ms > 0xFFFF ? 0xFFFF : duration_ms, From 56146a44fbcacc10cd3f4b54edfa6e0f0f715ed1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 7 Nov 2018 16:51:48 +0000 Subject: [PATCH 015/361] legacy support --- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 +++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 34 +++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 7cc2fd1dcd..5a278834eb 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -465,6 +465,10 @@ private: uint8_t _active_sets[(MAX_ADVERTISING_SETS / 8) + 1]; private: + bool is_extended_advertising_enabled() { + return _pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING); + } + static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { if (bit_number > MAX_ADVERTISING_SETS) { return false; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index a19545ae14..56b8dce5de 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1614,9 +1614,9 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return BLE_ERROR_INVALID_PARAM; } - if (_pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING)) { - // do legacy stuff - return BLE_ERROR_OPERATION_NOT_PERMITTED; + if (!is_extended_advertising_enabled()) { + memcpy(&getLegacyAdvertisingParams(), params, sizeof(GapAdvertisingParams)); + return BLE_ERROR_NONE; } pal::advertising_event_properties_t event_properties;//TODO @@ -1686,6 +1686,13 @@ ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdver return BLE_ERROR_INVALID_PARAM; } + if (!is_extended_advertising_enabled()) { + if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { + memcpy(&getLegacyAdvertisingPayload(), payload, sizeof(GapAdvertisingData)); + } + return BLE_ERROR_NOT_IMPLEMENTED; + } + return _pal_gap.set_extended_advertising_data( handle, /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, @@ -1700,6 +1707,13 @@ ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const Gap return BLE_ERROR_INVALID_PARAM; } + if (!is_extended_advertising_enabled()) { + if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { + memcpy(&getLegacyAdvertisingScanResponse(), response, sizeof(GapAdvertisingData)); + } + return BLE_ERROR_NOT_IMPLEMENTED; + } + return _pal_gap.set_extended_scan_response_data( handle, /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, @@ -1718,6 +1732,13 @@ ble_error_t GenericGap::startAdvertising( return BLE_ERROR_INVALID_PARAM; } + if (!is_extended_advertising_enabled()) { + if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { + return startAdvertising(getLegacyAdvertisingParams()); + } + return BLE_ERROR_NOT_IMPLEMENTED; + } + /* round up */ uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; @@ -1741,6 +1762,13 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { return BLE_ERROR_INVALID_PARAM; } + if (!is_extended_advertising_enabled()) { + if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { + return stopAdvertising(); + } + return BLE_ERROR_NOT_IMPLEMENTED; + } + return _pal_gap.extended_advertising_enable( true, 1, From 834e6c4f9b73da99259d84c96b3c98d978762fe4 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 11:19:38 +0000 Subject: [PATCH 016/361] Update mbed-os/features/FEATURE_BLE/ble/GapAdvertisingData.h --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 128 +++++++++++------- 1 file changed, 79 insertions(+), 49 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 6f8563eaa8..9be9187ff1 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -19,8 +19,11 @@ #include #include +#include #include "blecommon.h" +#include "platform/Span.h" +#include "NonCopyable.h" /** * @addtogroup ble @@ -110,7 +113,7 @@ * errors such as adding an exclusive AD field twice in the advertising * or scan response payload. */ -class GapAdvertisingData +class GapAdvertisingData : public mbed::NonCopyable { public: /*! @@ -531,14 +534,69 @@ public: */ typedef enum Appearance_t Appearance; + GapAdvertisingData(mbed::Span buffer) : + _buffer(buffer), + _minimiseFragmentation(false), + _auto_allocated(false) { + } + + GapAdvertisingData() : + _minimiseFragmentation(false), + _auto_allocated(true) { + uint8_t *buffer = malloc(GAP_ADVERTISING_DATA_MAX_PAYLOAD); + _buffer = mbed::make_Span(buffer, buffer ? GAP_ADVERTISING_DATA_MAX_PAYLOAD : 0); + } + + ~GapAdvertisingData() { + if (_auto_allocated) { + free(_buffer.data()); + } + } + /** - * Construct a GapAdvertising instance with an empty payload. + * Get the subspan of the buffer containing valid data. + * + * @return A Span containing the payload. */ - GapAdvertisingData(void) : - _payload(), - _payloadLen(0), - _appearance(GENERIC_TAG), - _minimiseFragmentation(false) { + void getData(mbed::Span data) { + data = _buffer.first<_payloadLen>(); + } + + /** + * Get the pointer to the advertising payload bytes. + * + * @return A pointer to the payload. + */ + const uint8_t *getPayload() const + { + return _buffer.data(); + } + + /** + * Get the pointer to the advertising payload bytes. + * + * @return A pointer to the payload. + */ + uint8_t *getPayload() { + return _buffer.data(); + } + + /** + * Get the payload length. + * + * @return The payload length in bytes. + */ + uint8_t getPayloadLen(void) const + { + return _payloadLen; + } + + void setMinimiseFragmentation(bool enable = true) { + _minimiseFragmentation = enable; + } + + bool getMinimiseFragmentation() { + return _minimiseFragmentation; } /** @@ -662,30 +720,10 @@ public: */ void clear(void) { - memset(&_payload, 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); + memset(_buffer.data(), 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); _payloadLen = 0; } - /** - * Get the pointer to the advertising payload bytes. - * - * @return A pointer to the payload. - */ - const uint8_t *getPayload(void) const - { - return _payload; - } - - /** - * Get the payload length. - * - * @return The payload length in bytes. - */ - uint8_t getPayloadLen(void) const - { - return _payloadLen; - } - /** * Get the appearance set. * @@ -711,28 +749,20 @@ public: { /* Scan through advertisement data */ for (uint8_t idx = 0; idx < _payloadLen; ) { - uint8_t fieldType = _payload[idx + 1]; + uint8_t fieldType = _buffer[idx + 1]; if (fieldType == type) { - return &_payload[idx]; + return (_buffer.data() + idx); } /* Advance to next field */ - idx += _payload[idx] + 1; + idx += _buffer[idx] + 1; } /* Field not found */ return NULL; } - void setMinimiseFragmentation(bool enable = true) { - _minimiseFragmentation = enable; - } - - bool getMinimiseFragmentation() { - return _minimiseFragmentation; - } - private: /** * Append advertising data based on the specified type. @@ -754,15 +784,15 @@ private: } /* Field length. */ - memset(&_payload[_payloadLen], len + 1, 1); + memset(_buffer.data() + _payloadLen, len + 1, 1); _payloadLen++; /* Field ID. */ - memset(&_payload[_payloadLen], (uint8_t)advDataType, 1); + memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); _payloadLen++; /* Payload. */ - memcpy(&_payload[_payloadLen], payload, len); + memcpy(_buffer.data() + _payloadLen, payload, len); _payloadLen += len; return BLE_ERROR_NONE; @@ -821,13 +851,13 @@ private: case COMPLETE_LIST_128BIT_SERVICE_IDS: case LIST_128BIT_SOLICITATION_IDS: { /* Check if data fits */ - if ((_payloadLen + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + if ((_payloadLen + len) <= _buffer.size()) { /* * Make room for new field by moving the remainder of the * advertisement payload "to the right" starting after the * TYPE field. */ - uint8_t* end = &_payload[_payloadLen]; + uint8_t* end = _buffer.data() +_payloadLen; while (&field[1] < end) { end[len] = *end; @@ -892,7 +922,7 @@ private: if ((_payloadLen - dataLength + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { /* Remove old field */ - while ((field + dataLength + 2) < &_payload[_payloadLen]) { + while ((field + dataLength + 2) < _buffer[_payloadLen]) { *field = field[dataLength + 2]; field++; } @@ -908,10 +938,8 @@ private: return result; } - /** - * Advertising data buffer. - */ - uint8_t _payload[GAP_ADVERTISING_DATA_MAX_PAYLOAD]; +private: + mbed::Span _buffer; /** * Length of the data added to the advertising buffer. @@ -924,6 +952,8 @@ private: uint16_t _appearance; bool _minimiseFragmentation; + + bool _auto_allocated; }; /** From 26f40e07f777368072b94d18aa140dca7d5b363c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 11:43:42 +0000 Subject: [PATCH 017/361] packetisation --- features/FEATURE_BLE/ble/generic/GenericGap.h | 3 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 38 +++++++++++++++---- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 5a278834eb..945da141e7 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -48,7 +48,8 @@ class GenericGap : public ::Gap, public: /* TODO: move to config */ - static const size_t MAX_ADVERTISING_SETS = 64; + static const size_t MAX_ADVERTISING_SETS = 15; + static const size_t MAX_HCI_DATA_LENGTH = 251; /** * Construct a GenericGap instance for a given BLE instance ID. * diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 56b8dce5de..4ff0e65c14 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1693,13 +1693,37 @@ ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdver return BLE_ERROR_NOT_IMPLEMENTED; } - return _pal_gap.set_extended_advertising_data( - handle, - /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, - payload->setMinimiseFragmentation, - payload->getPayloadLen(), - payload->getPayload() - ); + ble_error_t status = BLE_ERROR_NONE; + uint16_t index = 0; + const uint16_t& length = payload->getPayloadLen(); + uint16_t packet_data_length = length; + pal::advertising_fragment_description_t operation; + operation = (length > MAX_HCI_DATA_LENGTH) ? + pal::advertising_fragment_description_t::COMPLETE_FRAGMENT + : operation = pal::advertising_fragment_description_t::FIRST_FRAGMENT; + + while (index < length) { + if ((length - index) > MAX_HCI_DATA_LENGTH) { + packet_data_length = MAX_HCI_DATA_LENGTH; + } else { + packet_data_length = length - index; + operation = pal::advertising_fragment_description_t::LAST_FRAGMENT; + } + + _pal_gap.set_extended_advertising_data( + handle, + packet_data_length, + payload->setMinimiseFragmentation, + packet_data_length, + payload->getPayload() + index + ); + + index += packet_data_length; + + operation = pal::advertising_fragment_description_t::INTERMEDIATE_FRAGMENT; + } + + return status; } ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { From 9d83a8e134be5d4cd6ef339b4550195a04e65313 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 13:09:20 +0000 Subject: [PATCH 018/361] non braking Advertising data deprecation --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 78 ++++++++++++------- 1 file changed, 51 insertions(+), 27 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 9be9187ff1..20bc7031ce 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -113,7 +113,7 @@ * errors such as adding an exclusive AD field twice in the advertising * or scan response payload. */ -class GapAdvertisingData : public mbed::NonCopyable +class AdvertisingData { public: /*! @@ -534,23 +534,23 @@ public: */ typedef enum Appearance_t Appearance; - GapAdvertisingData(mbed::Span buffer) : + AdvertisingData(mbed::Span buffer) : _buffer(buffer), - _minimiseFragmentation(false), - _auto_allocated(false) { + _payloadLen(0) + _appearance(GENERIC_TAG), + _minimiseFragmentation(false) { } - GapAdvertisingData() : - _minimiseFragmentation(false), - _auto_allocated(true) { - uint8_t *buffer = malloc(GAP_ADVERTISING_DATA_MAX_PAYLOAD); - _buffer = mbed::make_Span(buffer, buffer ? GAP_ADVERTISING_DATA_MAX_PAYLOAD : 0); + void setMinimiseFragmentation(bool enable = true) { + _minimiseFragmentation = enable; } - ~GapAdvertisingData() { - if (_auto_allocated) { - free(_buffer.data()); - } + bool getMinimiseFragmentation() const { + return _minimiseFragmentation; + } + + size_t getBufferSize() { + return _buffer.size(); } /** @@ -558,8 +558,8 @@ public: * * @return A Span containing the payload. */ - void getData(mbed::Span data) { - data = _buffer.first<_payloadLen>(); + void getData(mbed::Span &data) { + data = mbed::make_Span(_buffer.data(), _payloadLen); } /** @@ -591,14 +591,6 @@ public: return _payloadLen; } - void setMinimiseFragmentation(bool enable = true) { - _minimiseFragmentation = enable; - } - - bool getMinimiseFragmentation() { - return _minimiseFragmentation; - } - /** * Adds a new field into the payload. * @@ -938,8 +930,16 @@ private: return result; } -private: - mbed::Span _buffer; +protected: + AdvertisingData(const AdvertisingData& other) { + _buffer = mbed::make_Span(other.getPayload(), other.getBufferSize()); + _payloadLen = other.getPayloadLen(); + _appearance = other.getAppearance(); + _minimiseFragmentation = other.getMinimiseFragmentation(); + } + +protected: + mbed::Span _buffer; /** * Length of the data added to the advertising buffer. @@ -952,10 +952,34 @@ private: uint16_t _appearance; bool _minimiseFragmentation; - - bool _auto_allocated; }; +/** + * @deprecated Use AdvertisingData; + */ +class GapAdvertisingData : public AdvertisingData +{ +public: + GapAdvertisingData() : + _buffer(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) { } + + GapAdvertisingData(const GapAdvertisingData& other) : + _buffer(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) + { + memcpy(_payload, other.getPayload(), GAP_ADVERTISING_DATA_MAX_PAYLOAD); + _payloadLen = other.getPayloadLen(); + _appearance = other.getAppearance(); + _minimiseFragmentation = other.getMinimiseFragmentation(); + } + +private: + /** + * Advertising data buffer. + */ + uint8_t _payload[GAP_ADVERTISING_DATA_MAX_PAYLOAD]; +}; + + /** * @} * @} From 944d867c79407d4ec81547a2c9fa6bc97f671f85 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 13:15:20 +0000 Subject: [PATCH 019/361] fix comments and missing comma in constructor --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 20bc7031ce..2e003c2c4c 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -42,7 +42,7 @@ * in an advertisement payload. * * After construction, the advertising payload contained in the instance of - * GapAdvertisingData is empty. Adding new states and named fields can be + * AdvertisingData is empty. Adding new states and named fields can be * achieved by invoking the function addData(), and updating existing state * involves calling the function updateData(). * @@ -61,17 +61,17 @@ * static const uint8_t device_name[] = "HRM"; * * // construct an empty advertising payload - * GapAdvertisingData advertising_data; + * AdvertisingData advertising_data; * * // set the flags of the advertising device * advertising_data.addFlags( - * GapAdvertisingData::LE_GENERAL_DISCOVERABLE | - * GapAdvertisingData::BREDR_NOT_SUPPORTED + * AdvertisingData::LE_GENERAL_DISCOVERABLE | + * AdvertisingData::BREDR_NOT_SUPPORTED * ); * * // set the advertised name of the device * advertising_data.addData( - * GapAdvertisingData::COMPLETE_LOCAL_NAME, + * AdvertisingData::COMPLETE_LOCAL_NAME, * device_name, * sizeof(device_name) * ); @@ -96,7 +96,7 @@ * * @par * For convenience, all appropriate AD types are encapsulated in - * GapAdvertisingData::DataType. + * AdvertisingData::DataType. * * @par * Before the AD Types and their payload (if any) can be inserted into @@ -129,7 +129,7 @@ public: */ enum DataType_t { /** - * Flags, refer to GapAdvertisingData::Flags_t. + * Flags, refer to AdvertisingData::Flags_t. */ FLAGS = 0x01, @@ -199,7 +199,7 @@ public: SERVICE_DATA = 0x16, /** - * Appearance, refer to GapAdvertisingData::Appearance_t. + * Appearance, refer to AdvertisingData::Appearance_t. */ APPEARANCE = 0x19, @@ -216,7 +216,7 @@ public: }; /** - * Alias for GapAdvertisingData::DataType_t. + * Alias for AdvertisingData::DataType_t. * * @deprecated Future releases will drop this type alias. */ @@ -262,7 +262,7 @@ public: }; /** - * Alias for GapAdvertisingData::Flags_t. + * Alias for AdvertisingData::Flags_t. * * @deprecated Future releases will drop this type alias. */ @@ -528,7 +528,7 @@ public: }; /** - * Alias for GapAdvertisingData::Appearance_t. + * Alias for AdvertisingData::Appearance_t. * * @deprecated Future releases will drop this type alias. */ @@ -536,7 +536,7 @@ public: AdvertisingData(mbed::Span buffer) : _buffer(buffer), - _payloadLen(0) + _payloadLen(0), _appearance(GENERIC_TAG), _minimiseFragmentation(false) { } @@ -661,12 +661,12 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * GapAdvertisingData::APPEARANCE as the field type. + * AdvertisingData::APPEARANCE as the field type. */ ble_error_t addAppearance(Appearance appearance = GENERIC_TAG) { _appearance = appearance; - return addData(GapAdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); + return addData(AdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); } /** @@ -680,11 +680,11 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * GapAdvertisingData::FLAGS as the field type. + * AdvertisingData::FLAGS as the field type. */ ble_error_t addFlags(uint8_t flags = LE_GENERAL_DISCOVERABLE) { - return addData(GapAdvertisingData::FLAGS, &flags, 1); + return addData(AdvertisingData::FLAGS, &flags, 1); } /** @@ -697,12 +697,12 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * GapAdvertisingData::TX_POWER_LEVEL as the field type. + * AdvertisingData::TX_POWER_LEVEL as the field type. */ ble_error_t addTxPower(int8_t txPower) { /* To Do: Basic error checking to make sure txPower is in range. */ - return addData(GapAdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); + return addData(AdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); } /** @@ -802,7 +802,7 @@ private: uint8_t* findField(DataType_t type) { return const_cast( - static_cast(this)->findField(type) + static_cast(this)->findField(type) ); } From 93b0b9f6e2f1810d4d05bdad9be8214a351916a2 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 13:29:31 +0000 Subject: [PATCH 020/361] fix getting value instead of address --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 2e003c2c4c..3570879d33 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -914,7 +914,7 @@ private: if ((_payloadLen - dataLength + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { /* Remove old field */ - while ((field + dataLength + 2) < _buffer[_payloadLen]) { + while ((field + dataLength + 2) < _buffer.data() + _payloadLen) { *field = field[dataLength + 2]; field++; } From 019b0c2146b9a4be4eb6531157655d309b629037 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 13:39:30 +0000 Subject: [PATCH 021/361] added constructor to use with deprecated data --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 3570879d33..229cf1bc5f 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -541,6 +541,13 @@ public: _minimiseFragmentation(false) { } + AdvertisingData(uint8_t* buffer, size_t buffer_size) : + _buffer(buffer, buffer_size), + _payloadLen(0), + _appearance(GENERIC_TAG), + _minimiseFragmentation(false) { + } + void setMinimiseFragmentation(bool enable = true) { _minimiseFragmentation = enable; } @@ -549,7 +556,7 @@ public: return _minimiseFragmentation; } - size_t getBufferSize() { + size_t getBufferSize() const { return _buffer.size(); } @@ -961,10 +968,10 @@ class GapAdvertisingData : public AdvertisingData { public: GapAdvertisingData() : - _buffer(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) { } + AdvertisingData(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) { } GapAdvertisingData(const GapAdvertisingData& other) : - _buffer(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) + AdvertisingData(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) { memcpy(_payload, other.getPayload(), GAP_ADVERTISING_DATA_MAX_PAYLOAD); _payloadLen = other.getPayloadLen(); From 4a86b3dd100ee8223369513233446a20a474a8b6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 14:02:20 +0000 Subject: [PATCH 022/361] typo in var name --- features/FEATURE_BLE/ble/pal/GapTypes.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 6a4d71f276..fe93749ff0 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -829,7 +829,7 @@ struct advertising_data_status_t : SafeEnum( static_cast(value) ) From 52f54c032ae6ff770e9c0cadeb01f03b264b3bf2 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 14:02:57 +0000 Subject: [PATCH 023/361] compiilation errors --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 2 +- features/FEATURE_BLE/ble/GapAdvertisingParams.h | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 229cf1bc5f..e0f0d50296 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -938,7 +938,7 @@ private: } protected: - AdvertisingData(const AdvertisingData& other) { + AdvertisingData(AdvertisingData& other) { _buffer = mbed::make_Span(other.getPayload(), other.getBufferSize()); _payloadLen = other.getPayloadLen(); _appearance = other.getAppearance(); diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 6f438f9e7e..898e7d24a7 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -262,14 +262,12 @@ class GapExtendedAdvertisingParams { _advType(ble::EXT_ADV_CONNECTABLE_UNDIRECTED), _minInterval(0), _maxInterval(0), - _maxDuration(0), _peerAddressType(), _ownAddressType(), _policy(ble::ADV_POLICY_IGNORE_WHITELIST), _primaryPhy(ble::phy_t::LE_1M), _secondaryPhy(ble::phy_t::LE_1M), _peerAddress(), - _maxEvents(0), _txPower(0), _eventNumber(0), _channel37(1), @@ -453,7 +451,7 @@ class GapExtendedAdvertisingParams { } BLEProtocol::AddressBytes_t* getPeerAddress() { - return _peerAddress; + return &_peerAddress; }; ble::peer_address_type_t getPeerAddressType() { From 060d2f52165cb18339f1898bc8e23449e6dbfbf0 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 14:29:53 +0000 Subject: [PATCH 024/361] advertising data only contains advertising data --- features/FEATURE_BLE/ble/Gap.h | 22 +++++------- features/FEATURE_BLE/ble/GapAdvertisingData.h | 35 +++++-------------- 2 files changed, 16 insertions(+), 41 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 044f4193ae..cd981fe1ae 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -28,12 +28,6 @@ #include "platform/mbed_toolchain.h" #include "platform/NonCopyable.h" -/* Forward declarations for classes that are only used for pointers or - references. */ -class GapAdvertisingParams; -class GapScanningParams; -class GapAdvertisingData; - /** * @addtogroup ble * @{ @@ -88,18 +82,18 @@ class GapAdvertisingData; * Gap& gap; * * // construct the packet to advertise - * GapAdvertisingData advertising_data; + * AdvertisingData advertising_data; * * // Add advertiser flags * advertising_data.addFlags( - * GapAdvertisingData::LE_GENERAL_DISCOVERABLE | - * GapAdvertisingData::BREDR_NOT_SUPPORTED + * AdvertisingData::LE_GENERAL_DISCOVERABLE | + * AdvertisingData::BREDR_NOT_SUPPORTED * ); * * // Add the name of the device to the advertising data * static const uint8_t device_name[] = "HRM"; * advertising_data.addData( - * GapAdvertisingData::COMPLETE_LOCAL_NAME, + * AdvertisingData::COMPLETE_LOCAL_NAME, * device_name, * sizeof(device_name) * ); @@ -1182,14 +1176,14 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { + virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false) { (void) handle; (void) payload; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { + virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response) { (void) handle; (void) response; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1885,7 +1879,7 @@ public: * * @return BLE_ERROR_NONE if the new appearance was set correctly. */ - virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) + virtual ble_error_t setAppearance(AdvertisingData::Appearance appearance) { (void)appearance; @@ -1901,7 +1895,7 @@ public: * @return BLE_ERROR_NONE if the device-appearance was fetched correctly * from the underlying BLE stack. */ - virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) + virtual ble_error_t getAppearance(AdvertisingData::Appearance *appearanceP) { (void)appearanceP; diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index e0f0d50296..773520309f 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -536,24 +536,12 @@ public: AdvertisingData(mbed::Span buffer) : _buffer(buffer), - _payloadLen(0), - _appearance(GENERIC_TAG), - _minimiseFragmentation(false) { + _payloadLen(0) { } AdvertisingData(uint8_t* buffer, size_t buffer_size) : _buffer(buffer, buffer_size), - _payloadLen(0), - _appearance(GENERIC_TAG), - _minimiseFragmentation(false) { - } - - void setMinimiseFragmentation(bool enable = true) { - _minimiseFragmentation = enable; - } - - bool getMinimiseFragmentation() const { - return _minimiseFragmentation; + _payloadLen(0) { } size_t getBufferSize() const { @@ -672,7 +660,6 @@ public: */ ble_error_t addAppearance(Appearance appearance = GENERIC_TAG) { - _appearance = appearance; return addData(AdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); } @@ -732,7 +719,12 @@ public: */ uint16_t getAppearance(void) const { - return (uint16_t)_appearance; + uint16_t appearance = GENERIC_TAG; + uint8_t *field = findField(AdvertisingData::APPEARANCE); + if (field) { + memcpy((uint8_t*)appearance, field, 2); + } + return appearance; } /** @@ -941,8 +933,6 @@ protected: AdvertisingData(AdvertisingData& other) { _buffer = mbed::make_Span(other.getPayload(), other.getBufferSize()); _payloadLen = other.getPayloadLen(); - _appearance = other.getAppearance(); - _minimiseFragmentation = other.getMinimiseFragmentation(); } protected: @@ -952,13 +942,6 @@ protected: * Length of the data added to the advertising buffer. */ uint8_t _payloadLen; - - /** - * Appearance value. - */ - uint16_t _appearance; - - bool _minimiseFragmentation; }; /** @@ -975,8 +958,6 @@ public: { memcpy(_payload, other.getPayload(), GAP_ADVERTISING_DATA_MAX_PAYLOAD); _payloadLen = other.getPayloadLen(); - _appearance = other.getAppearance(); - _minimiseFragmentation = other.getMinimiseFragmentation(); } private: From a5e1bdb97e85e4ca4c2e2e8b95b01d6fbbe3ca26 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 14:30:12 +0000 Subject: [PATCH 025/361] missing parens --- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 945da141e7..25ed71a612 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -488,7 +488,7 @@ private: uint8_t byte = bit_number / 8; uint8_t bit = bit_number - byte; bytes += byte; - *bytes |= 0x01 >> bit; + *bytes |= (0x01 >> bit); return true; } @@ -499,7 +499,7 @@ private: uint8_t byte = bit_number / 8; uint8_t bit = bit_number - byte; bytes += byte - *bytes &= 0x00 >> bit; + *bytes &= (0x00 >> bit); return true; } }; From 87482b55300d6fe042b4d71c49f4ae852e426221 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 15:02:18 +0000 Subject: [PATCH 026/361] compilation errors fixed --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 6 +++--- .../FEATURE_BLE/source/generic/GenericGap.cpp | 16 ++++++++-------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 773520309f..5235ef1bca 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -720,7 +720,7 @@ public: uint16_t getAppearance(void) const { uint16_t appearance = GENERIC_TAG; - uint8_t *field = findField(AdvertisingData::APPEARANCE); + const uint8_t *field = findField(AdvertisingData::APPEARANCE); if (field) { memcpy((uint8_t*)appearance, field, 2); } diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 25ed71a612..fe14e6b00c 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -488,7 +488,7 @@ private: uint8_t byte = bit_number / 8; uint8_t bit = bit_number - byte; bytes += byte; - *bytes |= (0x01 >> bit); + *bytes = *bytes | (0x01 >> bit); return true; } @@ -498,8 +498,8 @@ private: } uint8_t byte = bit_number / 8; uint8_t bit = bit_number - byte; - bytes += byte - *bytes &= (0x00 >> bit); + bytes += byte; + *bytes = *bytes & (0x00 >> bit); return true; } }; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 4ff0e65c14..42b4c3001e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1628,10 +1628,10 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert case ADV_NON_CONNECTABLE_UNDIRECTED: case EXT_ADV_NON_CONNECTABLE_DIRECTED: case EXT_ADV_SCANNABLE_DIRECTED: - use_type = AddressUseType_t::PERIPHERAL_NON_CONNECTABLE + use_type = PERIPHERAL_NON_CONNECTABLE; break; default: - use_type = AddressUseType_t::PERIPHERAL_CONNECTABLE; + use_type = PERIPHERAL_CONNECTABLE; } return _pal_gap.set_extended_advertising_parameters( @@ -1642,14 +1642,14 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, (pal::own_address_type_t)get_own_address_type(use_type), pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, - params->getPeerAddress(), + ble::address_t(), (pal::advertising_filter_policy_t)_advertising_filter_policy, - (pal::advertising_power_t)params->getTxPower(), - params->getPrimaryPhy(), - params->getSecondaryMaxSkip(), - params->getSecondaryPhy(), + 0, + ble::phy_set_t::PHY_SET_1M, + 0, + ble::phy_set_t::PHY_SET_1M, 0xFF, - params->getScanRequestNotification() + true ); } From 8794c0b43b8cc4a2b14df9437137568310a28c5f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 16:15:10 +0000 Subject: [PATCH 027/361] make packetisation common --- features/FEATURE_BLE/ble/generic/GenericGap.h | 10 +-- .../FEATURE_BLE/source/generic/GenericGap.cpp | 65 ++++++++++--------- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index fe14e6b00c..df027ffb41 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -88,9 +88,9 @@ public: ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params); - ble_error_t setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload); + ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false); - ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response); + ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response, bool minimiseFragmentation = false); ble_error_t startAdvertising(AdvHandle_t handle, uint8_t maxEvents = 0, uint32_t maxDuration = 0); @@ -227,12 +227,12 @@ public: /** * @see Gap::setAppearance */ - virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance); + virtual ble_error_t setAppearance(AdvertisingData::Appearance appearance); /** * @see Gap::getAppearance */ - virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP); + virtual ble_error_t getAppearance(AdvertisingData::Appearance *appearanceP); /** * @see Gap::setTxPower @@ -376,6 +376,8 @@ public: ); private: + ble_error_t setAdvertisingData(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse); + /** @note Implements ConnectionEventMonitor. * @copydoc ConnectionEventMonitor::set_connection_event_handler */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 42b4c3001e..fe08467d90 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -733,12 +733,12 @@ ble_error_t GenericGap::getDeviceName(uint8_t *deviceName, unsigned *lengthP) return BLE_ERROR_NONE; } -ble_error_t GenericGap::setAppearance(GapAdvertisingData::Appearance appearance) +ble_error_t GenericGap::setAppearance(AdvertisingData::Appearance appearance) { return _gap_service.set_appearance(appearance); } -ble_error_t GenericGap::getAppearance(GapAdvertisingData::Appearance *appearanceP) +ble_error_t GenericGap::getAppearance(AdvertisingData::Appearance *appearanceP) { if (appearanceP == NULL) { return BLE_ERROR_INVALID_PARAM; @@ -1681,14 +1681,26 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend ); } -ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdvertisingData* payload) { +ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation) { + return setAdvertisingData(handle, payload, minimiseFragmentation, false); +} + +ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response, bool minimiseFragmentation) { + return setAdvertisingData(handle, response, minimiseFragmentation, true); +} + +ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const GapAdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse) { if (!get_adv_set_bit(_existing_sets, handle) || !payload) { return BLE_ERROR_INVALID_PARAM; } if (!is_extended_advertising_enabled()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - memcpy(&getLegacyAdvertisingPayload(), payload, sizeof(GapAdvertisingData)); + if (scan_reponse) { + memcpy(&getLegacyAdvertisingPayload(), payload, sizeof(AdvertisingData)); + } else { + memcpy(&getLegacyAdvertisingScanResponse(), payload, sizeof(AdvertisingData)); + } } return BLE_ERROR_NOT_IMPLEMENTED; } @@ -1710,13 +1722,23 @@ ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdver operation = pal::advertising_fragment_description_t::LAST_FRAGMENT; } - _pal_gap.set_extended_advertising_data( - handle, - packet_data_length, - payload->setMinimiseFragmentation, - packet_data_length, - payload->getPayload() + index - ); + if (scan_reponse) { + _pal_gap.set_extended_advertising_data( + handle, + operation, + minimiseFragmentation, + packet_data_length, + payload->getPayload() + index + ); + } else { + _pal_gap.set_extended_advertising_data( + handle, + operation, + minimiseFragmentation, + packet_data_length, + payload->getPayload() + index + ); + } index += packet_data_length; @@ -1726,27 +1748,6 @@ ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const GapAdver return status; } -ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const GapAdvertisingData* response) { - if (!get_adv_set_bit(_existing_sets, handle) || !response) { - return BLE_ERROR_INVALID_PARAM; - } - - if (!is_extended_advertising_enabled()) { - if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - memcpy(&getLegacyAdvertisingScanResponse(), response, sizeof(GapAdvertisingData)); - } - return BLE_ERROR_NOT_IMPLEMENTED; - } - - return _pal_gap.set_extended_scan_response_data( - handle, - /*TODO fragment*/ pal::advertising_fragment_description_t::FIRST_FRAGMENT, - response->setMinimiseFragmentation, - response->getPayloadLen(), - response->getPayload() - ); -} - ble_error_t GenericGap::startAdvertising( AdvHandle_t handle, uint8_t maxEvents, From 78a4bdda8a7a57a5114aa4e4a9ef10f5eca53564 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 17:29:54 +0000 Subject: [PATCH 028/361] type translation --- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 22 ++++++++++++++----- features/FEATURE_BLE/ble/pal/GapTypes.h | 3 +++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 7 +++--- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 898e7d24a7..8355a3818b 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -440,7 +440,7 @@ class GapExtendedAdvertisingParams { return _notifyOnScan; } - /**/ + /* helper get functions */ uint32_t getMinPrimaryInterval() const { return _minInterval; @@ -450,22 +450,34 @@ class GapExtendedAdvertisingParams { return _maxInterval; } - BLEProtocol::AddressBytes_t* getPeerAddress() { + BLEProtocol::AddressBytes_t* getPeerAddress() const { return &_peerAddress; }; - ble::peer_address_type_t getPeerAddressType() { + ble::peer_address_type_t getPeerAddressType() const { return _peerAddressType; }; - ble::phy_t getPrimaryPhy() { + ble::phy_t getPrimaryPhy() const { return _primaryPhy; } - ble::phy_t getSecondaryPhy() { + ble::phy_t getSecondaryPhy() const { return _secondaryPhy; } + bool getChannel37() const { + return _channel37; + } + + bool getChannel38() const { + return _channel37; + } + + bool getChannel39() const { + return _channel37; + } + private: ble::advertising_type_t _advType; uint32_t _minInterval; diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index fe93749ff0..488b3b6c08 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -211,6 +211,9 @@ struct advertising_channel_map_t : SafeEnum */ advertising_channel_map_t(type value) : SafeEnum(value) { } + + advertising_channel_map_t(bool ch37, bool ch38, bool ch39) { + SafeEnum(ch37 | (ch38 << 1) | (ch39 << 2)) { } }; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index fe08467d90..7088ac6a7b 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1619,11 +1619,10 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return BLE_ERROR_NONE; } - pal::advertising_event_properties_t event_properties;//TODO - ble::advertising_type_t adv_type = params->getAdvertisingType(); + pal::advertising_event_properties_t event_properties; AddressUseType_t use_type; - switch(adv_type) { + switch(params->getAdvertisingType()) { case ADV_SCANNABLE_UNDIRECTED: case ADV_NON_CONNECTABLE_UNDIRECTED: case EXT_ADV_NON_CONNECTABLE_DIRECTED: @@ -1658,7 +1657,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend return BLE_ERROR_INVALID_PARAM; } - pal::advertising_channel_map_t channel_map; /*TODO translate*/ + pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); pal::advertising_event_properties_t event_properties;//TODO //params->getAdvertisingType() From e58928def167c321bd74fc9da6e268b13780666e Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 11:08:43 +0000 Subject: [PATCH 029/361] Move advertising event and advertising event data status to ble. --- features/FEATURE_BLE/ble/BLETypes.h | 119 ++++++++++++++++++++++---- features/FEATURE_BLE/ble/pal/PalGap.h | 2 +- 2 files changed, 105 insertions(+), 16 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 74168c6ae4..64b7bbe8f6 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -154,27 +154,116 @@ enum advertising_type_t { * * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. */ - ADV_NON_CONNECTABLE_UNDIRECTED, + ADV_NON_CONNECTABLE_UNDIRECTED +}; +struct advertising_data_status_t : SafeEnum{ + enum type { + COMPLETE = 0x00, + INCOMPLETE_MORE_DATA = 0x01, + INCOMPLETE_DATA_TRUNCATED = 0x02 + }; - /* extended advertising */ - EXT_ADV_CONNECTABLE_UNDIRECTED, + /** + * Construct a new advertising_data_status_t value. + */ + advertising_data_status_t(type value) : + SafeEnum(value) { } - EXT_ADV_NON_CONNECTABLE_DIRECTED, - - EXT_ADV_SCANNABLE_DIRECTED, - - EXT_ADV_HIGH_DUTY_CYCLE_CONNECTABLE_DIRECTED + /** + * Explicit constructor from a raw value. + */ + explicit advertising_data_status_t(uint8_t raw_value) : + SafeEnum( + static_cast(raw_value) + ) + { } }; struct advertising_event_t { - uint8_t connectable_advertising:1; - uint8_t scannable_advertising:1; - uint8_t directed_advertising:1; - uint8_t scan_response:1; - uint8_t legacy:1; - uint8_t complete:1; - uint8_t last:1; + explicit advertising_event_t(uint8_t value) : value(value) { } + + advertising_event_t(advertising_type_t legacy_type) + { + switch (legacy_type) { + case ADV_CONNECTABLE_UNDIRECTED: + value = 0x23; + break; + case ADV_CONNECTABLE_DIRECTED: + value = 0x25; + break; + case ADV_SCANNABLE_UNDIRECTED: + value = 0x22; + break; + case ADV_NON_CONNECTABLE_UNDIRECTED: + value = 0x20; + break; + } + } + + bool connectable() const + { + return static_cast(value & (1 << 0)); + } + + bool scannable_advertising() const + { + return static_cast(value & (1 << 1)); + } + + bool directed_advertising() const + { + return static_cast(value & (1 << 2)); + } + + bool scan_response() const + { + return static_cast(value & (1 << 3)); + } + + bool legacy_advertising() const + { + return static_cast(value & (1 << 4)); + } + + advertising_data_status_t data_status() const + { + return static_cast((value >> 5) & 0x03); + } + + bool complete() const + { + return data_status() == advertising_data_status_t::COMPLETE; + } + + bool more_data_to_come() const + { + return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; + } + + bool truncated() const + { + return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; + } + + friend bool operator==( + const advertising_event_t &lhs, + const advertising_event_t &rhs + ) + { + return lhs.value == rhs.value; + } + + friend bool operator!=( + const advertising_event_t &lhs, + const advertising_event_t &rhs + ) + { + return !(rhs == lhs); + } + +private: + uint8_t value; }; /** diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index e9e1eb17cc..ac160d66dc 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -156,7 +156,7 @@ struct Gap { * report event. */ virtual void on_extended_advertising_report( - extended_advertising_report_event_type_t event_type, + advertising_event_t event_type, const connection_peer_address_type_t *address_type, const address_t &address, phy_t primary_phy, From 44d8545dc86e6dd1995c7ffce12f666310f0983d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 11:09:20 +0000 Subject: [PATCH 030/361] BLE: Add ANONYMOUS in peer_advertising_type_t --- features/FEATURE_BLE/ble/BLETypes.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 64b7bbe8f6..453b9888fd 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -746,7 +746,12 @@ struct peer_address_type_t :SafeEnum { /** * A Random static address used as a device identity address. */ - RANDOM_STATIC_IDENTITY + RANDOM_STATIC_IDENTITY, + + /** + * No address provided (anonymous advertisement) + */ + ANONYMOUS = 0xFF }; /** From f83f32948a9e44bf56aa213d1eda7044f3b301e6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 11:10:08 +0000 Subject: [PATCH 031/361] BLE: Fix typo in arguments name. --- features/FEATURE_BLE/ble/Gap.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index cd981fe1ae..cdbe78f929 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1031,12 +1031,12 @@ public: virtual void onScanRequest( AdvHandle_t advHandle, - const BLEProtocol::AddressBytes_t peerAddres, - PeerAddressType_t peerAddresType + const BLEProtocol::AddressBytes_t peerAddress, + PeerAddressType_t peerAddressType ) { (void) advHandle; - (void) peerAddres; - (void) peerAddresType; + (void) peerAddress; + (void) peerAddressType; } virtual void onAdvertisingEnd( @@ -1053,15 +1053,15 @@ public: void onAdvertisingReport( ble::advertising_event_t type, - PeerAddressType_t peerAddrType, - BLEProtocol::AddressBytes_t peerAddr, + PeerAddressType_t peerAddressType, + BLEProtocol::AddressBytes_t peerAddress, uint8_t advertisingDataLen, const uint8_t *advertisingData, AdvReportOptionalInformation *extraInfo ) { (void) type; - (void) peerAddrType; - (void) peerAddr; + (void) peerAddressType; + (void) peerAddress; (void) advertisingDataLen; (void) advertisingData; (void) extraInfo; From 14b24d324c2cc7d62fdf6deb3a062b79c7ac5545 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 13:26:49 +0000 Subject: [PATCH 032/361] BLE: Move advertising_handle_t into ble namespace. --- features/FEATURE_BLE/ble/BLETypes.h | 6 ++++++ features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/pal/GapTypes.h | 7 ------- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 453b9888fd..e873eb3517 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -48,6 +48,12 @@ typedef uintptr_t connection_handle_t; */ typedef uint16_t attribute_handle_t; +/** + * Handle of an advertising set. + * + * @note Range of valid handle is comprised between 0x00 and 0xEF. + */ +typedef uint8_t advertising_handle_t; /** * Inclusive range of GATT attributes handles. diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index cdbe78f929..3a618f649f 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1008,7 +1008,7 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; - typedef uint8_t AdvHandle_t; + typedef ble::advertising_handle_t AdvHandle_t; static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 488b3b6c08..f0cca80732 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -546,13 +546,6 @@ struct connection_role_t : SafeEnum { SafeEnum(raw_value) { } }; -/** - * Handle of an advertising set. - * - * @note Range of valid handle is comprised between 0x00 and 0xEF. - */ -typedef uint8_t advertising_handle_t; - /** * Properties of an advertising event. */ From f9309059471cd4a232de5559e422e20a1a23380b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 13:28:41 +0000 Subject: [PATCH 033/361] BLE: Regactor Gap::EventHandler::onScanRequest signature. --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 3a618f649f..9278ace4b1 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1031,8 +1031,8 @@ public: virtual void onScanRequest( AdvHandle_t advHandle, - const BLEProtocol::AddressBytes_t peerAddress, - PeerAddressType_t peerAddressType + PeerAddressType_t peerAddressType, + const BLEProtocol::AddressBytes_t &peerAddress ) { (void) advHandle; (void) peerAddress; From dee48e71e37b236cc5f58ee5813b889668c55e26 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 13:30:19 +0000 Subject: [PATCH 034/361] BLE: Typedef ble::advertising_event_t into Gap::AdvertisingEventType_t --- features/FEATURE_BLE/ble/Gap.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9278ace4b1..71d142dbd2 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1009,6 +1009,7 @@ public: GapShutdownCallbackChain_t; typedef ble::advertising_handle_t AdvHandle_t; + typedef ble::advertising_event_t AdvertisingEventType_t; static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; @@ -1052,7 +1053,7 @@ public: } void onAdvertisingReport( - ble::advertising_event_t type, + AdvertisingEventType_t type, PeerAddressType_t peerAddressType, BLEProtocol::AddressBytes_t peerAddress, uint8_t advertisingDataLen, From 5e707731f21f1b02e11d5373f5cd3c5af9ebecf2 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 13:32:58 +0000 Subject: [PATCH 035/361] BLE: Wrap advertising data in a span. --- features/FEATURE_BLE/ble/Gap.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 71d142dbd2..648edd34b3 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -27,6 +27,7 @@ #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" #include "platform/NonCopyable.h" +#include "platform/Span.h" /** * @addtogroup ble @@ -1056,14 +1057,12 @@ public: AdvertisingEventType_t type, PeerAddressType_t peerAddressType, BLEProtocol::AddressBytes_t peerAddress, - uint8_t advertisingDataLen, - const uint8_t *advertisingData, + mbed::Span advertisingData, AdvReportOptionalInformation *extraInfo ) { (void) type; (void) peerAddressType; (void) peerAddress; - (void) advertisingDataLen; (void) advertisingData; (void) extraInfo; } From d1e3800e798819c3f7d3de453e93d7a7851309a1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 13:41:00 +0000 Subject: [PATCH 036/361] BLE: Refactor AdvReportOptionalInformation and onAdvertisingReport --- features/FEATURE_BLE/ble/Gap.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 648edd34b3..3b486839aa 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1015,7 +1015,7 @@ public: static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; - struct AdvReportOptionalInformation { + struct AdvReportExtraInformation { PeerAddressType_t directAddressType; BLEProtocol::AddressBytes_t directAddress; Phy_t primaryPhy; @@ -1056,9 +1056,9 @@ public: void onAdvertisingReport( AdvertisingEventType_t type, PeerAddressType_t peerAddressType, - BLEProtocol::AddressBytes_t peerAddress, + BLEProtocol::AddressBytes_t const &peerAddress, mbed::Span advertisingData, - AdvReportOptionalInformation *extraInfo + const AdvReportExtraInformation &extraInfo ) { (void) type; (void) peerAddressType; From 2f53ee896c56fc2ed7430d51af519b8ebe15eeb4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 14:22:36 +0000 Subject: [PATCH 037/361] BLE: Add setters to advertising_event_t and use it in GapExtendedAdvertisingParams. --- features/FEATURE_BLE/ble/BLETypes.h | 52 +++++++++++++++++++ .../FEATURE_BLE/ble/GapAdvertisingParams.h | 6 +-- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index e873eb3517..f93331f23a 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -207,31 +207,83 @@ struct advertising_event_t { } } + advertising_event_t() : value(0) { } + bool connectable() const { return static_cast(value & (1 << 0)); } + advertising_event_t& connectable(bool v) + { + if (v) { + value |= (1 << 0); + } else { + value &= ~(1 << 0); + } + return *this; + } + bool scannable_advertising() const { return static_cast(value & (1 << 1)); } + advertising_event_t& scannable_advertising(bool v) + { + if (v) { + value |= (1 << 1); + } else { + value &= ~(1 << 1); + } + return *this; + } + bool directed_advertising() const { return static_cast(value & (1 << 2)); } + advertising_event_t& directed_advertising(bool v) + { + if (v) { + value |= (1 << 2); + } else { + value &= ~(1 << 2); + } + return *this; + } + bool scan_response() const { return static_cast(value & (1 << 3)); } + advertising_event_t& scan_response(bool v) + { + if (v) { + value |= (1 << 3); + } else { + value &= ~(1 << 3); + } + return *this; + } + bool legacy_advertising() const { return static_cast(value & (1 << 4)); } + advertising_event_t& legacy_advertising(bool v) + { + if (v) { + value |= (1 << 4); + } else { + value &= ~(1 << 4); + } + return *this; + } + advertising_data_status_t data_status() const { return static_cast((value >> 5) & 0x03); diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 8355a3818b..0c718cae62 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -259,7 +259,7 @@ private: class GapExtendedAdvertisingParams { GapExtendedAdvertisingParams() : - _advType(ble::EXT_ADV_CONNECTABLE_UNDIRECTED), + _advType(ble::advertising_event_t().connectable(true).scannable_advertising(true)), _minInterval(0), _maxInterval(0), _peerAddressType(), @@ -292,7 +292,7 @@ class GapExtendedAdvertisingParams { * * @return Advertising type. */ - ble::advertising_type_t getType() { + ble::advertising_event_t getType() { return _advType; } @@ -479,7 +479,7 @@ class GapExtendedAdvertisingParams { } private: - ble::advertising_type_t _advType; + ble::advertising_event_t _advType; uint32_t _minInterval; uint32_t _maxInterval; ble::peer_address_type_t _peerAddressType; From 426de4a2d9b008ded885cdc358f30a76d1edc6a2 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 15:42:41 +0000 Subject: [PATCH 038/361] BLE: Fix GapAdvertisingData copy constructor. --- features/FEATURE_BLE/ble/GapAdvertisingData.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 5235ef1bca..52aa7e991d 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -930,9 +930,9 @@ private: } protected: - AdvertisingData(AdvertisingData& other) { - _buffer = mbed::make_Span(other.getPayload(), other.getBufferSize()); - _payloadLen = other.getPayloadLen(); + AdvertisingData(const AdvertisingData& other) : + _buffer(other._buffer), + _payloadLen(other._payloadLen) { } protected: From e951fa15ffd81c419707f38415e77f9e185b5ab7 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 15:43:21 +0000 Subject: [PATCH 039/361] BLE: Fix GapExtendedAdvertisingParams::getPeerAddress return type. --- features/FEATURE_BLE/ble/GapAdvertisingParams.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 0c718cae62..20b43a5ec7 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -450,8 +450,8 @@ class GapExtendedAdvertisingParams { return _maxInterval; } - BLEProtocol::AddressBytes_t* getPeerAddress() const { - return &_peerAddress; + const BLEProtocol::AddressBytes_t& getPeerAddress() const { + return _peerAddress; }; ble::peer_address_type_t getPeerAddressType() const { From fb804bf85af329aee81e16fe9a03f856071b3ef6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 17:32:48 +0000 Subject: [PATCH 040/361] BLE: Fix GapExtendedAdvertisingParams visibility and constness. --- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 20b43a5ec7..cb95fcbb7b 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -258,6 +258,8 @@ private: }; class GapExtendedAdvertisingParams { + +public: GapExtendedAdvertisingParams() : _advType(ble::advertising_event_t().connectable(true).scannable_advertising(true)), _minInterval(0), @@ -292,11 +294,11 @@ class GapExtendedAdvertisingParams { * * @return Advertising type. */ - ble::advertising_event_t getType() { + ble::advertising_event_t getType() const { return _advType; } - bool getAnonymousAdvertising() { + bool getAnonymousAdvertising() const { return _anonymous; } @@ -309,7 +311,7 @@ class GapExtendedAdvertisingParams { ble_error_t getPrimaryInterval( uint32_t *min /* ms */, uint32_t *max /* ms */ - ) { + ) const { if (!min || !max) { return BLE_ERROR_INVALID_PARAM; } @@ -330,7 +332,7 @@ class GapExtendedAdvertisingParams { bool *channel37, bool *channel38, bool *channel39 - ) { + ) const { if (!channel37 || !channel38 || !channel39) { return BLE_ERROR_INVALID_PARAM; } @@ -350,7 +352,7 @@ class GapExtendedAdvertisingParams { _channel39 = channel39; } - BLEProtocol::AddressType::Type getOwnAddressType() { + BLEProtocol::AddressType::Type getOwnAddressType() const { return _ownAddressType; } @@ -363,7 +365,7 @@ class GapExtendedAdvertisingParams { ble_error_t getPeer( BLEProtocol::AddressBytes_t *address, ble::peer_address_type_t *addressType - ) { + ) const { if (!address || !addressType) { return BLE_ERROR_INVALID_PARAM; } @@ -380,7 +382,7 @@ class GapExtendedAdvertisingParams { _peerAddressType = addressType; }; - ble::advertising_policy_mode_t getPolicyMode() { + ble::advertising_policy_mode_t getPolicyMode() const { return _policy; } @@ -390,7 +392,7 @@ class GapExtendedAdvertisingParams { _policy = mode; } - int8_t getTxPower() { + int8_t getTxPower() const { return _txPower; } @@ -403,7 +405,7 @@ class GapExtendedAdvertisingParams { ble_error_t getPhy( ble::phy_t *primaryPhy, ble::phy_t *secondaryPhy - ) { + ) const { if (!primaryPhy || !secondaryPhy) { return BLE_ERROR_INVALID_PARAM; } @@ -420,7 +422,7 @@ class GapExtendedAdvertisingParams { _secondaryPhy = secondaryPhy; } - uint8_t getSecondaryMaxSkip() { + uint8_t getSecondaryMaxSkip() const { return _eventNumber; } @@ -436,7 +438,7 @@ class GapExtendedAdvertisingParams { _notifyOnScan = enable; } - bool getScanRequestNotification() { + bool getScanRequestNotification() const { return _notifyOnScan; } @@ -454,15 +456,15 @@ class GapExtendedAdvertisingParams { return _peerAddress; }; - ble::peer_address_type_t getPeerAddressType() const { + ble::peer_address_type_t getPeerAddressType() const { return _peerAddressType; }; - ble::phy_t getPrimaryPhy() const { + ble::phy_t getPrimaryPhy() const { return _primaryPhy; } - ble::phy_t getSecondaryPhy() const { + ble::phy_t getSecondaryPhy() const { return _secondaryPhy; } From 0c1e01952b0047466fcd08b8a74fb1020aae888d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 17:42:03 +0000 Subject: [PATCH 041/361] Compilation fixes --- features/FEATURE_BLE/ble/generic/GenericGap.h | 64 ++++++++ features/FEATURE_BLE/ble/pal/GapTypes.h | 27 ++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 139 +++++++++++++++--- .../TARGET_CORDIO/source/CordioPalGap.cpp | 4 +- platform/mbed_toolchain.h | 2 +- 5 files changed, 210 insertions(+), 26 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index df027ffb41..1fc9747a09 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -442,6 +442,70 @@ private: ble::phy_t rx_phy ); + virtual void on_enhanced_connection_complete( + pal::hci_error_code_t status, + connection_handle_t connection_handle, + pal::connection_role_t own_role, + pal::connection_peer_address_type_t peer_address_type, + const ble::address_t &peer_address, + const ble::address_t &local_resolvable_private_address, + const ble::address_t &peer_resolvable_private_address, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout, + pal::clock_accuracy_t master_clock_accuracy + ); + + virtual void on_extended_advertising_report( + advertising_event_t event_type, + const pal::connection_peer_address_type_t *address_type, + const ble::address_t &address, + phy_t primary_phy, + const phy_t *secondary_phy, + pal::advertising_sid_t advertising_sid, + pal::advertising_power_t tx_power, + pal::rssi_t rssi, + uint16_t periodic_advertising_interval, + pal::direct_address_type_t direct_address_type, + const ble::address_t &direct_address, + uint8_t data_length, + const uint8_t *data_size + ); + + virtual void on_periodic_advertising_sync_established( + pal::hci_error_code_t error, + pal::sync_handle_t sync_handle, + pal::advertising_sid_t advertising_sid, + pal::connection_peer_address_type_t advertiser_address_type, + const ble::address_t &advertiser_address, + uint16_t periodic_advertising_interval, + pal::clock_accuracy_t clock_accuracy + ); + + virtual void on_periodic_advertising_report( + pal::sync_handle_t sync_handle, + pal::advertising_power_t tx_power, + pal::rssi_t rssi, + pal::advertising_data_status_t data_status, + uint8_t data_length, + const uint8_t *data + ); + + virtual void on_periodic_advertising_sync_loss(pal::sync_handle_t sync_handle); + + virtual void on_advertising_set_terminated( + pal::hci_error_code_t status, + advertising_handle_t advertising_handle, + connection_handle_t connection_handle, + uint8_t number_of_completed_extended_advertising_events + ); + + virtual void on_scan_request_received( + advertising_handle_t advertising_handle, + pal::connection_peer_address_type_t scanner_address_type, + const ble::address_t &address + ); + private: pal::EventQueue& _event_queue; pal::Gap &_pal_gap; diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index f0cca80732..18d3b60a58 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -635,6 +635,33 @@ struct advertising_event_properties_t { } } + explicit advertising_event_properties_t(ble::advertising_type_t adv_type) : + connectable(false), + scannable(false), + directed(false), + high_duty_cycle(false), + use_legacy_pdu(true), + omit_advertisser_address(false), + include_tx_power(false) + { + switch (adv_type) { + case ADV_CONNECTABLE_UNDIRECTED: + connectable = true; + scannable = true; + break; + case ADV_CONNECTABLE_DIRECTED: + connectable = true; + directed = true; + break; + case ADV_SCANNABLE_UNDIRECTED: + scannable = true; + break; + case ADV_NON_CONNECTABLE_UNDIRECTED: + break; + } + } + + /** * If set the advertising event is connectable. */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7088ac6a7b..b2bf3f3c1d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1619,36 +1619,38 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return BLE_ERROR_NONE; } - pal::advertising_event_properties_t event_properties; + ble::advertising_type_t adv_type = params->getAdvertisingType(); AddressUseType_t use_type; - switch(params->getAdvertisingType()) { + switch(adv_type) { case ADV_SCANNABLE_UNDIRECTED: case ADV_NON_CONNECTABLE_UNDIRECTED: - case EXT_ADV_NON_CONNECTABLE_DIRECTED: - case EXT_ADV_SCANNABLE_DIRECTED: use_type = PERIPHERAL_NON_CONNECTABLE; break; default: use_type = PERIPHERAL_CONNECTABLE; } + address_t dummy_peer_address; + + pal::advertising_event_properties_t event_properties(adv_type); + return _pal_gap.set_extended_advertising_parameters( - (pal::advertising_handle_t)Gap::LEGACY_ADVERTISING_HANDLE, + Gap::LEGACY_ADVERTISING_HANDLE, event_properties, - (pal::advertising_interval_t)params->getIntervalInADVUnits(), - (pal::advertising_interval_t)params->getIntervalInADVUnits(), + (pal::advertising_interval_t) params->getIntervalInADVUnits(), + (pal::advertising_interval_t) params->getIntervalInADVUnits(), pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, - (pal::own_address_type_t)get_own_address_type(use_type), + (pal::own_address_type_t) get_own_address_type(use_type), pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, - ble::address_t(), + dummy_peer_address, (pal::advertising_filter_policy_t)_advertising_filter_policy, - 0, - ble::phy_set_t::PHY_SET_1M, - 0, - ble::phy_set_t::PHY_SET_1M, - 0xFF, - true + /* TX power : no preference */ 127, + /* primary phy */ phy_t::LE_1M, + /* max skip */ 0x00, + /* secondary phy */ phy_t::LE_1M, + /* SID */ 0x00, + false ); } @@ -1656,22 +1658,26 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend if (!get_adv_set_bit(_existing_sets, handle) || !params) { return BLE_ERROR_INVALID_PARAM; } - + pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); pal::advertising_event_properties_t event_properties;//TODO //params->getAdvertisingType() return _pal_gap.set_extended_advertising_parameters( - (pal::advertising_handle_t)handle, + handle, event_properties, (pal::advertising_interval_t)params->getMinPrimaryInterval(), (pal::advertising_interval_t)params->getMaxPrimaryInterval(), channel_map, - (pal::own_address_type_t)params->getOwnAddressType(), - (pal::advertising_peer_address_type_t)params->getPeerAddressType(), + /* FIXME: No, the enum type is no correct to represent own address type! + * params->getOwnAddressType() */ + pal::own_address_type_t::PUBLIC_ADDRESS, + /* FIXME: No, the enum type is no correct to represent that address type! + * params->getPeerAddressType() */ + pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, params->getPeerAddress(), - (pal::advertising_filter_policy_t)params->getPolicyMode(), - (pal::advertising_power_t)params->getTxPower(), + (pal::advertising_filter_policy_t::type) params->getPolicyMode(), + (pal::advertising_power_t) params->getTxPower(), params->getPrimaryPhy(), params->getSecondaryMaxSkip(), params->getSecondaryPhy(), @@ -1688,7 +1694,7 @@ ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const Adv return setAdvertisingData(handle, response, minimiseFragmentation, true); } -ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const GapAdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse) { +ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse) { if (!get_adv_set_bit(_existing_sets, handle) || !payload) { return BLE_ERROR_INVALID_PARAM; } @@ -1708,7 +1714,9 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const GapAdvertis uint16_t index = 0; const uint16_t& length = payload->getPayloadLen(); uint16_t packet_data_length = length; - pal::advertising_fragment_description_t operation; + pal::advertising_fragment_description_t operation( + pal::advertising_fragment_description_t::COMPLETE_FRAGMENT + ); operation = (length > MAX_HCI_DATA_LENGTH) ? pal::advertising_fragment_description_t::COMPLETE_FRAGMENT : operation = pal::advertising_fragment_description_t::FIRST_FRAGMENT; @@ -1806,5 +1814,90 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { return get_adv_set_bit(_active_sets, handle); } +void GenericGap::on_enhanced_connection_complete( + pal::hci_error_code_t status, + connection_handle_t connection_handle, + pal::connection_role_t own_role, + connection_peer_address_type_t peer_address_type, + const ble::address_t &peer_address, + const ble::address_t &local_resolvable_private_address, + const ble::address_t &peer_resolvable_private_address, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout, + pal::clock_accuracy_t master_clock_accuracy +) +{ + +} + +void GenericGap::on_extended_advertising_report( + advertising_event_t event_type, + const connection_peer_address_type_t *address_type, + const ble::address_t &address, + phy_t primary_phy, + const phy_t *secondary_phy, + pal::advertising_sid_t advertising_sid, + pal::advertising_power_t tx_power, + pal::rssi_t rssi, + uint16_t periodic_advertising_interval, + pal::direct_address_type_t direct_address_type, + const ble::address_t &direct_address, + uint8_t data_length, + const uint8_t *data_size +) +{ + +} + +void GenericGap::on_periodic_advertising_sync_established( + pal::hci_error_code_t error, + pal::sync_handle_t sync_handle, + pal::advertising_sid_t advertising_sid, + connection_peer_address_type_t advertiser_address_type, + const ble::address_t &advertiser_address, + uint16_t periodic_advertising_interval, + pal::clock_accuracy_t clock_accuracy +) +{ + +} + +void GenericGap::on_periodic_advertising_report( + pal::sync_handle_t sync_handle, + pal::advertising_power_t tx_power, + pal::rssi_t rssi, + pal::advertising_data_status_t data_status, + uint8_t data_length, + const uint8_t *data +) +{ + +} + +void GenericGap::on_periodic_advertising_sync_loss(pal::sync_handle_t sync_handle) +{ + +} + +void GenericGap::on_advertising_set_terminated( + pal::hci_error_code_t status, + advertising_handle_t advertising_handle, + connection_handle_t connection_handle, + uint8_t number_of_completed_extended_advertising_events +) +{ + +} + +void GenericGap::on_scan_request_received( + advertising_handle_t advertising_handle, + connection_peer_address_type_t scanner_address_type, + const ble::address_t &address +) +{ + +} + } // namespace generic } // namespace ble diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index 72ecd033cd..8df8dc7c66 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -544,7 +544,7 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { phy_t sec_phy(evt->secPhy); handler->on_extended_advertising_report( - evt->eventType, + advertising_event_t(evt->eventType), (evt->addrType == HCI_ADDR_TYPE_ANONYMOUS) ? NULL : &addr_type, evt->addr, phy_t(evt->priPhy), @@ -865,7 +865,7 @@ ble_error_t Gap::extended_scan_enable( DmScanStart( scanning_phys.value(), DM_DISC_MODE_NONE, - scan_type, + extended_scan_type, filter_duplicates.value(), // TODO: cordio API incomplete ??? duration_ms > 0xFFFF ? 0xFFFF : duration_ms, period diff --git a/platform/mbed_toolchain.h b/platform/mbed_toolchain.h index fba7d32bed..8203570ddb 100644 --- a/platform/mbed_toolchain.h +++ b/platform/mbed_toolchain.h @@ -277,7 +277,7 @@ #if defined(__CC_ARM) #define MBED_DEPRECATED(M) __attribute__((deprecated)) #elif defined(__GNUC__) || defined(__clang__) -#define MBED_DEPRECATED(M) __attribute__((deprecated(M))) +#define MBED_DEPRECATED(M) #else #define MBED_DEPRECATED(M) #endif From 75c0b0ed9038ccde21708d00cfc57d37738187e8 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 17:56:48 +0000 Subject: [PATCH 042/361] BLE: Fix advertising_channel_map_t constructor. --- features/FEATURE_BLE/ble/pal/GapTypes.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 18d3b60a58..74e2a18329 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -212,8 +212,9 @@ struct advertising_channel_map_t : SafeEnum advertising_channel_map_t(type value) : SafeEnum(value) { } - advertising_channel_map_t(bool ch37, bool ch38, bool ch39) { - SafeEnum(ch37 | (ch38 << 1) | (ch39 << 2)) { } + advertising_channel_map_t(bool ch37, bool ch38, bool ch39) : + SafeEnum(ch37 | (ch38 << 1) | (ch39 << 2)) + { } }; From 732b4255ce44c933bfbf63d1a4badd5f8e7ea005 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 8 Nov 2018 18:03:01 +0000 Subject: [PATCH 043/361] revert toolchain changes --- platform/mbed_toolchain.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/mbed_toolchain.h b/platform/mbed_toolchain.h index 8203570ddb..fba7d32bed 100644 --- a/platform/mbed_toolchain.h +++ b/platform/mbed_toolchain.h @@ -277,7 +277,7 @@ #if defined(__CC_ARM) #define MBED_DEPRECATED(M) __attribute__((deprecated)) #elif defined(__GNUC__) || defined(__clang__) -#define MBED_DEPRECATED(M) +#define MBED_DEPRECATED(M) __attribute__((deprecated(M))) #else #define MBED_DEPRECATED(M) #endif From c58099f0eeee12e4d13d3cd95ac5c3b14ac496f4 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 8 Nov 2018 18:10:41 +0000 Subject: [PATCH 044/361] new scan call --- features/FEATURE_BLE/ble/BLETypes.h | 11 +++++++++++ features/FEATURE_BLE/ble/Gap.h | 12 ++++++++++-- features/FEATURE_BLE/ble/GapScanningParams.h | 5 ----- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index f93331f23a..21e4602b08 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -368,6 +368,17 @@ enum scanning_policy_mode_t { SCAN_POLICY_FILTER_ALL_ADV = 1, }; +/** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ +enum scanning_filter_duplicates_t { + SCAN_FILTER_DUPLICATES_DISABLED = 0, + SCAN_FILTER_DUPLICATES_ENABLED = 1, + SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 +}; + /** * Type that describes link's encryption state. */ diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 3b486839aa..b677bbc64d 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1283,11 +1283,19 @@ public: /* scanning */ - ble_error_t startScan(const GapScanningParams params) { + ble_error_t setScanParameters( + const GapScanningParams* params = NULL, + const GapScanningParams* params = NULL, + const GapScanningParams* params = NULL + ) { return startRadioScan(params); }; - ble_error_t startScan() { + ble_error_t startScan( + ble::scanning_filter_duplicates_t filtering = SCAN_FILTER_DUPLICATES_DISABLED, + uint32_t duration = 0, + uint32_t period = 0 + ) { return startRadioScan(_scanningParams); }; diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 70e7247cde..b929c6a27e 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -246,11 +246,6 @@ private: * Obtain the peer device's advertising data and (if possible) scanResponse. */ bool _activeScanning; - - /** Primary channel PHY. */ - ble::phy_t _phy; - - ble::scanning_policy_mode_t _mode; }; /** From 5d077e6dbc947de04586d34de19ed263df6bbd1e Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 09:24:54 +0000 Subject: [PATCH 045/361] new addr types for ext adv --- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 41 ++++++++++++++----- .../FEATURE_BLE/source/generic/GenericGap.cpp | 6 +-- 2 files changed, 33 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index cb95fcbb7b..e8b28698f4 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -20,6 +20,7 @@ #include "BLETypes.h" #include "BLEProtocol.h" #include "blecommon.h" +#include "SafeEnum.h" /** * @addtogroup ble @@ -258,6 +259,25 @@ private: }; class GapExtendedAdvertisingParams { +public: + struct own_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address. */ + RANDOM, /**< Random Device Address. */ + RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use the public address. */ + RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use previously set random address. */ + }; + }; + struct peer_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ + RANDOM /**< Random Device Address or Random (static) Identity Address. */ + }; + }; public: GapExtendedAdvertisingParams() : @@ -276,16 +296,16 @@ public: _channel38(1), _channel39(1), _anonymous(0), - _notifyOnScan(1) { - - } + _notifyOnScan(1) { } /** * Update the advertising type. * * @param[in] newAdvType The new advertising type. */ - void setType(ble::advertising_type_t newAdvType) { + void setType( + ble::advertising_type_t newAdvType + ) { _advType = newAdvType; } @@ -352,19 +372,20 @@ public: _channel39 = channel39; } - BLEProtocol::AddressType::Type getOwnAddressType() const { + //TODO new type in params + own_address_type_t getOwnAddressType() const { return _ownAddressType; } void setOwnAddressType( - BLEProtocol::AddressType::Type addressType + own_address_type_t addressType ) { _ownAddressType = addressType; } ble_error_t getPeer( BLEProtocol::AddressBytes_t *address, - ble::peer_address_type_t *addressType + peer_address_type_t *addressType ) const { if (!address || !addressType) { return BLE_ERROR_INVALID_PARAM; @@ -376,7 +397,7 @@ public: void setPeer( const BLEProtocol::AddressBytes_t address, - ble::peer_address_type_t addressType + peer_address_type_t addressType ) { memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); _peerAddressType = addressType; @@ -456,7 +477,7 @@ public: return _peerAddress; }; - ble::peer_address_type_t getPeerAddressType() const { + peer_address_type_t getPeerAddressType() const { return _peerAddressType; }; @@ -484,7 +505,7 @@ private: ble::advertising_event_t _advType; uint32_t _minInterval; uint32_t _maxInterval; - ble::peer_address_type_t _peerAddressType; + peer_address_type_t _peerAddressType; BLEProtocol::AddressType_t _ownAddressType; ble::advertising_policy_mode_t _policy; ble::phy_t _primaryPhy; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b2bf3f3c1d..74a2ab5dd6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1669,11 +1669,9 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend (pal::advertising_interval_t)params->getMinPrimaryInterval(), (pal::advertising_interval_t)params->getMaxPrimaryInterval(), channel_map, - /* FIXME: No, the enum type is no correct to represent own address type! - * params->getOwnAddressType() */ + params->getOwnAddressType(), pal::own_address_type_t::PUBLIC_ADDRESS, - /* FIXME: No, the enum type is no correct to represent that address type! - * params->getPeerAddressType() */ + params->getPeerAddressType(), pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, params->getPeerAddress(), (pal::advertising_filter_policy_t::type) params->getPolicyMode(), From 60fb78795b700d01514c63c2b9e1c7da40a50806 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 10:48:18 +0000 Subject: [PATCH 046/361] fix adv and scan types --- features/FEATURE_BLE/ble/BLETypes.h | 12 +++++- features/FEATURE_BLE/ble/Gap.h | 9 ++-- features/FEATURE_BLE/ble/GapAdvertisingData.h | 2 +- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 42 +++++++++++++++---- features/FEATURE_BLE/ble/GapScanningParams.h | 20 --------- features/FEATURE_BLE/ble/pal/GapTypes.h | 1 + .../FEATURE_BLE/source/GapScanningParams.cpp | 4 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 11 ++--- 8 files changed, 55 insertions(+), 46 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 21e4602b08..9e294f7576 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -143,7 +143,7 @@ enum advertising_type_t { /** * Device is connectable and expects connection from a specific peer. - * + * (3.75 ms or smaller Advertising Interval) * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. */ ADV_CONNECTABLE_DIRECTED, @@ -160,7 +160,12 @@ enum advertising_type_t { * * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. */ - ADV_NON_CONNECTABLE_UNDIRECTED + ADV_NON_CONNECTABLE_UNDIRECTED, + + /** + * Device is connectable and expects connection from a specific peer (sent at long user set intervals). + */ + ADV_CONNECTABLE_DIRECTED_LOW_DUTY }; struct advertising_data_status_t : SafeEnum{ @@ -204,6 +209,9 @@ struct advertising_event_t { case ADV_NON_CONNECTABLE_UNDIRECTED: value = 0x20; break; + case ADV_CONNECTABLE_DIRECTED_LOW_DUTY: + value = 0x2D; + break; } } diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index b677bbc64d..c953f0a5fd 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1284,15 +1284,14 @@ public: /* scanning */ ble_error_t setScanParameters( - const GapScanningParams* params = NULL, - const GapScanningParams* params = NULL, - const GapScanningParams* params = NULL + const GapScanningParams* params ) { - return startRadioScan(params); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; }; ble_error_t startScan( - ble::scanning_filter_duplicates_t filtering = SCAN_FILTER_DUPLICATES_DISABLED, + ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, uint32_t duration = 0, uint32_t period = 0 ) { diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 52aa7e991d..aaaac71909 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -722,7 +722,7 @@ public: uint16_t appearance = GENERIC_TAG; const uint8_t *field = findField(AdvertisingData::APPEARANCE); if (field) { - memcpy((uint8_t*)appearance, field, 2); + memcpy((uint8_t*)&appearance, field, 2); } return appearance; } diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index e8b28698f4..f1499b5402 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -271,21 +271,24 @@ public: the local IRK from the resolving list. If the resolving list contains no matching entry, use previously set random address. */ }; + own_address_type_t(type value) : ble::SafeEnum(value) { } }; + struct peer_address_type_t : ble::SafeEnum { enum type { PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ RANDOM /**< Random Device Address or Random (static) Identity Address. */ }; + peer_address_type_t(type value) : ble::SafeEnum(value) { } }; public: GapExtendedAdvertisingParams() : - _advType(ble::advertising_event_t().connectable(true).scannable_advertising(true)), + _advType(ble::ADV_CONNECTABLE_UNDIRECTED), _minInterval(0), _maxInterval(0), - _peerAddressType(), - _ownAddressType(), + _peerAddressType(peer_address_type_t::PUBLIC), + _ownAddressType(own_address_type_t::PUBLIC), _policy(ble::ADV_POLICY_IGNORE_WHITELIST), _primaryPhy(ble::phy_t::LE_1M), _secondaryPhy(ble::phy_t::LE_1M), @@ -296,7 +299,9 @@ public: _channel38(1), _channel39(1), _anonymous(0), - _notifyOnScan(1) { } + _notifyOnScan(1), + _legacyPDU(0), + _includeHeaderTxPower(0) { } /** * Update the advertising type. @@ -314,7 +319,7 @@ public: * * @return Advertising type. */ - ble::advertising_event_t getType() const { + ble::advertising_type_t getType() const { return _advType; } @@ -372,7 +377,6 @@ public: _channel39 = channel39; } - //TODO new type in params own_address_type_t getOwnAddressType() const { return _ownAddressType; } @@ -463,6 +467,26 @@ public: return _notifyOnScan; } + void setUseLegacyPDU( + bool enable = true + ) { + _legacyPDU = enable; + } + + bool getUseLegacyPDU() const { + return _legacyPDU; + } + + void includeTxPowerInHeader( + bool enable = true + ) { + _includeHeaderTxPower = enable; + } + + bool getTxPowerInHeader() const { + return _includeHeaderTxPower; + } + /* helper get functions */ uint32_t getMinPrimaryInterval() const { @@ -502,11 +526,11 @@ public: } private: - ble::advertising_event_t _advType; + ble::advertising_type_t _advType; uint32_t _minInterval; uint32_t _maxInterval; peer_address_type_t _peerAddressType; - BLEProtocol::AddressType_t _ownAddressType; + own_address_type_t _ownAddressType; ble::advertising_policy_mode_t _policy; ble::phy_t _primaryPhy; ble::phy_t _secondaryPhy; @@ -518,6 +542,8 @@ private: uint8_t _channel39:1; uint8_t _anonymous:1; uint8_t _notifyOnScan:1; + uint8_t _legacyPDU:1; + uint8_t _includeHeaderTxPower:1; }; /** diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index b929c6a27e..1aeef8a0f2 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -206,26 +206,6 @@ public: return _activeScanning; } - /** - * - * @param phy LE_2m is illegal - */ - void setScanningPhy(ble::phy_t phy) { - _phy = phy; - } - - ble::phy_t getScanningPhy() { - return _phy; - } - - ble::scanning_policy_mode_t getScanningPolicy() { - return _mode; - } - - void setScanningPolicy(ble::scanning_policy_mode_t mode) { - _mode = mode; - } - private: /** * Scan interval in units of 625us (between 2.5ms and 10.24s). diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 74e2a18329..42593141a9 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -651,6 +651,7 @@ struct advertising_event_properties_t { scannable = true; break; case ADV_CONNECTABLE_DIRECTED: + case ADV_CONNECTABLE_DIRECTED_LOW_DUTY: connectable = true; directed = true; break; diff --git a/features/FEATURE_BLE/source/GapScanningParams.cpp b/features/FEATURE_BLE/source/GapScanningParams.cpp index d0ca1acc58..1d9f1cb26f 100644 --- a/features/FEATURE_BLE/source/GapScanningParams.cpp +++ b/features/FEATURE_BLE/source/GapScanningParams.cpp @@ -21,9 +21,7 @@ GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_ _interval(MSEC_TO_SCAN_DURATION_UNITS(interval)), _window(MSEC_TO_SCAN_DURATION_UNITS(window)), _timeout(timeout), - _activeScanning(activeScanning), - _phy(ble::phy_t::LE_1M), - _mode(ble::SCAN_POLICY_IGNORE_WHITELIST) { + _activeScanning(activeScanning) { /* stay within limits */ if (_interval < SCAN_INTERVAL_MIN) { _interval = SCAN_INTERVAL_MIN; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 74a2ab5dd6..7215c3f55f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1633,7 +1633,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert address_t dummy_peer_address; - pal::advertising_event_properties_t event_properties(adv_type); + pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)adv_type); return _pal_gap.set_extended_advertising_parameters( Gap::LEGACY_ADVERTISING_HANDLE, @@ -1660,8 +1660,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend } pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); - pal::advertising_event_properties_t event_properties;//TODO - //params->getAdvertisingType() + pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params->getType()); return _pal_gap.set_extended_advertising_parameters( handle, @@ -1669,10 +1668,8 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtend (pal::advertising_interval_t)params->getMinPrimaryInterval(), (pal::advertising_interval_t)params->getMaxPrimaryInterval(), channel_map, - params->getOwnAddressType(), - pal::own_address_type_t::PUBLIC_ADDRESS, - params->getPeerAddressType(), - pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, + (pal::own_address_type_t::type)params->getOwnAddressType().value(), + (pal::advertising_peer_address_type_t::type)params->getPeerAddressType().value(), params->getPeerAddress(), (pal::advertising_filter_policy_t::type) params->getPolicyMode(), (pal::advertising_power_t) params->getTxPower(), From 8c253a3dfe92fcedb67d9c5f12d8a2c950600d44 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 11:19:05 +0000 Subject: [PATCH 047/361] proposed scan type changes --- features/FEATURE_BLE/ble/GapScanningParams.h | 48 +++++++++++++++++-- .../FEATURE_BLE/source/GapScanningParams.cpp | 39 +++++++++++++-- 2 files changed, 79 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 1aeef8a0f2..16dc7bb72c 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -108,10 +108,16 @@ public: * @note If interval is equal to window */ GapScanningParams( - uint16_t interval = SCAN_INTERVAL_MAX, - uint16_t window = SCAN_WINDOW_MAX, + uint16_t interval = 0, + uint16_t window = 0, uint16_t timeout = 0, - bool activeScanning = false + bool activeScanning = false, + ble::scanning_policy_mode_t policy = ble::SCAN_POLICY_IGNORE_WHITELIST, + uint16_t codedInterval = 0, + uint16_t codedWindow = 0, + uint16_t codedTimeout = 0, + bool codedActiveScanning = false, + ble::scanning_policy_mode_t codedPolicy = ble::SCAN_POLICY_IGNORE_WHITELIST ); /** @@ -203,7 +209,15 @@ public: */ bool getActiveScanning(void) const { - return _activeScanning; + return _active_scanning; + } + + ble::scanning_policy_mode_t getScanningPolicy() { + return _policy; + } + + void setScanningPolicy(ble::scanning_policy_mode_t policy) { + _policy = policy; } private: @@ -222,10 +236,34 @@ private: */ uint16_t _timeout; + /** + * Scan interval in units of 625us (between 2.5ms and 10.24s). + */ + uint16_t _interval_coded; + + /** + * Scan window in units of 625us (between 2.5ms and 10.24s). + */ + uint16_t _window_coded; + + /** + * Scan timeout between 0x0001 and 0xFFFF in seconds; 0x0000 disables timeout. + */ + uint16_t _timeout_coded; + + ble::scanning_policy_mode_t _policy; + ble::scanning_policy_mode_t _policy_coded; + + /** * Obtain the peer device's advertising data and (if possible) scanResponse. */ - bool _activeScanning; + uint8_t _active_scanning:1; + uint8_t _active_scanning_coded:1; + + uint8_t _phy_1m:1; + uint8_t _phy_coded:1; + }; /** diff --git a/features/FEATURE_BLE/source/GapScanningParams.cpp b/features/FEATURE_BLE/source/GapScanningParams.cpp index 1d9f1cb26f..02eeda6fd7 100644 --- a/features/FEATURE_BLE/source/GapScanningParams.cpp +++ b/features/FEATURE_BLE/source/GapScanningParams.cpp @@ -17,11 +17,31 @@ #include "ble/Gap.h" #include "ble/GapScanningParams.h" -GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_t timeout, bool activeScanning) : +GapScanningParams::GapScanningParams( + uint16_t interval, + uint16_t window, + uint16_t timeout, + bool activeScanning, + ble::scanning_policy_mode_t policy, + uint16_t codedInterval, + uint16_t codedWindow, + uint16_t codedTimeout, + bool codedActiveScanning, + ble::scanning_policy_mode_t codedPolicy + ) : _interval(MSEC_TO_SCAN_DURATION_UNITS(interval)), _window(MSEC_TO_SCAN_DURATION_UNITS(window)), _timeout(timeout), - _activeScanning(activeScanning) { + _active_scanning(activeScanning), + _policy(policy), + _interval_coded(MSEC_TO_SCAN_DURATION_UNITS(codedWindow)), + _window_coded(MSEC_TO_SCAN_DURATION_UNITS(codedWindow)), + _timeout_coded(codedTimeout), + _active_scanning_coded(codedActiveScanning), + _policy_coded(codedPolicy), + _phy_1m(window != 0), + _phy_coded(codedWindow != 0) { + //TODO: refactor /* stay within limits */ if (_interval < SCAN_INTERVAL_MIN) { _interval = SCAN_INTERVAL_MIN; @@ -35,6 +55,19 @@ GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_ if (_window > SCAN_WINDOW_MAX) { _window = SCAN_WINDOW_MAX; } + + if (_interval_coded < SCAN_INTERVAL_MIN) { + _interval_coded = SCAN_INTERVAL_MIN; + } + if (_interval_coded > SCAN_INTERVAL_MAX) { + _interval_coded = SCAN_INTERVAL_MAX; + } + if (_window_coded < SCAN_WINDOW_MIN) { + _window_coded = SCAN_WINDOW_MIN; + } + if (_window_coded > SCAN_WINDOW_MAX) { + _window_coded = SCAN_WINDOW_MAX; + } } ble_error_t @@ -71,5 +104,5 @@ GapScanningParams::setTimeout(uint16_t newTimeout) void GapScanningParams::setActiveScanning(bool activeScanning) { - _activeScanning = activeScanning; + _active_scanning = activeScanning; } From ca72f5a28987749b34f8503dfd502f64fd5a18cc Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 13:43:20 +0000 Subject: [PATCH 048/361] merged adv param types --- features/FEATURE_BLE/ble/Gap.h | 14 +- features/FEATURE_BLE/ble/GapAdvertisingData.h | 29 ++- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 227 +++++++++++------- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 - .../FEATURE_BLE/source/generic/GenericGap.cpp | 65 ++--- 5 files changed, 187 insertions(+), 150 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index c953f0a5fd..b4fc4cb6f4 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1169,13 +1169,6 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { - (void) handle; - (void) params; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false) { (void) handle; (void) payload; @@ -1203,6 +1196,7 @@ public: } ble_error_t status = setAdvertisingData(getLegacyAdvertisingPayload(), getLegacyAdvertisingScanResponse()); + if (status != BLE_ERROR_NONE) { return status; } @@ -2461,6 +2455,8 @@ protected: _advParams = new GapAdvertisingParams(); } MBED_ASSERT(_advParams); + /* this setting is now read from the params */ + _advParams->setPolicyMode(getAdvertisingPolicyMode()); return *_advParams; } @@ -2909,7 +2905,7 @@ public: MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "This setting is now part of advertising paramters." ) virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) { @@ -2928,7 +2924,7 @@ public: MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "This setting is now part of advertising paramters." ) virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const { diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index aaaac71909..562a072946 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -534,16 +534,31 @@ public: */ typedef enum Appearance_t Appearance; + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Buffer used to store the data. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ AdvertisingData(mbed::Span buffer) : _buffer(buffer), _payloadLen(0) { } + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Pointer to buffer to be used for storing advertising data. + * @param buffer_size Size of the buffer. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ AdvertisingData(uint8_t* buffer, size_t buffer_size) : _buffer(buffer, buffer_size), _payloadLen(0) { } + /** Return maximum size of the data that can be stored. + * + * @return Size of the buffer used to store the data. + */ size_t getBufferSize() const { return _buffer.size(); } @@ -936,16 +951,16 @@ protected: } protected: + /** The memory backing the the data provided by the user. */ mbed::Span _buffer; - /** - * Length of the data added to the advertising buffer. - */ + /** Length of the data added to the advertising buffer. */ uint8_t _payloadLen; }; -/** - * @deprecated Use AdvertisingData; +/** @deprecated Use AdvertisingData instead. + * This version provides the buffer backing for the advertising data + * but it's only big enough for legacy advertising. */ class GapAdvertisingData : public AdvertisingData { @@ -961,9 +976,7 @@ public: } private: - /** - * Advertising data buffer. - */ + /** Advertising data buffer. */ uint8_t _payload[GAP_ADVERTISING_DATA_MAX_PAYLOAD]; }; diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index f1499b5402..c96d7646b5 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -22,6 +22,14 @@ #include "blecommon.h" #include "SafeEnum.h" +/* TODO: std::clamp */ +#define CLAMP(value, min, max) \ + if (value > max) { \ + value = max; \ + } else if (value < min) { \ + value = min; \ + } + /** * @addtogroup ble * @{ @@ -87,6 +95,28 @@ public: static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; + struct own_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address. */ + RANDOM, /**< Random Device Address. */ + RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use the public address. */ + RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use previously set random address. */ + }; + own_address_type_t(type value) : ble::SafeEnum(value) { } + }; + + struct peer_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ + RANDOM /**< Random Device Address or Random (static) Identity Address. */ + }; + peer_address_type_t(type value) : ble::SafeEnum(value) { } + }; + public: /** * Construct an instance of GapAdvertisingParams. @@ -106,28 +136,36 @@ public: ) : _advType(advType), _interval(interval), - _timeout(timeout) + _maxInterval(0), + _timeout(timeout), + _peerAddressType(peer_address_type_t::PUBLIC), + _ownAddressType(own_address_type_t::PUBLIC), + _policy(ble::ADV_POLICY_IGNORE_WHITELIST), + _primaryPhy(ble::phy_t::LE_1M), + _secondaryPhy(ble::phy_t::LE_1M), + _peerAddress(), + _txPower(127), + _eventNumber(0), + _channel37(1), + _channel38(1), + _channel39(1), + _anonymous(0), + _notifyOnScan(0), + _legacyPDU(1), + _includeHeaderTxPower(0) { /* Interval checks. */ if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { /* Interval must be 0 in directed connectable mode. */ _interval = 0; + _maxInterval = 0; } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { /* Min interval is slightly larger than in other modes. */ - if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) { - _interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; - } - if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) { - _interval = GAP_ADV_PARAMS_INTERVAL_MAX; - } + CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); } else { - /* Stay within interval limits. */ - if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN) { - _interval = GAP_ADV_PARAMS_INTERVAL_MIN; - } - if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) { - _interval = GAP_ADV_PARAMS_INTERVAL_MAX; - } + CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); } /* Timeout checks. */ @@ -139,6 +177,7 @@ public: } } +public: /** * Number of microseconds in 0.625 milliseconds. */ @@ -241,68 +280,6 @@ public: _timeout = newTimeout; } -private: - /** - * The advertising type. - */ - ble::advertising_type_t _advType; - - /** - * The advertising interval in ADV duration units (in other words, 0.625ms). - */ - uint16_t _interval; - - /** - * The advertising timeout in seconds. - */ - uint16_t _timeout; -}; - -class GapExtendedAdvertisingParams { -public: - struct own_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address. */ - RANDOM, /**< Random Device Address. */ - RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use the public address. */ - RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use previously set random address. */ - }; - own_address_type_t(type value) : ble::SafeEnum(value) { } - }; - - struct peer_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ - RANDOM /**< Random Device Address or Random (static) Identity Address. */ - }; - peer_address_type_t(type value) : ble::SafeEnum(value) { } - }; - -public: - GapExtendedAdvertisingParams() : - _advType(ble::ADV_CONNECTABLE_UNDIRECTED), - _minInterval(0), - _maxInterval(0), - _peerAddressType(peer_address_type_t::PUBLIC), - _ownAddressType(own_address_type_t::PUBLIC), - _policy(ble::ADV_POLICY_IGNORE_WHITELIST), - _primaryPhy(ble::phy_t::LE_1M), - _secondaryPhy(ble::phy_t::LE_1M), - _peerAddress(), - _txPower(0), - _eventNumber(0), - _channel37(1), - _channel38(1), - _channel39(1), - _anonymous(0), - _notifyOnScan(1), - _legacyPDU(0), - _includeHeaderTxPower(0) { } - /** * Update the advertising type. * @@ -323,16 +300,30 @@ public: return _advType; } + /** + * + * @return + */ bool getAnonymousAdvertising() const { return _anonymous; } + /** Advertise without your own address. + * + * @param enable Advertising anonymous if true. + */ void setAnonymousAdvertising( bool enable ) { _anonymous = enable; } + /** Get the advertising intervals on the primary channels. + * + * @param min Minimum interval in milliseconds. + * @param max Maximum interval in milliseconds. + * @return Error if pointers are invalid. + */ ble_error_t getPrimaryInterval( uint32_t *min /* ms */, uint32_t *max /* ms */ @@ -340,19 +331,31 @@ public: if (!min || !max) { return BLE_ERROR_INVALID_PARAM; } - *min = _minInterval; - *max = _maxInterval; + *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + *max = ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); return BLE_ERROR_NONE; } + /** Set the advertising intervals on the primary channels. + * + * @param min Minimum interval in milliseconds. + * @param max Maximum interval in milliseconds. + */ void setPrimaryInterval( uint32_t min /* ms */, uint32_t max /* ms */ ) { - _minInterval = min; - _maxInterval = max; + _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); + _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(max); } + /** Get channels set for primary advertising. + * + * @param channel37 Use channel 37. + * @param channel38 Use channel 38. + * @param channel39 Use channel 39. + * @return Error if pointers are invalid. + */ ble_error_t getPrimaryChannels( bool *channel37, bool *channel38, @@ -367,26 +370,48 @@ public: return BLE_ERROR_NONE; } + /** Set which channels are to be used for primary advertising. + * At least must be used. If all are set to disabled all channels will be used. + * + * @param channel37 Use channel 37. + * @param channel38 Use channel 38. + * @param channel39 Use channel 39. + */ void setPrimaryChannels( bool channel37, bool channel38, bool channel39 ) { + if (!channel37 && !channel38 && !channel39) { + channel37 = channel38 = channel39 = true; + } _channel37 = channel37; _channel38 = channel38; _channel39 = channel39; } + /** Get what type of address is to be used as your own address during advertising. + * + * @return Addres tpe used. + */ own_address_type_t getOwnAddressType() const { return _ownAddressType; } + /** Get what type of address is to be used as your own address during advertising. + */ void setOwnAddressType( own_address_type_t addressType ) { _ownAddressType = addressType; } + /** Get peer address and type used during directed advertising. + * + * @param address Address that will have the peer address written to. + * @param addressType Pointer to type which will have the address type written to. + * @return Error if pointers are invalid. + */ ble_error_t getPeer( BLEProtocol::AddressBytes_t *address, peer_address_type_t *addressType @@ -399,6 +424,11 @@ public: return BLE_ERROR_NONE; }; + /** Set peer address and type used during directed advertising. + * + * @param address Peer's address bytes. + * @param addressType Peer's address type. + */ void setPeer( const BLEProtocol::AddressBytes_t address, peer_address_type_t addressType @@ -407,26 +437,46 @@ public: _peerAddressType = addressType; }; + /** Get the policy of whitelist use during advertising; + * + * @return Policy used. + */ ble::advertising_policy_mode_t getPolicyMode() const { return _policy; } - + /** Set the policy of whitelist use during advertising; + * + * @param Policy to use. + */ void setPolicyMode( ble::advertising_policy_mode_t mode ) { _policy = mode; } + /** Get the advertising TX power. + * + * @return Advertising TX power. + */ int8_t getTxPower() const { return _txPower; } + /** Set the advertising TX power. + * + * @param txPower Advertising TX power. + */ void setTxPower( int8_t txPower ) { _txPower = txPower; } + /** Get PHYs used on primary and secondary advertising channels. + * + * @param primaryPhy,secondaryPhy Pointer where the result is written to. + * @return Error if pointers are invalid. + */ ble_error_t getPhy( ble::phy_t *primaryPhy, ble::phy_t *secondaryPhy @@ -439,6 +489,11 @@ public: return BLE_ERROR_NONE; } + /** Get PHYs used on primary and secondary advertising channels. + * + * @param primaryPhy Primary advertising channles PHY. + * @param secondaryPhy Secondary advertising channles PHY. + */ void setPhy( ble::phy_t primaryPhy, ble::phy_t secondaryPhy @@ -490,7 +545,7 @@ public: /* helper get functions */ uint32_t getMinPrimaryInterval() const { - return _minInterval; + return _interval; } uint32_t getMaxPrimaryInterval() const { @@ -527,8 +582,12 @@ public: private: ble::advertising_type_t _advType; - uint32_t _minInterval; - uint32_t _maxInterval; + /** + * The advertising interval in ADV duration units (in other words, 0.625ms). + */ + uint16_t _interval; + uint16_t _timeout; + uint16_t _maxInterval; peer_address_type_t _peerAddressType; own_address_type_t _ownAddressType; ble::advertising_policy_mode_t _policy; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 1fc9747a09..d9e41192b9 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -86,8 +86,6 @@ public: ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params); - ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params); - ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false); ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response, bool minimiseFragmentation = false); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7215c3f55f..0d464efd8a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1610,65 +1610,36 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { } ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { - if (handle != Gap::LEGACY_ADVERTISING_HANDLE || !params) { - return BLE_ERROR_INVALID_PARAM; - } - - if (!is_extended_advertising_enabled()) { - memcpy(&getLegacyAdvertisingParams(), params, sizeof(GapAdvertisingParams)); - return BLE_ERROR_NONE; - } - - ble::advertising_type_t adv_type = params->getAdvertisingType(); - - AddressUseType_t use_type; - switch(adv_type) { - case ADV_SCANNABLE_UNDIRECTED: - case ADV_NON_CONNECTABLE_UNDIRECTED: - use_type = PERIPHERAL_NON_CONNECTABLE; - break; - default: - use_type = PERIPHERAL_CONNECTABLE; - } - - address_t dummy_peer_address; - - pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)adv_type); - - return _pal_gap.set_extended_advertising_parameters( - Gap::LEGACY_ADVERTISING_HANDLE, - event_properties, - (pal::advertising_interval_t) params->getIntervalInADVUnits(), - (pal::advertising_interval_t) params->getIntervalInADVUnits(), - pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, - (pal::own_address_type_t) get_own_address_type(use_type), - pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, - dummy_peer_address, - (pal::advertising_filter_policy_t)_advertising_filter_policy, - /* TX power : no preference */ 127, - /* primary phy */ phy_t::LE_1M, - /* max skip */ 0x00, - /* secondary phy */ phy_t::LE_1M, - /* SID */ 0x00, - false - ); -} - -ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapExtendedAdvertisingParams* params) { if (!get_adv_set_bit(_existing_sets, handle) || !params) { return BLE_ERROR_INVALID_PARAM; } - pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params->getType()); + event_properties.include_tx_power = params->getTxPowerInHeader(); + event_properties.omit_advertisser_address = params->getAnonymousAdvertising(); + event_properties.use_legacy_pdu = params->getUseLegacyPDU(); + + pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); + pal::own_address_type_t own_address_type = (pal::own_address_type_t::type)params->getOwnAddressType().value(); + + if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { + AddressUseType_t use_type = PERIPHERAL_CONNECTABLE; + if ((params->getAdvertisingType() == ADV_SCANNABLE_UNDIRECTED) || + (params->getAdvertisingType() == ADV_NON_CONNECTABLE_UNDIRECTED)) { + use_type = PERIPHERAL_NON_CONNECTABLE; + } + + own_address_type = (pal::own_address_type_t) get_own_address_type(use_type); + } + return _pal_gap.set_extended_advertising_parameters( handle, event_properties, (pal::advertising_interval_t)params->getMinPrimaryInterval(), (pal::advertising_interval_t)params->getMaxPrimaryInterval(), channel_map, - (pal::own_address_type_t::type)params->getOwnAddressType().value(), + own_address_type, (pal::advertising_peer_address_type_t::type)params->getPeerAddressType().value(), params->getPeerAddress(), (pal::advertising_filter_policy_t::type) params->getPolicyMode(), From 238f15b03124dd6b322d8bfbb8b81c3b6f8b079e Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 14:04:14 +0000 Subject: [PATCH 049/361] doc fixes --- features/FEATURE_BLE/ble/BLETypes.h | 2 +- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 63 ++++++++++++++----- features/FEATURE_BLE/ble/pal/GapTypes.h | 22 +++---- .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 +- 4 files changed, 61 insertions(+), 30 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 9e294f7576..a13cef2464 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -826,7 +826,7 @@ struct peer_address_type_t :SafeEnum { RANDOM_STATIC_IDENTITY, /** - * No address provided (anonymous advertisement) + * No address provided (anonymous advertisement). */ ANONYMOUS = 0xFF }; diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index c96d7646b5..7dc6257f40 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -40,8 +40,8 @@ /** * Parameters defining the advertising process. * - * Advertising parameters are a triplet of three value: - * - The Advertising mode modeled after ble::advertising_type_t. It defines + * Advertising parameters for legacy advertising are a triplet of three value: + * - The Advertising mode modelled after ble::advertising_type_t. It defines * if the device is connectable and scannable. This value can be set at * construction time, updated with setAdvertisingType() and queried by * getAdvertisingType(). @@ -136,7 +136,7 @@ public: ) : _advType(advType), _interval(interval), - _maxInterval(0), + _maxInterval(interval), _timeout(timeout), _peerAddressType(peer_address_type_t::PUBLIC), _ownAddressType(own_address_type_t::PUBLIC), @@ -145,7 +145,7 @@ public: _secondaryPhy(ble::phy_t::LE_1M), _peerAddress(), _txPower(127), - _eventNumber(0), + _maxSkip(0), _channel37(1), _channel38(1), _channel39(1), @@ -266,6 +266,7 @@ public: void setInterval(uint16_t newInterval) { _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newInterval); + _maxInterval = _interval; } /** @@ -300,9 +301,9 @@ public: return _advType; } - /** + /** Check if advertising is anonymous. * - * @return + * @return True if advertising is anonymous. */ bool getAnonymousAdvertising() const { return _anonymous; @@ -322,6 +323,7 @@ public: * * @param min Minimum interval in milliseconds. * @param max Maximum interval in milliseconds. + * * @return Error if pointers are invalid. */ ble_error_t getPrimaryInterval( @@ -354,6 +356,7 @@ public: * @param channel37 Use channel 37. * @param channel38 Use channel 38. * @param channel39 Use channel 39. + * * @return Error if pointers are invalid. */ ble_error_t getPrimaryChannels( @@ -410,6 +413,7 @@ public: * * @param address Address that will have the peer address written to. * @param addressType Pointer to type which will have the address type written to. + * * @return Error if pointers are invalid. */ ble_error_t getPeer( @@ -475,6 +479,7 @@ public: /** Get PHYs used on primary and secondary advertising channels. * * @param primaryPhy,secondaryPhy Pointer where the result is written to. + * * @return Error if pointers are invalid. */ ble_error_t getPhy( @@ -491,8 +496,8 @@ public: /** Get PHYs used on primary and secondary advertising channels. * - * @param primaryPhy Primary advertising channles PHY. - * @param secondaryPhy Secondary advertising channles PHY. + * @param primaryPhy Primary advertising channels PHY. + * @param secondaryPhy Secondary advertising channels PHY. */ void setPhy( ble::phy_t primaryPhy, @@ -503,13 +508,13 @@ public: } uint8_t getSecondaryMaxSkip() const { - return _eventNumber; + return _maxSkip; } void setSecondaryMaxSkip( uint8_t eventNumber ) { - _eventNumber = eventNumber; + _maxSkip = eventNumber; } void setScanRequestNotification( @@ -544,14 +549,40 @@ public: /* helper get functions */ - uint32_t getMinPrimaryInterval() const { + /** Get the minimum advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint16_t getMinPrimaryIntervalInADVUnits() const { return _interval; } - uint32_t getMaxPrimaryInterval() const { + /** Get the maximum advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint16_t getMaxPrimaryIntervalInADVUnits() const { return _maxInterval; } + /** Get the minimum advertisement interval in milliseconds. + * + * @return The advertisement interval in milliseconds. + */ + uint32_t getMinPrimaryInterval() const { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + } + + /** Get the maximum advertisement interval in milliseconds. + * + * @return The advertisement interval in milliseconds. + */ + uint32_t getMaxPrimaryInterval() const { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); + } + const BLEProtocol::AddressBytes_t& getPeerAddress() const { return _peerAddress; }; @@ -582,11 +613,11 @@ public: private: ble::advertising_type_t _advType; - /** - * The advertising interval in ADV duration units (in other words, 0.625ms). - */ + /* The advertising interval in ADV duration units (in other words, 0.625ms). */ uint16_t _interval; + /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ uint16_t _timeout; + /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ uint16_t _maxInterval; peer_address_type_t _peerAddressType; own_address_type_t _ownAddressType; @@ -595,7 +626,7 @@ private: ble::phy_t _secondaryPhy; BLEProtocol::AddressBytes_t _peerAddress; uint8_t _txPower; - uint8_t _eventNumber; + uint8_t _maxSkip; uint8_t _channel37:1; uint8_t _channel38:1; uint8_t _channel39:1; diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 42593141a9..966ccc99f9 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -30,27 +30,27 @@ namespace pal { struct advertising_type_t : SafeEnum { enum type { /** - * Connectable and scannable undirected advertising . + * Connectable and scannable undirected advertising. */ ADV_IND = 0x00, /** - * Connectable high duty cycle directed advertising + * Connectable high duty cycle directed advertising. */ ADV_DIRECT_IND = 0x01, /** - * Scannable undirected advertising + * Scannable undirected advertising. */ ADV_SCAN_IND = 0x02, /** - * Non connectable undirected advertising + * Non connectable undirected advertising. */ ADV_NONCONN_IND = 0x03, /** - * Connectable low duty cycle directed advertising + * Connectable low duty cycle directed advertising. */ ADV_DIRECT_IND_LOW_DUTY_CYCLE = 0x04 }; @@ -70,12 +70,12 @@ struct advertising_type_t : SafeEnum { struct own_address_type_t : SafeEnum { enum type { /** - * Use the public device address + * Use the public device address. */ PUBLIC_ADDRESS = 0x00, /** - * Use the random device address + * Use the random device address. */ RANDOM_ADDRESS = 0x01, @@ -134,12 +134,12 @@ struct connection_peer_address_type_t : SafeEnum { enum type { /** - * Public device address + * Public device address. */ PUBLIC_ADDRESS = 0x00, /** - * Random device address + * Random device address. */ RANDOM_ADDRESS = 0x01, @@ -736,7 +736,7 @@ typedef uint32_t advertising_interval_t; * * Value comprised between -127 and +126 are considered power values in dBm while * the special value 127 can be used as a wildcard to indicates that the host - * has no preference or if the power informtion is not available. + * has no preference or if the power information is not available. */ typedef int8_t advertising_power_t; @@ -816,7 +816,7 @@ struct duplicates_filter_t : SafeEnum{ ENABLE, /** - * Enable duplicate filtering, reset the cache periodicaly. + * Enable duplicate filtering, reset the cache periodically. */ PERIODIC_RESET }; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0d464efd8a..d29620984b 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1636,8 +1636,8 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return _pal_gap.set_extended_advertising_parameters( handle, event_properties, - (pal::advertising_interval_t)params->getMinPrimaryInterval(), - (pal::advertising_interval_t)params->getMaxPrimaryInterval(), + (pal::advertising_interval_t)params->getMinPrimaryIntervalInADVUnits(), + (pal::advertising_interval_t)params->getMaxPrimaryIntervalInADVUnits(), channel_map, own_address_type, (pal::advertising_peer_address_type_t::type)params->getPeerAddressType().value(), From b276e6edafc4f5dd947cdd5c44b3d980119ae8e5 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 14:53:13 +0000 Subject: [PATCH 050/361] fix high duty cycle setting (reversed) --- features/FEATURE_BLE/ble/pal/GapTypes.h | 14 +++++++------- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- .../targets/TARGET_CORDIO/source/CordioPalGap.cpp | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 966ccc99f9..4921d16a7b 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -560,7 +560,7 @@ struct advertising_event_properties_t { directed(false), high_duty_cycle(false), use_legacy_pdu(false), - omit_advertisser_address(false), + omit_advertiser_address(false), include_tx_power(false) { } @@ -591,7 +591,7 @@ struct advertising_event_properties_t { directed(directed), high_duty_cycle(high_duty_cycle), use_legacy_pdu(use_legacy_pdu), - omit_advertisser_address(omit_advertisser_address), + omit_advertiser_address(omit_advertisser_address), include_tx_power(include_tx_power) { } @@ -610,7 +610,7 @@ struct advertising_event_properties_t { directed(false), high_duty_cycle(false), use_legacy_pdu(true), - omit_advertisser_address(false), + omit_advertiser_address(false), include_tx_power(false) { switch ((advertising_type_t::type) adv_type.value()) { @@ -621,11 +621,11 @@ struct advertising_event_properties_t { case advertising_type_t::ADV_DIRECT_IND: connectable = true; directed = true; + high_duty_cycle = true; break; case advertising_type_t::ADV_DIRECT_IND_LOW_DUTY_CYCLE: connectable = true; directed = true; - high_duty_cycle = true; use_legacy_pdu = true; break; case advertising_type_t::ADV_SCAN_IND: @@ -642,7 +642,7 @@ struct advertising_event_properties_t { directed(false), high_duty_cycle(false), use_legacy_pdu(true), - omit_advertisser_address(false), + omit_advertiser_address(false), include_tx_power(false) { switch (adv_type) { @@ -696,7 +696,7 @@ struct advertising_event_properties_t { /** * If set omit the advertiser address in all PDUs. */ - bool omit_advertisser_address :1; + bool omit_advertiser_address :1; /** * If set include the Tx power in the extended advertising header. @@ -714,7 +714,7 @@ struct advertising_event_properties_t { result |= directed << 2; result |= high_duty_cycle << 3; result |= use_legacy_pdu << 4; - result |= omit_advertisser_address << 5; + result |= omit_advertiser_address << 5; result |= include_tx_power << 6; return result; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index d29620984b..7a677a49d3 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1617,7 +1617,7 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params->getType()); event_properties.include_tx_power = params->getTxPowerInHeader(); - event_properties.omit_advertisser_address = params->getAnonymousAdvertising(); + event_properties.omit_advertiser_address = params->getAnonymousAdvertising(); event_properties.use_legacy_pdu = params->getUseLegacyPDU(); pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index 8df8dc7c66..782aa16b43 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -655,7 +655,7 @@ ble_error_t Gap::set_extended_advertising_parameters( ); DmAdvUseLegacyPdu(advertising_handle, event_properties.use_legacy_pdu); - DmAdvOmitAdvAddr(advertising_handle, event_properties.omit_advertisser_address); + DmAdvOmitAdvAddr(advertising_handle, event_properties.omit_advertiser_address); DmAdvConfig( advertising_handle, From 587eb9845e32e52576299d3755fec48e95668867 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 15:00:40 +0000 Subject: [PATCH 051/361] call the right func for set scan response --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7a677a49d3..9e9031cb43 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1696,7 +1696,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising } if (scan_reponse) { - _pal_gap.set_extended_advertising_data( + _pal_gap.set_extended_scan_response_data( handle, operation, minimiseFragmentation, From 23dc80896801ee091f3c6dec2cb99910573c25fd Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 15:08:51 +0000 Subject: [PATCH 052/361] handle legacy adv calls --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9e9031cb43..b75667368e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1668,9 +1668,15 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising if (!is_extended_advertising_enabled()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { if (scan_reponse) { - memcpy(&getLegacyAdvertisingPayload(), payload, sizeof(AdvertisingData)); + return _pal_gap.set_advertising_data( + payload->getPayloadLen(), + pal::advertising_data_t(payload->getPayload(), payload->getPayloadLen()) + ); } else { - memcpy(&getLegacyAdvertisingScanResponse(), payload, sizeof(AdvertisingData)); + return _pal_gap.set_scan_response_data( + payload->getPayloadLen(), + pal::advertising_data_t(payload->getPayload(), payload->getPayloadLen()) + ); } } return BLE_ERROR_NOT_IMPLEMENTED; From 2f6d8618189ca3ab68f90feee3c79a187d2550b7 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 15:16:05 +0000 Subject: [PATCH 053/361] fix packetisation in adv set data --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b75667368e..bc710804fa 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1686,23 +1686,20 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising uint16_t index = 0; const uint16_t& length = payload->getPayloadLen(); uint16_t packet_data_length = length; - pal::advertising_fragment_description_t operation( - pal::advertising_fragment_description_t::COMPLETE_FRAGMENT - ); - operation = (length > MAX_HCI_DATA_LENGTH) ? - pal::advertising_fragment_description_t::COMPLETE_FRAGMENT - : operation = pal::advertising_fragment_description_t::FIRST_FRAGMENT; + + typedef pal::advertising_fragment_description_t op_t; + op_t operation = (length > MAX_HCI_DATA_LENGTH) ? op_t::FIRST_FRAGMENT : op_t::COMPLETE_FRAGMENT; while (index < length) { if ((length - index) > MAX_HCI_DATA_LENGTH) { packet_data_length = MAX_HCI_DATA_LENGTH; } else { packet_data_length = length - index; - operation = pal::advertising_fragment_description_t::LAST_FRAGMENT; + operation = op_t::LAST_FRAGMENT; } if (scan_reponse) { - _pal_gap.set_extended_scan_response_data( + status = _pal_gap.set_extended_scan_response_data( handle, operation, minimiseFragmentation, @@ -1710,7 +1707,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising payload->getPayload() + index ); } else { - _pal_gap.set_extended_advertising_data( + status = _pal_gap.set_extended_advertising_data( handle, operation, minimiseFragmentation, @@ -1719,9 +1716,13 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising ); } + if (status != BLE_ERROR_NONE) { + return status; + } + index += packet_data_length; - operation = pal::advertising_fragment_description_t::INTERMEDIATE_FRAGMENT; + operation = op_t::INTERMEDIATE_FRAGMENT; } return status; From 66631716071abe12c90477d7448c8bc06e247abf Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 15:36:58 +0000 Subject: [PATCH 054/361] docs --- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 64 ++++++++++++++++++- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 7dc6257f40..ea8dfa01f7 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -507,48 +507,78 @@ public: _secondaryPhy = secondaryPhy; } + /** Return how many events can be skipped on the secondary channel. + * + * @return How many events can be skipped on the secondary channel. + */ uint8_t getSecondaryMaxSkip() const { return _maxSkip; } + /** Set how many events can be skipped on the secondary channel. + * + * @param eventNumber Number of events that can be skipped. + */ void setSecondaryMaxSkip( uint8_t eventNumber ) { _maxSkip = eventNumber; } + /** Enabled or disable the callback that notifies the user about a scan request. + * + * @param enable Enable callback if true. + */ void setScanRequestNotification( bool enable = true ) { _notifyOnScan = enable; } + /** Return of the callback for scan request is enabled. + * + * @return True if callback is enabled. + */ bool getScanRequestNotification() const { return _notifyOnScan; } + /** Use legacy PDU during advertising. + * + * @param enable If true legacy PDU will be used. + */ void setUseLegacyPDU( bool enable = true ) { _legacyPDU = enable; } + /** Check if legacy PDU is used during advertising. + * + * @return True legacy PDU will be used. + */ bool getUseLegacyPDU() const { return _legacyPDU; } + /** Set if TX power should be included in the header. + * + * @param enable If true include the TX power in the header. + */ void includeTxPowerInHeader( bool enable = true ) { _includeHeaderTxPower = enable; } + /** Check if TX power should be included in the header. + * + * @return True if TX power is included in the header. + */ bool getTxPowerInHeader() const { return _includeHeaderTxPower; } - /* helper get functions */ - /** Get the minimum advertisement interval in units of 0.625ms. * * @return The advertisement interval in advertisement duration units @@ -583,30 +613,60 @@ public: return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); } + /** Peer address for directed advertising. + * + * @return Peer address. + */ const BLEProtocol::AddressBytes_t& getPeerAddress() const { return _peerAddress; }; + /** Peer address type for directed advertising. + * + * @return Peer address type. + */ peer_address_type_t getPeerAddressType() const { return _peerAddressType; }; + /** Get PHY used for primary advertising. + * + * @return PHY used for primary advertising. + */ ble::phy_t getPrimaryPhy() const { return _primaryPhy; } + /** Get PHY used for secondary advertising. + * + * @return PHY used for secondary advertising. + */ ble::phy_t getSecondaryPhy() const { return _secondaryPhy; } + /** Check if channel 37 is used for primary advertising. + * + * @return True if channel used. + */ bool getChannel37() const { return _channel37; } + + /** Check if channel 38 is used for primary advertising. + * + * @return True if channel used. + */ bool getChannel38() const { return _channel37; } + + /** Check if channel 39 is used for primary advertising. + * + * @return True if channel used. + */ bool getChannel39() const { return _channel37; } From a1582bd3acccf209b9ea9c1e6198a27a7d79ce6a Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 16:29:42 +0000 Subject: [PATCH 055/361] pointer to ref --- features/FEATURE_BLE/ble/Gap.h | 41 ++++---- features/FEATURE_BLE/ble/generic/GenericGap.h | 10 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 98 ++++++++++++------- 3 files changed, 92 insertions(+), 57 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index b4fc4cb6f4..71cb72cb47 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1015,17 +1015,6 @@ public: static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; - struct AdvReportExtraInformation { - PeerAddressType_t directAddressType; - BLEProtocol::AddressBytes_t directAddress; - Phy_t primaryPhy; - Phy_t secondaryPhy; - uint16_t periodicInterval; - uint8_t SID; - int8_t txPower; - int8_t rssi; - }; - /** * Definition of the general handler of Gap related events. */ @@ -1037,8 +1026,8 @@ public: const BLEProtocol::AddressBytes_t &peerAddress ) { (void) advHandle; - (void) peerAddress; (void) peerAddressType; + (void) peerAddress; } virtual void onAdvertisingEnd( @@ -1057,14 +1046,27 @@ public: AdvertisingEventType_t type, PeerAddressType_t peerAddressType, BLEProtocol::AddressBytes_t const &peerAddress, - mbed::Span advertisingData, - const AdvReportExtraInformation &extraInfo + Phy_t primaryPhy, + Phy_t secondaryPhy, + uint8_t SID, + int8_t txPower, + int8_t rssi, + int16_t periodicInterval, + PeerAddressType_t directAddressType, + BLEProtocol::AddressBytes_t directAddress, + mbed::Span advertisingData ) { (void) type; (void) peerAddressType; (void) peerAddress; + (void) primaryPhy; + (void) secondaryPhy; + (void) SID; + (void) txPower; + (void) rssi; + (void) directAddressType; + (void) directAddress; (void) advertisingData; - (void) extraInfo; } /** @@ -1110,7 +1112,7 @@ public: * @param rxPhy PHY used by the receiver. * * @note Success doesn't mean the PHY has been updated it means both - * ends have negociated the best phy according to their configuration and + * ends have negotiated the best PHY according to their configuration and * capabilities. The PHY currently used are present in the txPhy and * rxPhy parameters. */ @@ -1162,21 +1164,22 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { + virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params) { (void) handle; (void) params; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false) { + virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, + bool minimiseFragmentation = false) { (void) handle; (void) payload; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response) { + virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response) { (void) handle; (void) response; /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index d9e41192b9..090559d1a1 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -84,11 +84,11 @@ public: ble_error_t destroyAdvertisingSet(AdvHandle_t handle); - ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params); + ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params); - ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation = false); + ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation = false); - ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response, bool minimiseFragmentation = false); + ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response, bool minimiseFragmentation = false); ble_error_t startAdvertising(AdvHandle_t handle, uint8_t maxEvents = 0, uint32_t maxDuration = 0); @@ -374,7 +374,7 @@ public: ); private: - ble_error_t setAdvertisingData(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse); + ble_error_t setAdvertisingData(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation, bool scan_reponse); /** @note Implements ConnectionEventMonitor. * @copydoc ConnectionEventMonitor::set_connection_event_handler @@ -467,7 +467,7 @@ private: pal::direct_address_type_t direct_address_type, const ble::address_t &direct_address, uint8_t data_length, - const uint8_t *data_size + const uint8_t *data ); virtual void on_periodic_advertising_sync_established( diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index bc710804fa..e6c4977515 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -27,6 +27,7 @@ #include "ble/generic/GenericGap.h" #include "drivers/Timeout.h" +#include "Span.h" namespace ble { namespace generic { @@ -1609,24 +1610,24 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_INVALID_PARAM; } -ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams* params) { - if (!get_adv_set_bit(_existing_sets, handle) || !params) { +ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params) { + if (!get_adv_set_bit(_existing_sets, handle)) { return BLE_ERROR_INVALID_PARAM; } - pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params->getType()); + pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params.getType()); - event_properties.include_tx_power = params->getTxPowerInHeader(); - event_properties.omit_advertiser_address = params->getAnonymousAdvertising(); - event_properties.use_legacy_pdu = params->getUseLegacyPDU(); + event_properties.include_tx_power = params.getTxPowerInHeader(); + event_properties.omit_advertiser_address = params.getAnonymousAdvertising(); + event_properties.use_legacy_pdu = params.getUseLegacyPDU(); - pal::advertising_channel_map_t channel_map(params->getChannel37(), params->getChannel38(), params->getChannel39()); - pal::own_address_type_t own_address_type = (pal::own_address_type_t::type)params->getOwnAddressType().value(); + pal::advertising_channel_map_t channel_map(params.getChannel37(), params.getChannel38(), params.getChannel39()); + pal::own_address_type_t own_address_type = (pal::own_address_type_t::type)params.getOwnAddressType().value(); if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { AddressUseType_t use_type = PERIPHERAL_CONNECTABLE; - if ((params->getAdvertisingType() == ADV_SCANNABLE_UNDIRECTED) || - (params->getAdvertisingType() == ADV_NON_CONNECTABLE_UNDIRECTED)) { + if ((params.getAdvertisingType() == ADV_SCANNABLE_UNDIRECTED) || + (params.getAdvertisingType() == ADV_NON_CONNECTABLE_UNDIRECTED)) { use_type = PERIPHERAL_NON_CONNECTABLE; } @@ -1636,32 +1637,32 @@ ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvert return _pal_gap.set_extended_advertising_parameters( handle, event_properties, - (pal::advertising_interval_t)params->getMinPrimaryIntervalInADVUnits(), - (pal::advertising_interval_t)params->getMaxPrimaryIntervalInADVUnits(), + (pal::advertising_interval_t)params.getMinPrimaryIntervalInADVUnits(), + (pal::advertising_interval_t)params.getMaxPrimaryIntervalInADVUnits(), channel_map, own_address_type, - (pal::advertising_peer_address_type_t::type)params->getPeerAddressType().value(), - params->getPeerAddress(), - (pal::advertising_filter_policy_t::type) params->getPolicyMode(), - (pal::advertising_power_t) params->getTxPower(), - params->getPrimaryPhy(), - params->getSecondaryMaxSkip(), - params->getSecondaryPhy(), + (pal::advertising_peer_address_type_t::type)params.getPeerAddressType().value(), + params.getPeerAddress(), + (pal::advertising_filter_policy_t::type) params.getPolicyMode(), + (pal::advertising_power_t) params.getTxPower(), + params.getPrimaryPhy(), + params.getSecondaryMaxSkip(), + params.getSecondaryPhy(), (handle % 0x10), - params->getScanRequestNotification() + params.getScanRequestNotification() ); } -ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation) { +ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation) { return setAdvertisingData(handle, payload, minimiseFragmentation, false); } -ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData* response, bool minimiseFragmentation) { +ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response, bool minimiseFragmentation) { return setAdvertisingData(handle, response, minimiseFragmentation, true); } -ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const AdvertisingData* payload, bool minimiseFragmentation, bool scan_reponse) { - if (!get_adv_set_bit(_existing_sets, handle) || !payload) { +ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation, bool scan_reponse) { + if (!get_adv_set_bit(_existing_sets, handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1669,13 +1670,13 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { if (scan_reponse) { return _pal_gap.set_advertising_data( - payload->getPayloadLen(), - pal::advertising_data_t(payload->getPayload(), payload->getPayloadLen()) + payload.getPayloadLen(), + pal::advertising_data_t(payload.getPayload(), payload.getPayloadLen()) ); } else { return _pal_gap.set_scan_response_data( - payload->getPayloadLen(), - pal::advertising_data_t(payload->getPayload(), payload->getPayloadLen()) + payload.getPayloadLen(), + pal::advertising_data_t(payload.getPayload(), payload.getPayloadLen()) ); } } @@ -1684,7 +1685,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising ble_error_t status = BLE_ERROR_NONE; uint16_t index = 0; - const uint16_t& length = payload->getPayloadLen(); + const uint16_t& length = payload.getPayloadLen(); uint16_t packet_data_length = length; typedef pal::advertising_fragment_description_t op_t; @@ -1704,7 +1705,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising operation, minimiseFragmentation, packet_data_length, - payload->getPayload() + index + payload.getPayload() + index ); } else { status = _pal_gap.set_extended_advertising_data( @@ -1712,7 +1713,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising operation, minimiseFragmentation, packet_data_length, - payload->getPayload() + index + payload.getPayload() + index ); } @@ -1817,10 +1818,25 @@ void GenericGap::on_extended_advertising_report( pal::direct_address_type_t direct_address_type, const ble::address_t &direct_address, uint8_t data_length, - const uint8_t *data_size + const uint8_t *data ) { - + if (_eventHandler) { + _eventHandler->onAdvertisingReport( + event_type, + (PeerAddressType_t::type)(address_type? address_type->value() : connection_peer_address_type_t::PUBLIC_ADDRESS), + (BLEProtocol::AddressBytes_t&)address, + primary_phy, + secondary_phy? *secondary_phy : phy_t::LE_1M, + advertising_sid, + tx_power, + rssi, + periodic_advertising_interval, + (PeerAddressType_t::type)direct_address_type.value(), + (BLEProtocol::AddressBytes_t&)direct_address, + mbed::make_Span(data, data_length) + ); + } } void GenericGap::on_periodic_advertising_sync_established( @@ -1860,7 +1876,16 @@ void GenericGap::on_advertising_set_terminated( uint8_t number_of_completed_extended_advertising_events ) { + clear_adv_set_bit(_active_sets, advertising_handle); + if (_eventHandler) { + _eventHandler->onAdvertisingEnd( + advertising_handle, + connection_handle, + number_of_completed_extended_advertising_events, + (SUCCESS == status) + ); + } } void GenericGap::on_scan_request_received( @@ -1869,6 +1894,13 @@ void GenericGap::on_scan_request_received( const ble::address_t &address ) { + if (_eventHandler) { + _eventHandler->onScanRequest( + advertising_handle, + (ble::peer_address_type_t::type)scanner_address_type.value(), + (const BLEProtocol::AddressBytes_t&)address + ); + } } From 2b00903a30c2ad94ec15dd90ee2a3c8fbc3fc696 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 9 Nov 2018 16:38:36 +0000 Subject: [PATCH 056/361] missing param --- features/FEATURE_BLE/ble/Gap.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 71cb72cb47..a71e465365 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1064,6 +1064,7 @@ public: (void) SID; (void) txPower; (void) rssi; + (void) periodicInterval; (void) directAddressType; (void) directAddress; (void) advertisingData; From 962b5c34d4bd791102b20d8443a2840bb7b1b67a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:35:53 +0000 Subject: [PATCH 057/361] BLE: Tag scanning filter policy mode with FIXME --- features/FEATURE_BLE/ble/BLETypes.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index a13cef2464..f720dc01c3 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -359,6 +359,8 @@ enum advertising_policy_mode_t { ADV_POLICY_FILTER_ALL_REQS = 3, }; + +// FIXME: Add new modes! /** * Scanning policy filter mode. * From 1a14453da1a6752e158a93e105618b476545db76 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:38:41 +0000 Subject: [PATCH 058/361] BLE: Add mechanism to track use of non compatible scan API. --- features/FEATURE_BLE/ble/Gap.h | 14 ++++++++++- features/FEATURE_BLE/ble/generic/GenericGap.h | 8 ++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 25 +++++++++++++++++++ platform/mbed_error.h | 1 + 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index a71e465365..9588e9496b 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1293,7 +1293,8 @@ public: uint32_t duration = 0, uint32_t period = 0 ) { - return startRadioScan(_scanningParams); + use_non_deprecated_scan_api(); + return BLE_ERROR_NOT_IMPLEMENTED; }; /** @@ -1350,6 +1351,7 @@ public: uint16_t timeout = 0, bool activeScanning = false ) { + use_deprecated_scan_api(); ble_error_t rc; if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && @@ -1372,6 +1374,7 @@ public: * @note All restrictions from setScanParams(uint16_t, uint16_t, uint16_t, bool) apply. */ ble_error_t setScanParams(const GapScanningParams& scanningParams) { + use_deprecated_scan_api(); return setScanParams( scanningParams.getInterval(), scanningParams.getWindow(), @@ -1391,6 +1394,7 @@ public: */ ble_error_t setScanInterval(uint16_t interval) { + use_deprecated_scan_api(); return _scanningParams.setInterval(interval); } @@ -1407,6 +1411,7 @@ public: */ ble_error_t setScanWindow(uint16_t window) { + use_deprecated_scan_api(); ble_error_t rc; if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) { return rc; @@ -1433,6 +1438,7 @@ public: */ ble_error_t setScanTimeout(uint16_t timeout) { + use_deprecated_scan_api(); ble_error_t rc; if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) { return rc; @@ -1460,6 +1466,7 @@ public: */ ble_error_t setActiveScanning(bool activeScanning) { + use_deprecated_scan_api(); _scanningParams.setActiveScanning(activeScanning); /* If scanning is already active, propagate the new settings to the stack. */ @@ -1474,6 +1481,10 @@ protected: /* Override the following in the underlying adaptation layer to provide the * functionality of scanning. */ + virtual void use_deprecated_scan_api() const { } + + virtual void use_non_deprecated_scan_api() const { } + /** * Start scanning procedure in the underlying BLE stack. * @@ -1483,6 +1494,7 @@ protected: */ virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) { + use_deprecated_scan_api(); (void)scanningParams; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 090559d1a1..fa8be4dee3 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -424,6 +424,10 @@ private: void on_address_rotation_timeout(); + virtual void use_deprecated_scan_api() const; + + virtual void use_non_deprecated_scan_api() const; + /* implements pal::Gap::EventHandler */ private: virtual void on_read_phy( @@ -529,6 +533,10 @@ private: uint8_t _existing_sets[(MAX_ADVERTISING_SETS / 8) + 1]; uint8_t _active_sets[(MAX_ADVERTISING_SETS / 8) + 1]; + // deprecation flags + mutable bool _deprecated_scan_api_used : 1; + mutable bool _non_deprecated_scan_api_used : 1; + private: bool is_extended_advertising_enabled() { return _pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index e6c4977515..6525ef753d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -59,6 +59,9 @@ static const Gap::ConnectionParams_t default_connection_params = { static const GapScanningParams default_scan_params; +static const mbed_error_status_t mixed_scan_api_error = + MBED_MAKE_ERROR(MBED_MODULE_BLE, MBED_ERROR_CODE_BLE_USE_INCOMPATIBLE_API); + /* * Return true if value is included in the range [lower_bound : higher_bound] */ @@ -886,6 +889,8 @@ ble_error_t GenericGap::setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) { + use_deprecated_scan_api(); + if (mode > Gap::SCAN_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; } @@ -911,6 +916,7 @@ Gap::AdvertisingPolicyMode_t GenericGap::getAdvertisingPolicyMode(void) const Gap::ScanningPolicyMode_t GenericGap::getScanningPolicyMode(void) const { + use_deprecated_scan_api(); return (ScanningPolicyMode_t) _scanning_filter_policy.value(); } @@ -921,6 +927,8 @@ Gap::InitiatorPolicyMode_t GenericGap::getInitiatorPolicyMode(void) const ble_error_t GenericGap::startRadioScan(const GapScanningParams &scanningParams) { + use_deprecated_scan_api(); + if (is_scan_params_valid(&scanningParams) == false) { return BLE_ERROR_INVALID_PARAM; } @@ -1904,5 +1912,22 @@ void GenericGap::on_scan_request_received( } + +void GenericGap::use_deprecated_scan_api() const +{ + if (_non_deprecated_scan_api_used) { + MBED_ERROR(mixed_scan_api_error, "Use of deprecated scan API with up to date API"); + } + _deprecated_scan_api_used = true; +} + +void GenericGap::use_non_deprecated_scan_api() const +{ + if (_deprecated_scan_api_used) { + MBED_ERROR(mixed_scan_api_error, "Use of up to date scan API with deprecated API"); + } + _non_deprecated_scan_api_used = true; +} + } // namespace generic } // namespace ble diff --git a/platform/mbed_error.h b/platform/mbed_error.h index fa2b9d621b..7c3d155967 100644 --- a/platform/mbed_error.h +++ b/platform/mbed_error.h @@ -788,6 +788,7 @@ typedef enum _mbed_error_code { MBED_DEFINE_SYSTEM_ERROR(ASSERTION_FAILED, 68), /* 324 Assertion Failed */ MBED_DEFINE_SYSTEM_ERROR(AUTHENTICATION_FAILED, 69), /* 325 Authentication Failed */ MBED_DEFINE_SYSTEM_ERROR(RBP_AUTHENTICATION_FAILED, 70), /* 326 Rollback Protection Authentication Failed */ + MBED_DEFINE_SYSTEM_ERROR(BLE_USE_INCOMPATIBLE_API, 71), /* 327 Concurrent use of incompatible versions of a BLE API */ //Everytime you add a new system error code, you must update //Error documentation under Handbook to capture the info on From 27ea24886353181748af83f433fae0a115e6dadd Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:39:19 +0000 Subject: [PATCH 059/361] BLE: Fix GapScanningParams includes. --- features/FEATURE_BLE/ble/GapScanningParams.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 16dc7bb72c..06ceafc9f9 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -17,6 +17,9 @@ #ifndef MBED_GAP_SCANNING_PARAMS_H__ #define MBED_GAP_SCANNING_PARAMS_H__ +#include +#include "ble/blecommon.h" + /** * @addtogroup ble * @{ From 28ead51401ce16df96a3a7059ba257e2560e9283 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:41:16 +0000 Subject: [PATCH 060/361] BLE: Add GapScanParameters type. The new type covers what is required by extended and legacy scan parameters. --- features/FEATURE_BLE/ble/GapScanParameters.h | 136 +++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 features/FEATURE_BLE/ble/GapScanParameters.h diff --git a/features/FEATURE_BLE/ble/GapScanParameters.h b/features/FEATURE_BLE/ble/GapScanParameters.h new file mode 100644 index 0000000000..ae83d56b79 --- /dev/null +++ b/features/FEATURE_BLE/ble/GapScanParameters.h @@ -0,0 +1,136 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018-2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef MBED_GAP_SCAN_PARAMETERS_H__ +#define MBED_GAP_SCAN_PARAMETERS_H__ + +#include +#include "ble/blecommon.h" +#include "BLETypes.h" + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + + +class GapScanParameters { +public: + enum own_address_type_t { + PUBLIC_ADDRESS = 0x00, + RANDOM_ADDRESS = 0x01, + PRIVATE_RESOLVABLE_PUBLIC_FALLBACK = 0x02, + PRIVATE_RESOLVABLE_RANDOM_FALLBACK = 0x03 + }; + + struct phy_configuration_t { + uint16_t interval; + uint16_t window; + bool active_scanning; + }; + + GapScanParameters() : + own_address_type(PUBLIC_ADDRESS), + phy_1m_configuration(/* TODO */), + phy_coded_configuration(/* TODO */) + { } + + GapScanParameters& set_own_address_type(own_address_type_t address) + { + own_address_type = address; + return *this; + } + + own_address_type_t get_own_address_type() const + { + return own_address_type; + } + + GapScanParameters& set_scanning_filter_policy(ble::scanning_policy_mode_t filter_policy) + { + scanning_filter_policy = filter_policy; + return *this; + } + + ble::scanning_policy_mode_t get_scanning_filter_policy() const + { + return scanning_filter_policy; + } + + GapScanParameters& set_scanning_phys(bool enable_1m, bool enable_coded) + { + phys.set_1m(enable_1m); + phys.set_coded(enable_coded); + return *this; + } + + ble::phy_set_t get_scanning_phys() const + { + return phys; + } + + GapScanParameters& set_1m_phy_configuration( + uint16_t interval, + uint16_t window, + bool active_scanning + ) + { + phys.set_1m(true); + phy_configuration_t new_conf = { interval, window, active_scanning }; + phy_1m_configuration = new_conf; + return *this; + } + + phy_configuration_t get_1m_configuration() const + { + return phy_1m_configuration; + } + + GapScanParameters& set_coded_phy_configuration( + uint16_t interval, + uint16_t window, + bool active_scanning + ) + { + phys.set_coded(true); + phy_configuration_t new_conf = { interval, window, active_scanning }; + phy_coded_configuration = new_conf; + return *this; + } + + phy_configuration_t get_coded_configuration() const + { + return phy_1m_configuration; + } + +private: + own_address_type_t own_address_type; + ble::scanning_policy_mode_t scanning_filter_policy; + + ble::phy_set_t phys; + + phy_configuration_t phy_1m_configuration; + phy_configuration_t phy_coded_configuration; +}; + +/** + * @} + * @} + */ + +#endif /* ifndef MBED_GAP_SCAN_PARAMETERS_H__ */ From 4835a1afdc68bcf262033f225b1cd47ed4fd8aac Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:42:16 +0000 Subject: [PATCH 061/361] BLE: Add non legacy scan API. --- features/FEATURE_BLE/ble/Gap.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9588e9496b..49042da213 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -23,6 +23,7 @@ #include "GapAdvertisingParams.h" #include "GapScanningParams.h" #include "GapEvents.h" +#include "ble/GapScanParameters.h" #include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" @@ -1281,17 +1282,18 @@ public: /* scanning */ - ble_error_t setScanParameters( - const GapScanningParams* params + virtual ble_error_t setScanParameters( + const GapScanParameters& params ) { + use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; }; - ble_error_t startScan( + virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, - uint32_t duration = 0, - uint32_t period = 0 + uint16_t duration = 0, + uint16_t period = 0 ) { use_non_deprecated_scan_api(); return BLE_ERROR_NOT_IMPLEMENTED; From 24460de86fc6510758a619299132f5961cbdc46f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:42:58 +0000 Subject: [PATCH 062/361] BLE: Implement new scan API in GenericGap --- features/FEATURE_BLE/ble/generic/GenericGap.h | 8 ++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 86 +++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index fa8be4dee3..19b188f5f2 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -373,6 +373,14 @@ public: DisconnectionReason_t reason ); + virtual ble_error_t setScanParameters(const GapScanParameters ¶ms); + + virtual ble_error_t startScan( + scanning_filter_duplicates_t filtering, + uint16_t duration_ms, + uint16_t period_ms + ); + private: ble_error_t setAdvertisingData(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation, bool scan_reponse); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 6525ef753d..fab18b91eb 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1912,6 +1912,92 @@ void GenericGap::on_scan_request_received( } +ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) +{ + use_non_deprecated_scan_api(); + + // FIXME: validate parameters + // FIXME: deal with random address rotation + + if (is_extended_advertising_enabled()) { + bool active_scanning[] = { + params.get_1m_configuration().active_scanning, + params.get_coded_configuration().active_scanning + }; + + uint16_t scan_interval[] = { + params.get_1m_configuration().interval, + params.get_coded_configuration().interval + }; + + uint16_t scan_window[] = { + params.get_1m_configuration().window, + params.get_coded_configuration().window + }; + + return _pal_gap.set_extended_scan_parameters( + (pal::own_address_type_t::type) params.get_own_address_type(), + (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy(), + params.get_scanning_phys(), + active_scanning, + scan_interval, + scan_window + ); + } else { + GapScanParameters::phy_configuration_t legacy_configuration = + params.get_1m_configuration(); + + return _pal_gap.set_scan_parameters( + legacy_configuration.active_scanning, + legacy_configuration.interval, + legacy_configuration.window, + (pal::own_address_type_t::type) params.get_own_address_type(), + (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy() + ); + } +} + +ble_error_t GenericGap::startScan( + scanning_filter_duplicates_t filtering, + uint16_t duration, + uint16_t period +) +{ + use_non_deprecated_scan_api(); + // FIXME: deal with random address rotation + + if (is_extended_advertising_enabled()) { + return _pal_gap.extended_scan_enable( + /* enable */true, + (pal::duplicates_filter_t::type) filtering, + duration, + period + ); + } else { + if (period != 0) { + return BLE_ERROR_INVALID_PARAM; + } + + ble_error_t err = _pal_gap.scan_enable( + true, + filtering == SCAN_FILTER_DUPLICATES_DISABLED ? false : true + ); + + if (err) { + return err; + } + + _scan_timeout.detach(); + if (duration) { + _scan_timeout.attach_us( + mbed::callback(this, &GenericGap::on_scan_timeout), + duration * 10 /* ms */ * 1000 /* us */ + ); + } + + return BLE_ERROR_NONE; + } +} void GenericGap::use_deprecated_scan_api() const { From dc07e44290fafe92caa1a533a7f8d7ac2be14b1e Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 16:43:55 +0000 Subject: [PATCH 063/361] BLE: makes GenericGap::stopGap aware of extended scan. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index fab18b91eb..ff6d507c17 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -16,6 +16,8 @@ #include #include +#include + #include "ble/BLEInstanceBase.h" #include "ble/BLEProtocol.h" @@ -530,7 +532,13 @@ ble_error_t GenericGap::stopAdvertising() ble_error_t GenericGap::stopScan() { - ble_error_t err = _pal_gap.scan_enable(false, false); + ble_error_t err; + if (is_extended_advertising_enabled()) { + err = _pal_gap.extended_scan_enable(false, pal::duplicates_filter_t::DISABLE, 0, 0); + } else { + err = _pal_gap.scan_enable(false, false); + } + if (err) { return err; } From 61536c3f6429eda66eb6ede5106d1601c50c10f5 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 21:03:39 +0000 Subject: [PATCH 064/361] BLE: revert non backward compatible changes. This changeset includes order of function declaration in headers. --- features/FEATURE_BLE/ble/Gap.h | 3149 +++++++++-------- .../FEATURE_BLE/ble/GapAdvertisingParams.h | 557 +-- features/FEATURE_BLE/ble/generic/GenericGap.h | 13 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 13 +- 4 files changed, 1729 insertions(+), 2003 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 49042da213..965fe82f86 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -27,8 +27,13 @@ #include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" -#include "platform/NonCopyable.h" -#include "platform/Span.h" +#include "AdvertisingParameters.h" + +/* Forward declarations for classes that are only used for pointers or + references. */ +class GapAdvertisingParams; +class GapScanningParams; +class GapAdvertisingData; /** * @addtogroup ble @@ -84,18 +89,18 @@ * Gap& gap; * * // construct the packet to advertise - * AdvertisingData advertising_data; + * GapAdvertisingData advertising_data; * * // Add advertiser flags * advertising_data.addFlags( - * AdvertisingData::LE_GENERAL_DISCOVERABLE | - * AdvertisingData::BREDR_NOT_SUPPORTED + * GapAdvertisingData::LE_GENERAL_DISCOVERABLE | + * GapAdvertisingData::BREDR_NOT_SUPPORTED * ); * * // Add the name of the device to the advertising data * static const uint8_t device_name[] = "HRM"; * advertising_data.addData( - * AdvertisingData::COMPLETE_LOCAL_NAME, + * GapAdvertisingData::COMPLETE_LOCAL_NAME, * device_name, * sizeof(device_name) * ); @@ -318,6 +323,58 @@ * controller or by the peer. */ class Gap { + /* + * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated. + * They have been relocated to the class BLEProtocol. + */ +public: + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. + */ + typedef BLEProtocol::AddressType_t AddressType_t; + + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. + */ + typedef BLEProtocol::AddressType_t addr_type_t; + + /** + * Address-type for BLEProtocol addresses. + * + * @deprecated Use BLEProtocol::AddressType_t instead. The following + * constants have been left in their deprecated state to transparently + * support existing applications that may have used Gap::ADDR_TYPE_*. + */ + enum DeprecatedAddressType_t { + ADDR_TYPE_PUBLIC = BLEProtocol::AddressType::PUBLIC, + ADDR_TYPE_RANDOM_STATIC = BLEProtocol::AddressType::RANDOM_STATIC, + ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE, + ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE + }; + + /** + * Length (in octets) of the BLE MAC address. + */ + static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN; + + /** + * 48-bit address, LSB format. + * + * @deprecated Use BLEProtocol::AddressBytes_t instead. + */ + typedef BLEProtocol::AddressBytes_t Address_t; + + /** + * 48-bit address, LSB format. + * + * @deprecated Use BLEProtocol::AddressBytes_t instead. + */ + typedef BLEProtocol::AddressBytes_t address_t; + public: /** * Enumeration of possible timeout sources. @@ -395,9 +452,49 @@ public: CONN_INTERVAL_UNACCEPTABLE = 0x3B, }; - typedef ble::advertising_policy_mode_t AdvertisingPolicyMode_t; + /** + * Advertising policy filter modes. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. + */ + enum AdvertisingPolicyMode_t { + /** + * The whitelist is not used to filter peer request during advertising. + */ + ADV_POLICY_IGNORE_WHITELIST = 0, - typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; + /** + * The whitelist is used to filter peer scan requests. + */ + ADV_POLICY_FILTER_SCAN_REQS = 1, + + /** + * The whitelist is used to filter peer connection requests. + */ + ADV_POLICY_FILTER_CONN_REQS = 2, + + /** + * The whitelist is used to filter peer scan and connection requests. + */ + ADV_POLICY_FILTER_ALL_REQS = 3, + }; + + /** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ + enum ScanningPolicyMode_t { + /** + * The whitelist is not used for scanning operations. + */ + SCAN_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter incoming advertising. + */ + SCAN_POLICY_FILTER_ALL_ADV = 1, + }; /** * Connection initiation policy filter mode. @@ -437,6 +534,21 @@ public: uint8_t capacity; }; + /** + * Description of the states of the device. + */ + struct GapState_t { + /** + * If set, the device is currently advertising. + */ + unsigned advertising : 1; + + /** + * If set, the device is connected to at least one other peer. + */ + unsigned connected : 1; + }; + /** * Opaque value type representing a connection handle. * @@ -475,7 +587,7 @@ public: /** * Parameters of a BLE connection. */ - struct ConnectionParams_t { + typedef struct { /** * Minimum interval between two connection events allowed for a * connection. @@ -517,7 +629,7 @@ public: * @note maxConnectionInterval is in ms in the formulae above. */ uint16_t connectionSupervisionTimeout; - }; + } ConnectionParams_t; /** * Enumeration of GAP roles. @@ -578,7 +690,7 @@ public: /** * Type of advertisement. */ - ble::advertising_type_t type; + GapAdvertisingParams::AdvertisingType_t type; /** * Length of the advertisement data. @@ -604,7 +716,7 @@ public: "addressType won't work in connect when privacy is enabled; please" "use peerAddrType" ) - BLEProtocol::AddressType_t addressType; + AddressType_t addressType; /** * Type of the address received. @@ -663,7 +775,7 @@ public: /** * Address type of the local device. */ - BLEProtocol::AddressType_t ownAddrType; + BLEProtocol::AddressType_t ownAddrType; /** * Address of the local device. @@ -684,7 +796,7 @@ public: /** * Connection parameters. */ - const ConnectionParams_t *connectionParams; + const ConnectionParams_t *connectionParams; /** * Resolvable address used by the peer. @@ -1138,93 +1250,101 @@ public: ~EventHandler() { } }; - /* The following functions are meant to be overridden in the platform-specific subclass. */ - + /* + * The following functions are meant to be overridden in the platform-specific subclass. + */ public: + /** + * Set the device MAC address and type. + * + * The address set is used in subsequent GAP operations: scanning, + * advertising and connection initiation. + * + * @param[in] type Type of the address to set. + * @param[in] address Value of the address to set. It is ordered in + * little endian. This parameter is not considered if the address type + * is RANDOM_PRIVATE_RESOLVABLE or RANDOM_PRIVATE_NON_RESOLVABLE. For those + * types of address, the BLE API itself generates the address. + * + * @note Some implementation may refuse to set a new PUBLIC address. + * @note Random static address set does not change. + * + * @deprecated Starting with mbed-os-5.9.0 this function is deprecated and + * address management is delegated to implementation. Implementations may or + * may not continue to support this function. Compliance with the Bluetooth + * specification and unification of behaviour between implementations are + * the key reasons behind this change: + * - Many implementations do not allow changing of the public address. + * Therefore programs relying on this function are not portable across BLE + * implementations. + * - The Bluetooth specification forbid replacement of the random static + * address; this address can be set once and only once: at startup. + * Depending on the underlying implementation the random address may or + * may not have been set automatically at startup; therefore update of the + * Random Static address after ble initialisation may be a fault. As a + * result calls to this function were not portable. + * Furthermore replacement of the random static address silently + * invalidates the bond stored in the secure database. - /* advertising */ - - virtual uint8_t getMaxAdvertisingSetNumber() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 1; - } - - virtual uint8_t getMaxAdvertisingDataLength() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0x1F; - } - - virtual ble_error_t createAdvertisingSet(AdvHandle_t* handle) { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - virtual ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params) { - (void) handle; - (void) params; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, - bool minimiseFragmentation = false) { - (void) handle; - (void) payload; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response) { - (void) handle; - (void) response; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - virtual ble_error_t startAdvertising( - AdvHandle_t handle, - uint8_t maxEvents = 0, - uint32_t maxDuration = 0 + * @return BLE_ERROR_NONE on success. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "Non portable API, use enablePrivacy to enable use of private addresses" + ) + virtual ble_error_t setAddress( + BLEProtocol::AddressType_t type, + const BLEProtocol::AddressBytes_t address ) { - (void) maxEvents; - (void) maxDuration; - /* deprecation compatibility */ - if (handle != LEGACY_ADVERTISING_HANDLE) { - return BLE_ERROR_NOT_IMPLEMENTED; - } + /* avoid compiler warnings about unused variables */ + (void)type; + (void)address; - ble_error_t status = setAdvertisingData(getLegacyAdvertisingPayload(), getLegacyAdvertisingScanResponse()); - - if (status != BLE_ERROR_NONE) { - return status; - } - status = startAdvertising(getLegacyAdvertisingParams()); - - /* Requesting action from porter(s): override this API if this capability is supported. */ - return status; - } - - virtual ble_error_t stopAdvertising(AdvHandle_t handle) { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - virtual bool isAdvertisingActive(AdvHandle_t handle) const { - if (handle != LEGACY_ADVERTISING_HANDLE) { - return false; - } - /* Requesting action from porter(s): override this API if this capability is supported. */ - return state.advertising; + /** + * Fetch the current address and its type. + * + * @param[out] typeP Type of the current address set. + * @param[out] address Value of the current address. + * + * @note If privacy is enabled the device address may be unavailable to + * application code. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t getAddress( + BLEProtocol::AddressType_t *typeP, + BLEProtocol::AddressBytes_t address + ) { + /* Avoid compiler warnings about unused variables. */ + (void)typeP; + (void)address; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * Return the type of a random address. + * + * @param[in] address The random address to retrieve the type from. The + * address must be ordered in little endian. + * + * @param[out] addressType Type of the address to fill. + * + * @return BLE_ERROR_NONE in case of success or BLE_ERROR_INVALID_PARAM if + * the address in input was not identifiable as a random address. + */ + static ble_error_t getRandomAddressType( + const BLEProtocol::AddressBytes_t address, + RandomAddressType_t* addressType + ); + /** * Get the minimum advertising interval in milliseconds, which can be used * for connectable advertising types. @@ -1234,7 +1354,8 @@ public: */ virtual uint16_t getMinAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return 0; } @@ -1247,7 +1368,8 @@ public: */ virtual uint16_t getMinNonConnectableAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return 0; } @@ -1258,47 +1380,34 @@ public: */ virtual uint16_t getMaxAdvertisingInterval(void) const { - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return 0xFFFF; } /** - * Query the underlying stack for allowed Tx power values. + * Stop the ongoing advertising procedure. * - * @param[out] valueArrayPP Receive the immutable array of Tx values. - * @param[out] countP Receive the array's size. + * @note The current advertising parameters remain in effect. + * + * @retval BLE_ERROR_NONE if the advertising procedure has been successfully + * stopped. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). */ - virtual void getPermittedTxPowerValues( - const int8_t **valueArrayPP, - size_t *countP - ) { - /* Avoid compiler warnings about unused variables. */ - (void)valueArrayPP; - (void)countP; - - /* Requesting action from porter(s): override this API if this capability is supported. */ - *countP = 0; + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t stopAdvertising(void) + { + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; } - - /* scanning */ - - virtual ble_error_t setScanParameters( - const GapScanParameters& params - ) { - use_non_deprecated_scan_api(); - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - }; - - virtual ble_error_t startScan( - ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, - uint16_t duration = 0, - uint16_t period = 0 - ) { - use_non_deprecated_scan_api(); - return BLE_ERROR_NOT_IMPLEMENTED; - }; - + /** * Stop the ongoing scanning procedure. * @@ -1308,311 +1417,44 @@ public: */ virtual ble_error_t stopScan() { - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /* this block contains non-virtual helper functions for setting scan parameters */ -public: - /** - * Set the parameters used during a scan procedure. + * Initiate a connection to a peer. * - * @param[in] interval in ms between the start of two consecutive scan windows. - * That value is greater or equal to the scan window value. The - * maximum allowed value is 10.24ms. + * Once the connection is established, a ConnectionCallbackParams_t event is + * emitted to handlers that have been registered with onConnection(). * - * @param[in] window Period in ms during which the scanner listens to - * advertising channels. That value is in the range 2.5ms to 10.24s. + * @param[in] peerAddr MAC address of the peer. It must be in LSB format. + * @param[in] peerAddrType Address type of the peer. It is usually obtained + * from advertising frames. + * @param[in] connectionParams Connection parameters to use. + * @param[in] scanParams Scan parameters used to find the peer. * - * @param[in] timeout Duration in seconds of the scan procedure if any. The - * special value 0 disable specific duration of the scan procedure. - * - * @param[in] activeScanning If set to true, then the scanner sends scan - * requests to a scannable or connectable advertiser. If set to false, then the - * scanner does not send any request during the scan procedure. - * - * @return BLE_ERROR_NONE if the scan parameters were correctly set. - * - * @note The scanning window divided by the interval determines the duty - * cycle for scanning. For example, if the interval is 100ms and the window - * is 10ms, then the controller scans for 10 percent of the time. - * - * @note If the interval and the window are set to the same value, then the - * device scans continuously during the scan procedure. The scanning - * frequency changes at every interval. - * - * @note Once the scanning parameters have been configured, scanning can be - * enabled by using startScan(). - * - * @note The scan interval and window are recommendations to the BLE stack. + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. */ - ble_error_t setScanParams( - uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, - uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, - uint16_t timeout = 0, - bool activeScanning = false + virtual ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + PeerAddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams ) { - use_deprecated_scan_api(); - ble_error_t rc; - if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { - _scanningParams.setActiveScanning(activeScanning); - return BLE_ERROR_NONE; - } + /* Avoid compiler warnings about unused variables. */ + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams; + (void)scanParams; - return rc; - } - - /** - * Set the parameters used during a scan procedure. - * - * @param[in] scanningParams Parameter struct containing the interval, period, - * timeout and active scanning toggle. - * - * @return BLE_ERROR_NONE if the scan parameters were correctly set. - * - * @note All restrictions from setScanParams(uint16_t, uint16_t, uint16_t, bool) apply. - */ - ble_error_t setScanParams(const GapScanningParams& scanningParams) { - use_deprecated_scan_api(); - return setScanParams( - scanningParams.getInterval(), - scanningParams.getWindow(), - scanningParams.getTimeout(), - scanningParams.getActiveScanning() - ); - } - - /** - * Set the interval parameter used during scanning procedures. - * - * @param[in] interval Interval in ms between the start of two consecutive - * scan windows. That value is greater or equal to the scan window value. - * The maximum allowed value is 10.24ms. - * - * @return BLE_ERROR_NONE if the scan interval was correctly set. - */ - ble_error_t setScanInterval(uint16_t interval) - { - use_deprecated_scan_api(); - return _scanningParams.setInterval(interval); - } - - /** - * Set the window parameter used during scanning procedures. - * - * @param[in] window Period in ms during which the scanner listens to - * advertising channels. That value is in the range 2.5ms to 10.24s. - * - * @return BLE_ERROR_NONE if the scan window was correctly set. - * - * @note If scanning is already active, the updated value of scanWindow - * is propagated to the underlying BLE stack. - */ - ble_error_t setScanWindow(uint16_t window) - { - use_deprecated_scan_api(); - ble_error_t rc; - if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) { - return rc; - } - - /* If scanning is already active, propagate the new setting to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } - - /** - * Set the timeout parameter used during scanning procedures. - * - * @param[in] timeout Duration in seconds of the scan procedure if any. The - * special value 0 disables specific duration of the scan procedure. - * - * @return BLE_ERROR_NONE if the scan timeout was correctly set. - * - * @note If scanning is already active, the updated value of scanTimeout - * is propagated to the underlying BLE stack. - */ - ble_error_t setScanTimeout(uint16_t timeout) - { - use_deprecated_scan_api(); - ble_error_t rc; - if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) { - return rc; - } - - /* If scanning is already active, propagate the new settings to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } - - /** - * Enable or disable active scanning. - * - * @param[in] activeScanning If set to true, then the scanner sends scan - * requests to a scannable or connectable advertiser. If set to false then the - * scanner does not send any request during the scan procedure. - * - * @return BLE_ERROR_NONE if active scanning was successfully set. - * - * @note If scanning is already in progress, then active scanning is - * enabled for the underlying BLE stack. - */ - ble_error_t setActiveScanning(bool activeScanning) - { - use_deprecated_scan_api(); - _scanningParams.setActiveScanning(activeScanning); - - /* If scanning is already active, propagate the new settings to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } - -protected: - /* Override the following in the underlying adaptation layer to provide the - * functionality of scanning. */ - - virtual void use_deprecated_scan_api() const { } - - virtual void use_non_deprecated_scan_api() const { } - - /** - * Start scanning procedure in the underlying BLE stack. - * - * @param[in] scanningParams Parameters of the scan procedure. - * - * @return BLE_ERROR_NONE if the scan procedure was successfully started. - */ - virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) - { - use_deprecated_scan_api(); - (void)scanningParams; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } -public: - /* filtering policy */ - - /** - * Get the maximum size of the whitelist. - * - * @return Maximum size of the whitelist. - * - * @note If using Mbed OS, you can configure the size of the whitelist by - * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. - */ - virtual uint8_t getMaxWhitelistSize(void) const - { - return 0; - } - - /** - * Get the Link Layer to use the internal whitelist when scanning, - * advertising or initiating a connection depending on the filter policies. - * - * @param[in,out] whitelist Define the whitelist instance which is used - * to store the whitelist requested. In input, the caller provisions memory. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * copied into the supplied reference. - */ - virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the whitelist to be used during GAP procedures. - * - * @param[in] whitelist A reference to a whitelist containing the addresses - * to be copied to the internal whitelist. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * populated with the addresses in the given whitelist. - * - * @note The whitelist must not contain addresses of type @ref - * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This - * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might - * change its private address at any time, and it is not possible to resolve - * it. - * - * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), - * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. - */ - virtual ble_error_t setWhitelist(const Whitelist_t &whitelist) - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the current scan policy filter mode. - * - * @return The current scan policy filter mode. - */ - virtual ScanningPolicyMode_t getScanningPolicyMode(void) const - { - return ble::SCAN_POLICY_IGNORE_WHITELIST; - } - - /** - * Set the scan policy filter mode to be used during the next scan procedure. - * - * @param[in] mode New scan policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - */ - virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the initiator policy filter mode to be used during the next connection - * initiation. - * - * @param[in] mode New initiator policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - */ - virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the current initiator policy filter mode. - * - * @return The current scan policy filter mode. - */ - virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const - { - return INIT_POLICY_IGNORE_WHITELIST; - } - - /* connecting */ - - uint8_t getConnectionCount() { - return connectionCount; - } - /** * Initiate a connection to a peer. * @@ -1653,90 +1495,67 @@ public: } /** - * Initiate a disconnection procedure. + * Initiate a connection to a peer. * - * Once the disconnection procedure has completed a - * DisconnectionCallbackParams_t, the event is emitted to handlers that - * have been registered with onDisconnection(). + * Once the connection is established, a ConnectionCallbackParams_t event is + * emitted to handlers that have been registered with onConnection(). * - * @param[in] reason Reason of the disconnection transmitted to the peer. - * @param[in] connectionHandle Handle of the connection to end. + * @param[in] peerAddr MAC address of the peer. It must be in LSB format. + * @param[in] peerAddrType Address type of the peer. + * @param[in] connectionParams Connection parameters to use. + * @param[in] scanParams Scan parameters used to find the peer. * - * @return BLE_ERROR_NONE if the disconnection procedure successfully - * started. + * @deprecated BLEProtocol::AddressType_t is not able to to carry accurate + * meaning when privacy is in use. Please Uses the connect overload that + * accept a PeerAddressType_t as the peer address type. + * + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. */ - virtual ble_error_t disconnect( - Handle_t connectionHandle, - DisconnectionReason_t reason + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "This function won't work if privacy is enabled; You must use the overload " + "accepting PeerAddressType_t." + ) + virtual ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams ) { - (void)connectionHandle; - (void)reason; + /* Avoid compiler warnings about unused variables. */ + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams; + (void)scanParams; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } /** - * Returned the preferred connection parameters exposed in the GATT Generic - * Access Service. + * Initiate a connection to a peer. * - * @param[out] params Structure where the parameters are stored. + * @see connect() * - * @return BLE_ERROR_NONE if the parameters were successfully filled into - * @p params. + * @deprecated This funtion overloads Gap::connect( + * const BLEProtocol::Address_t peerAddr, + * BLEProtocol::AddressType_t peerAddrType, + * const ConnectionParams_t *connectionParams, + * const GapScanningParams *scanParams + * ) + * to maintain backward compatibility for changes from Gap::AddressType_t to + * BLEProtocol::AddressType_t. */ - virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) - { - (void)params; - - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the preferred connection parameters exposed in the GATT - * Generic Access Service. - * - * A connected peer may read the characteristic exposing these parameters - * and request an update of the connection parameters to accomodate the - * local device. - * - * @param[in] params Value of the preferred connection parameters. - * - * @return BLE_ERROR_NONE if the preferred connection params were set - * correctly. - */ - virtual ble_error_t setPreferredConnectionParams( - const ConnectionParams_t *params - ) { - (void)params; - - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Update connection parameters of an existing connection. - * - * In the central role, this initiates a Link Layer connection parameter - * update procedure. In the peripheral role, this sends the corresponding - * L2CAP request and waits for the central to perform the procedure. - * - * @param[in] handle Connection Handle. - * @param[in] params Pointer to desired connection parameters. - * - * @return BLE_ERROR_NONE if the connection parameters were updated correctly. - */ - virtual ble_error_t updateConnectionParams( - Handle_t handle, - const ConnectionParams_t *params - ) { - (void)handle; - (void)params; - - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + MBED_DEPRECATED("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead") + ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + DeprecatedAddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams + ); /** * Read the PHY used by the transmitter and the receiver on a connection. @@ -1804,45 +1623,221 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /* device configuration */ - /** - * Fetch the current address and its type. + * Initiate a disconnection procedure. * - * @param[out] typeP Type of the current address set. - * @param[out] address Value of the current address. + * Once the disconnection procedure has completed a + * DisconnectionCallbackParams_t, the event is emitted to handlers that + * have been registered with onDisconnection(). * - * @note If privacy is enabled the device address may be unavailable to - * application code. + * @param[in] reason Reason of the disconnection transmitted to the peer. + * @param[in] connectionHandle Handle of the connection to end. * - * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_NONE if the disconnection procedure successfully + * started. */ - virtual ble_error_t getAddress( - BLEProtocol::AddressType_t *typeP, - BLEProtocol::AddressBytes_t address + virtual ble_error_t disconnect( + Handle_t connectionHandle, DisconnectionReason_t reason ) { - (void)typeP; - (void)address; + /* avoid compiler warnings about unused variables */ + (void)connectionHandle; + (void)reason; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } /** - * Return the type of a random address. + * Initiate a disconnection procedure. * - * @param[in] address The random address to retrieve the type from. The - * address must be ordered in little endian. + * @deprecated This version of disconnect() doesn't take a connection handle. + * It works reliably only for stacks that are limited to a single connection. + * Use Gap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) + * instead. * - * @param[out] addressType Type of the address to fill. + * @param[in] reason The reason for disconnection; to be sent back to the peer. * - * @return BLE_ERROR_NONE in case of success or BLE_ERROR_INVALID_PARAM if - * the address in input was not identifiable as a random address. + * @return BLE_ERROR_NONE if disconnection was successful. */ - static ble_error_t getRandomAddressType( - const BLEProtocol::AddressBytes_t address, - RandomAddressType_t* addressType - ); + MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") + virtual ble_error_t disconnect(DisconnectionReason_t reason) { + /* Avoid compiler warnings about unused variables. */ + (void)reason; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /* advertising */ + + virtual uint8_t getMaxAdvertisingSetNumber() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 1; + } + + virtual uint8_t getMaxAdvertisingDataLength() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0x1F; + } + + virtual ble_error_t createAdvertisingSet(AdvHandle_t* handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t setAdvertisingParams( + AdvHandle_t handle, + const GapAdvertisingParameters ¶ms + ) { + (void) handle; + (void) params; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, + bool minimiseFragmentation = false) { + (void) handle; + (void) payload; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response) { + (void) handle; + (void) response; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t startAdvertising( + AdvHandle_t handle, + uint8_t maxEvents = 0, + uint32_t maxDuration = 0 + ) { + (void) maxEvents; + (void) maxDuration; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t stopAdvertising(AdvHandle_t handle) { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual bool isAdvertisingActive(AdvHandle_t handle) const { + if (handle != LEGACY_ADVERTISING_HANDLE) { + return false; + } + /* Requesting action from porter(s): override this API if this capability is supported. */ + return state.advertising; + } + + /* scanning */ + + virtual ble_error_t setScanParameters( + const GapScanParameters& params + ) { + use_non_deprecated_scan_api(); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + }; + + virtual ble_error_t startScan( + ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, + uint16_t duration = 0, + uint16_t period = 0 + ) { + use_non_deprecated_scan_api(); + return BLE_ERROR_NOT_IMPLEMENTED; + }; + +protected: + /* Override the following in the underlying adaptation layer to provide the + * functionality of scanning. */ + virtual void use_deprecated_scan_api() const { } + virtual void use_non_deprecated_scan_api() const { } + +public: + + /** + * Returned the preferred connection parameters exposed in the GATT Generic + * Access Service. + * + * @param[out] params Structure where the parameters are stored. + * + * @return BLE_ERROR_NONE if the parameters were successfully filled into + * @p params. + */ + virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) + { + /* Avoid compiler warnings about unused variables. */ + (void)params; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the value of the preferred connection parameters exposed in the GATT + * Generic Access Service. + * + * A connected peer may read the characteristic exposing these parameters + * and request an update of the connection parameters to accomodate the + * local device. + * + * @param[in] params Value of the preferred connection parameters. + * + * @return BLE_ERROR_NONE if the preferred connection params were set + * correctly. + */ + virtual ble_error_t setPreferredConnectionParams( + const ConnectionParams_t *params + ) { + /* Avoid compiler warnings about unused variables. */ + (void)params; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Update connection parameters of an existing connection. + * + * In the central role, this initiates a Link Layer connection parameter + * update procedure. In the peripheral role, this sends the corresponding + * L2CAP request and waits for the central to perform the procedure. + * + * @param[in] handle Connection Handle. + * @param[in] params Pointer to desired connection parameters. + * + * @return BLE_ERROR_NONE if the connection parameters were updated correctly. + */ + virtual ble_error_t updateConnectionParams( + Handle_t handle, + const ConnectionParams_t *params + ) { + /* avoid compiler warnings about unused variables */ + (void)handle; + (void)params; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } /** * Set the value of the device name characteristic in the Generic Access @@ -1854,9 +1849,11 @@ public: * @return BLE_ERROR_NONE if the device name was set correctly. */ virtual ble_error_t setDeviceName(const uint8_t *deviceName) { + /* Avoid compiler warnings about unused variables. */ (void)deviceName; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -1884,10 +1881,12 @@ public: */ virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) { + /* avoid compiler warnings about unused variables */ (void)deviceName; (void)lengthP; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -1898,11 +1897,13 @@ public: * * @return BLE_ERROR_NONE if the new appearance was set correctly. */ - virtual ble_error_t setAppearance(AdvertisingData::Appearance appearance) + virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) { + /* Avoid compiler warnings about unused variables. */ (void)appearance; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -1914,14 +1915,916 @@ public: * @return BLE_ERROR_NONE if the device-appearance was fetched correctly * from the underlying BLE stack. */ - virtual ble_error_t getAppearance(AdvertisingData::Appearance *appearanceP) + virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) { + /* Avoid compiler warnings about unused variables. */ (void)appearanceP; - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * Set the radio's transmit power. + * + * @param[in] txPower Radio's transmit power in dBm. + * + * @return BLE_ERROR_NONE if the new radio's transmit power was set + * correctly. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t setTxPower(int8_t txPower) + { + /* Avoid compiler warnings about unused variables. */ + (void)txPower; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Query the underlying stack for allowed Tx power values. + * + * @param[out] valueArrayPP Receive the immutable array of Tx values. + * @param[out] countP Receive the array's size. + */ + virtual void getPermittedTxPowerValues( + const int8_t **valueArrayPP, size_t *countP + ) { + /* Avoid compiler warnings about unused variables. */ + (void)valueArrayPP; + (void)countP; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + *countP = 0; + } + + /** + * Get the maximum size of the whitelist. + * + * @return Maximum size of the whitelist. + * + * @note If using Mbed OS, you can configure the size of the whitelist by + * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. + */ + virtual uint8_t getMaxWhitelistSize(void) const + { + return 0; + } + + /** + * Get the Link Layer to use the internal whitelist when scanning, + * advertising or initiating a connection depending on the filter policies. + * + * @param[in,out] whitelist Define the whitelist instance which is used + * to store the whitelist requested. In input, the caller provisions memory. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * copied into the supplied reference. + */ + virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const + { + (void) whitelist; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the value of the whitelist to be used during GAP procedures. + * + * @param[in] whitelist A reference to a whitelist containing the addresses + * to be copied to the internal whitelist. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * populated with the addresses in the given whitelist. + * + * @note The whitelist must not contain addresses of type @ref + * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This + * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might + * change its private address at any time, and it is not possible to resolve + * it. + * + * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), + * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. + */ + virtual ble_error_t setWhitelist(const Whitelist_t &whitelist) + { + (void) whitelist; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the advertising policy filter mode to be used during the next + * advertising procedure. + * + * @param[in] mode New advertising policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "This setting is now part of advertising paramters." + ) + virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the scan policy filter mode to be used during the next scan procedure. + * + * @param[in] mode New scan policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + */ + virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Set the initiator policy filter mode to be used during the next connection + * initiation. + * + * @param[in] mode New initiator policy filter mode. + * + * @return BLE_ERROR_NONE if the specified policy filter mode was set + * successfully. + */ + virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode) + { + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /** + * Get the current advertising policy filter mode. + * + * @return The current advertising policy filter mode. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "This setting is now part of advertising paramters." + ) + virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const + { + return ADV_POLICY_IGNORE_WHITELIST; + } + + /** + * Get the current scan policy filter mode. + * + * @return The current scan policy filter mode. + */ + virtual ScanningPolicyMode_t getScanningPolicyMode(void) const + { + return SCAN_POLICY_IGNORE_WHITELIST; + } + + /** + * Get the current initiator policy filter mode. + * + * @return The current scan policy filter mode. + */ + virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const + { + return INIT_POLICY_IGNORE_WHITELIST; + } + +protected: + /* Override the following in the underlying adaptation layer to provide the + functionality of scanning. */ + + /** + * Start scanning procedure in the underlying BLE stack. + * + * @param[in] scanningParams Parameters of the scan procedure. + * + * @return BLE_ERROR_NONE if the scan procedure was successfully started. + */ + virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) + { + (void)scanningParams; + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + /* + * APIs with nonvirtual implementations. + */ +public: + /** + * Get the current advertising and connection states of the device. + * + * @return The current GAP state of the device. + * + * @deprecated Deprecated since addition of extended advertising support. + * This is not meaningful when extended advertising is used, please use + * isAdvertisingActive() and getConnectionCount(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use isAdvertisingActive() and getConnectionCount()." + ) + GapState_t getState(void) const + { + return state; + } + + /** + * Set the advertising type to use during the advertising procedure. + * + * @param[in] advType New type of advertising to use. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType) + { + _advParams.setAdvertisingType(advType); + } + /** + * Set the advertising interval. + * + * @param[in] interval Advertising interval in units of milliseconds. + * Advertising is disabled if interval is 0. If interval is smaller than + * the minimum supported value, then the minimum supported value is used + * instead. This minimum value can be discovered using + * getMinAdvertisingInterval(). + * + * This field must be set to 0 if connectionMode is equal + * to ADV_CONNECTABLE_DIRECTED. + * + * @note Decreasing this value allows central devices to detect a + * peripheral faster, at the expense of the radio using more power + * due to the higher data transmit rate. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingInterval(uint16_t interval) + { + if (interval == 0) { + stopAdvertising(); + } else if (interval < getMinAdvertisingInterval()) { + interval = getMinAdvertisingInterval(); + } + _advParams.setInterval(interval); + } + + /** + * Set the advertising duration. + * + * A timeout event is genenerated once the advertising period expired. + * + * @param[in] timeout Advertising timeout (in seconds) between 0x1 and 0x3FFF. + * The special value 0 may be used to disable the advertising timeout. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingTimeout(uint16_t timeout) + { + _advParams.setTimeout(timeout); + } + + /** + * Start the advertising procedure. + * + * @return BLE_ERROR_NONE if the device started advertising successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t startAdvertising(void) + { + ble_error_t rc; + if ((rc = startAdvertising(_advParams)) == BLE_ERROR_NONE) { + state.advertising = 1; + } + return rc; + } + + /** + * Reset the value of the advertising payload advertised. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void clearAdvertisingPayload(void) + { + _advPayload.clear(); + setAdvertisingData(_advPayload, _scanResponse); + } + + /** + * Set gap flags in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addFlags(flags); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] flags The flags to be added. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload(uint8_t flags) + { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addFlags(flags)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; + } + + /** + * Set the appearance field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addAppearance(app); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] app The appearance to advertise. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) + { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addAppearance(app)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; + } + + /** + * Set the Tx Power field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addTxPower(power); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] power Transmit power in dBm used by the controller to advertise. + * + * @return BLE_ERROR_NONE if the data was successfully added to the + * advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) + { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addTxPower(power)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; + } + + /** + * Add a new field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.addData(type, data, len); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * @param[in] type Identity of the field being added. + * @param[in] data Buffer containing the value of the field. + * @param[in] len Length of the data buffer. + * + * @return BLE_ERROR_NONE if the advertisement payload was updated based on + * matching AD type; otherwise, an appropriate error. + * + * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the + * supplied value is appended to the values previously added to the payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len + ) { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; + } + + /** + * Update a particular field in the advertising payload. + * + * A call to this function is equivalent to: + * + * @code + * Gap ⪆ + * + * GapAdvertisingData payload = gap.getAdvertisingPayload(); + * payload.updateData(type, data, len); + * gap.setAdvertisingPayload(payload); + * @endcode + * + * + * @param[in] type Id of the field to update. + * @param[in] data data buffer containing the new value of the field. + * @param[in] len Length of the data buffer. + * + * @note If advertisements are enabled, then the update takes effect + * immediately. + * + * @return BLE_ERROR_NONE if the advertisement payload was updated based on + * matching AD type; otherwise, an appropriate error. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t updateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len + ) { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; + } + + /** + * Set the value of the payload advertised. + * + * @param[in] payload A reference to a user constructed advertisement + * payload to set. + * + * @return BLE_ERROR_NONE if the advertisement payload was successfully + * set. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) + { + ble_error_t rc = setAdvertisingData(payload, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = payload; + } + + return rc; + } + + /** + * Get a reference to the current advertising payload. + * + * @return A reference to the current advertising payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + const GapAdvertisingData &getAdvertisingPayload(void) const + { + return _advPayload; + } + + /** + * Add a new field in the advertising payload. + * + * @param[in] type AD type identifier. + * @param[in] data buffer containing AD data. + * @param[in] len Length of the data buffer. + * + * @return BLE_ERROR_NONE if the data was successfully added to the scan + * response payload. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t accumulateScanResponse( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len + ) { + GapAdvertisingData scanResponseCopy = _scanResponse; + ble_error_t rc; + if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(_advPayload, scanResponseCopy); + if (rc == BLE_ERROR_NONE) { + _scanResponse = scanResponseCopy; + } + + return rc; + } + + /** + * Reset the content of the scan response. + * + * @note This should be followed by a call to Gap::setAdvertisingPayload() + * or Gap::startAdvertising() before the update takes effect. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void clearScanResponse(void) { + _scanResponse.clear(); + setAdvertisingData(_advPayload, _scanResponse); + } + + /** + * Set the parameters used during a scan procedure. + * + * @param[in] interval in ms between the start of two consecutive scan windows. + * That value is greater or equal to the scan window value. The + * maximum allowed value is 10.24ms. + * + * @param[in] window Period in ms during which the scanner listens to + * advertising channels. That value is in the range 2.5ms to 10.24s. + * + * @param[in] timeout Duration in seconds of the scan procedure if any. The + * special value 0 disable specific duration of the scan procedure. + * + * @param[in] activeScanning If set to true, then the scanner sends scan + * requests to a scannable or connectable advertiser. If set to false, then the + * scanner does not send any request during the scan procedure. + * + * @return BLE_ERROR_NONE if the scan parameters were correctly set. + * + * @note The scanning window divided by the interval determines the duty + * cycle for scanning. For example, if the interval is 100ms and the window + * is 10ms, then the controller scans for 10 percent of the time. + * + * @note If the interval and the window are set to the same value, then the + * device scans continuously during the scan procedure. The scanning + * frequency changes at every interval. + * + * @note Once the scanning parameters have been configured, scanning can be + * enabled by using startScan(). + * + * @note The scan interval and window are recommendations to the BLE stack. + */ + ble_error_t setScanParams( + uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, + uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, + uint16_t timeout = 0, + bool activeScanning = false + ) { + ble_error_t rc; + if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && + ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && + ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { + _scanningParams.setActiveScanning(activeScanning); + return BLE_ERROR_NONE; + } + + return rc; + } + + /** + * Set the parameters used during a scan procedure. + * + * @param[in] scanningParams Parameter struct containing the interval, period, + * timeout and active scanning toggle. + * + * @return BLE_ERROR_NONE if the scan parameters were correctly set. + * + * @note All restrictions from setScanParams(uint16_t, uint16_t, uint16_t, bool) apply. + */ + ble_error_t setScanParams(const GapScanningParams& scanningParams) { + return setScanParams( + scanningParams.getInterval(), + scanningParams.getWindow(), + scanningParams.getTimeout(), + scanningParams.getActiveScanning() + ); + } + + /** + * Set the interval parameter used during scanning procedures. + * + * @param[in] interval Interval in ms between the start of two consecutive + * scan windows. That value is greater or equal to the scan window value. + * The maximum allowed value is 10.24ms. + * + * @return BLE_ERROR_NONE if the scan interval was correctly set. + */ + ble_error_t setScanInterval(uint16_t interval) + { + return _scanningParams.setInterval(interval); + } + + /** + * Set the window parameter used during scanning procedures. + * + * @param[in] window Period in ms during which the scanner listens to + * advertising channels. That value is in the range 2.5ms to 10.24s. + * + * @return BLE_ERROR_NONE if the scan window was correctly set. + * + * @note If scanning is already active, the updated value of scanWindow + * is propagated to the underlying BLE stack. + */ + ble_error_t setScanWindow(uint16_t window) + { + ble_error_t rc; + if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) { + return rc; + } + + /* If scanning is already active, propagate the new setting to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; + } + + /** + * Set the timeout parameter used during scanning procedures. + * + * @param[in] timeout Duration in seconds of the scan procedure if any. The + * special value 0 disables specific duration of the scan procedure. + * + * @return BLE_ERROR_NONE if the scan timeout was correctly set. + * + * @note If scanning is already active, the updated value of scanTimeout + * is propagated to the underlying BLE stack. + */ + ble_error_t setScanTimeout(uint16_t timeout) + { + ble_error_t rc; + if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) { + return rc; + } + + /* If scanning is already active, propagate the new settings to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; + } + + /** + * Enable or disable active scanning. + * + * @param[in] activeScanning If set to true, then the scanner sends scan + * requests to a scannable or connectable advertiser. If set to false then the + * scanner does not send any request during the scan procedure. + * + * @return BLE_ERROR_NONE if active scanning was successfully set. + * + * @note If scanning is already in progress, then active scanning is + * enabled for the underlying BLE stack. + */ + ble_error_t setActiveScanning(bool activeScanning) + { + _scanningParams.setActiveScanning(activeScanning); + + /* If scanning is already active, propagate the new settings to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; + } + + /** + * Start the scanning procedure. + * + * Packets received during the scan procedure are forwarded to the + * scan packet handler passed as argument to this function. + * + * @param[in] callback Advertisement packet event handler. Upon reception + * of an advertising packet, the packet is forwarded to @p callback. + * + * @return BLE_ERROR_NONE if the device successfully started the scan + * procedure. + * + * @note The parameters used by the procedure are defined by setScanParams(). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + ble_error_t startScan( + void (*callback)(const AdvertisementCallbackParams_t *params) + ) { + ble_error_t err = BLE_ERROR_NONE; + if (callback) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(callback); + } + } + + return err; + } + + /** + * Start the scanning procedure. + * + * Packets received during the scan procedure are forwarded to the + * scan packet handler passed as argument to this function. + * + * @param[in] object Instance used to invoke @p callbackMember. + * + * @param[in] callbackMember Advertisement packet event handler. Upon + * reception of an advertising packet, the packet is forwarded to @p + * callback invoked from @p object. + * + * @return BLE_ERROR_NONE if the device successfully started the scan + * procedure. + * + * @note The parameters used by the procedure are defined by setScanParams(). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ); + template + ble_error_t startScan( + T *object, + void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) + ) { + ble_error_t err = BLE_ERROR_NONE; + if (object && callbackMember) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(object, callbackMember); + } + } + + return err; + } + /** * Enable radio-notification events. * @@ -1937,14 +2840,13 @@ public: * * @return BLE_ERROR_NONE on successful initialization, otherwise an error code. */ - virtual ble_error_t initRadioNotification() + virtual ble_error_t initRadioNotification(void) { - /* Requesting action from porter(s): override this API if this capability is supported. */ + /* Requesting action from porter(s): override this API if this capability + is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /* privacy */ - /** * Enable or disable privacy mode of the local device. * @@ -2036,7 +2938,106 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /* event handlers */ +private: + /** + * Set the advertising data and scan response in the vendor subsytem. + * + * @param[in] advData Advertising data to set. + * @param[in] scanResponse Scan response to set. + * + * @return BLE_ERROR_NONE if the advertising data was set successfully. + * + * @note Must be implemented in vendor port. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t setAdvertisingData( + const GapAdvertisingData &advData, + const GapAdvertisingData &scanResponse + ) = 0; + + /** + * Start the advertising procedure. + * + * @param[in] params Advertising parameters to use. + * + * @return BLE_ERROR_NONE if the advertising procedure successfully + * started. + * + * @note Must be implemented in vendor port. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) = 0; + +public: + /** + * Get the current advertising parameters. + * + * @return A reference to the current advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + GapAdvertisingParams &getAdvertisingParams(void) + { + return _advParams; + } + + /** + * Const alternative to Gap::getAdvertisingParams(). + * + * @return A const reference to the current advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + const GapAdvertisingParams &getAdvertisingParams(void) const + { + return _advParams; + } + + /** + * Set the advertising parameters. + * + * @param[in] newParams The new advertising parameters. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use createAdvertisingSet(). + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use createAdvertisingSet() and use the resulting object's interface." + ) + void setAdvertisingParams(const GapAdvertisingParams &newParams) + { + _advParams = newParams; + } + + /* Event handlers. */ public: /** @@ -2260,17 +3261,16 @@ public: shutdownCallChain.clear(); /* Clear Gap state */ - connectionCount = 0; + state.advertising = 0; + state.connected = 0; + connectionCount = 0; /* Clear scanning state */ scanningActive = false; - state.advertising = false; - state.connected = false; /* Clear advertising and scanning data */ - legacyAdvertisingReset(); - GapScanningParams default_scan_params; - _scanningParams = default_scan_params; + _advPayload.clear(); + _scanResponse.clear(); /* Clear callbacks */ timeoutCallbackChain.clear(); @@ -2288,19 +3288,21 @@ protected: * Construct a Gap instance. */ Gap() : - connectionCount(0), - scanningActive(false), + _advParams(), + _advPayload(), _scanningParams(), - _advParams(NULL), - _advPayload(NULL), - _scanResponse(NULL), + _scanResponse(), + connectionCount(0), state(), + scanningActive(false), timeoutCallbackChain(), radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), disconnectionCallChain(), _eventHandler(NULL) { + _advPayload.clear(); + _scanResponse.clear(); } /* Entry points for the underlying stack to report events back to the user. */ @@ -2335,6 +3337,44 @@ public: const uint8_t *localResolvableAddr = NULL ); + /** + * Notify all registered connection event handlers of a connection event. + * + * @attention This function is meant to be called from the BLE stack specific + * implementation when a connection event occurs. + * + * @param[in] handle Handle of the new connection. + * @param[in] role Role of this BLE device in the connection. + * @param[in] peerAddrType Address type of the connected peer. + * @param[in] peerAddr Address of the connected peer. + * @param[in] ownAddrType Address type this device uses for this + * connection. + * @param[in] ownAddr Address this device uses for this connection. + * @param[in] connectionParams Parameters of the connection. + * @param[in] peerResolvableAddr Resolvable address used by the peer. + * @param[in] localResolvableAddr resolvable address used by the local device. + * + * @deprecated The type BLEProtocol::AddressType_t is not suitable when + * privacy is enabled. Use the overload that accepts a PeerAddressType_t + * instead. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." + ) + void processConnectionEvent( + Handle_t handle, + Role_t role, + BLEProtocol::AddressType_t peerAddrType, + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t ownAddrType, + const BLEProtocol::AddressBytes_t ownAddr, + const ConnectionParams_t *connectionParams, + const uint8_t *peerResolvableAddr = NULL, + const uint8_t *localResolvableAddr = NULL + ); + /** * Notify all registered disconnection event handlers of a disconnection event. * @@ -2348,7 +3388,9 @@ public: { /* Update Gap state */ --connectionCount; - state.connected = false; + if (!connectionCount) { + state.connected = 0; + } DisconnectionCallbackParams_t callbackParams(handle, reason); disconnectionCallChain.call(&callbackParams); @@ -2375,12 +3417,47 @@ public: const BLEProtocol::AddressBytes_t peerAddr, int8_t rssi, bool isScanResponse, - ble::advertising_type_t type, + GapAdvertisingParams::AdvertisingType_t type, uint8_t advertisingDataLen, const uint8_t *advertisingData, PeerAddressType_t addressType ); + /** + * Forward a received advertising packet to all registered event handlers + * listening for scanned packet events. + * + * @attention This function is meant to be called from the BLE stack specific + * implementation when a disconnection event occurs. + * + * @param[in] peerAddr Address of the peer that has emitted the packet. + * @param[in] rssi Value of the RSSI measured for the received packet. + * @param[in] isScanResponse If true, then the packet is a response to a scan + * request. + * @param[in] type Advertising type of the packet. + * @param[in] advertisingDataLen Length of the advertisement data received. + * @param[in] advertisingData Pointer to the advertisement packet's data. + * @param[in] addressType Type of the address of the peer that has emitted the packet. + * + * @deprecated The type BLEProtocol::AddressType_t is not suitable when + * privacy is enabled. Use the overload that accepts a PeerAddressType_t + * instead. + */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." + ) + void processAdvertisementReport( + const BLEProtocol::AddressBytes_t peerAddr, + int8_t rssi, + bool isScanResponse, + GapAdvertisingParams::AdvertisingType_t type, + uint8_t advertisingDataLen, + const uint8_t *advertisingData, + BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC + ); + /** * Notify the occurrence of a timeout event to all registered timeout events * handler. @@ -2394,7 +3471,7 @@ public: { if (source == TIMEOUT_SRC_ADVERTISING) { /* Update gap state if the source is an advertising timeout */ - state.advertising = false; + state.advertising = 0; } if (timeoutCallbackChain) { timeoutCallbackChain(source); @@ -2402,20 +3479,41 @@ public: } protected: + /** + * Current advertising parameters. + */ + GapAdvertisingParams _advParams; + + /** + * Current advertising data. + */ + GapAdvertisingData _advPayload; + + /** + * Current scanning parameters. + */ + GapScanningParams _scanningParams; + + /** + * Current scan response. + */ + GapAdvertisingData _scanResponse; /** * Number of open connections. */ uint8_t connectionCount; + /** + * Current GAP state. + */ + GapState_t state; + /** * Active scanning flag. */ bool scanningActive; - /** Current scanning parameters. */ - GapScanningParams _scanningParams; - protected: /** * Callchain containing all registered callback handlers for timeout @@ -2462,6 +3560,7 @@ private: /* Disallow copy and assignment. */ Gap(const Gap &); Gap& operator=(const Gap &); +#if 0 /* ----------------------- anything beyond this line is deprecated ------------------------- */ @@ -2502,970 +3601,8 @@ protected: delete _scanResponse; _scanResponse = NULL; } +#endif - /** Current advertising parameters. */ - GapAdvertisingParams* _advParams; - - /** Current advertising data. */ - GapAdvertisingData* _advPayload; - - /** Current scan response. */ - GapAdvertisingData* _scanResponse; - - /* deprecated types */ - -public: - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::advertising_policy_mode_t ADV_POLICY_IGNORE_WHITELIST = ble::ADV_POLICY_IGNORE_WHITELIST; - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_SCAN_REQS = ble::ADV_POLICY_FILTER_SCAN_REQS; - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_CONN_REQS = ble::ADV_POLICY_FILTER_CONN_REQS; - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::advertising_policy_mode_t ADV_POLICY_FILTER_ALL_REQS = ble::ADV_POLICY_FILTER_ALL_REQS; - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::scanning_policy_mode_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; - /** @deprecated Enum have been moved to BLETypes.h */ - static const ble::scanning_policy_mode_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; - - /** - * Description of the states of the device. - * @deprecated This is not meaningful when extended advertising is used, please use - * isAdvertisingActive() and getConnectionCount(). - */ - struct GapState_t { - /** - * If set, the device is currently advertising. - */ - unsigned advertising : 1; - - /** - * If set, the device is connected to at least one other peer. - */ - unsigned connected : 1; - }; - - /* These have been relocated to the class BLEProtocol. */ -public: - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. - */ - typedef BLEProtocol::AddressType_t AddressType_t; - - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. - */ - typedef BLEProtocol::AddressType_t addr_type_t; - - /** - * Address-type for BLEProtocol addresses. - * - * @deprecated Use BLEProtocol::AddressType_t instead. The following - * constants have been left in their deprecated state to transparently - * support existing applications that may have used Gap::ADDR_TYPE_*. - */ - enum DeprecatedAddressType_t { - ADDR_TYPE_PUBLIC = BLEProtocol::AddressType::PUBLIC, - ADDR_TYPE_RANDOM_STATIC = BLEProtocol::AddressType::RANDOM_STATIC, - ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE, - ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE - }; - - /** - * Length (in octets) of the BLE MAC address. - */ - static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN; - - /** - * 48-bit address, LSB format. - * - * @deprecated Use BLEProtocol::AddressBytes_t instead. - */ - typedef BLEProtocol::AddressBytes_t Address_t; - - /** - * 48-bit address, LSB format. - * - * @deprecated Use BLEProtocol::AddressBytes_t instead. - */ - typedef BLEProtocol::AddressBytes_t address_t; - - /* deprecated data */ - -protected: - GapState_t state; - - /* deprecated functions */ - -public: - /** - * Start the scanning procedure. - * - * Packets received during the scan procedure are forwarded to the - * scan packet handler passed as argument to this function. - * - * @param[in] callback Advertisement packet event handler. Upon reception - * of an advertising packet, the packet is forwarded to @p callback. - * - * @return BLE_ERROR_NONE if the device successfully started the scan - * procedure. - * - * @note The parameters used by the procedure are defined by setScanParams(). - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t startScan( - void (*callback)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (callback) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(callback); - } - } - - return err; - } - - /** - * Start the scanning procedure. - * - * Packets received during the scan procedure are forwarded to the - * scan packet handler passed as argument to this function. - * - * @param[in] object Instance used to invoke @p callbackMember. - * - * @param[in] callbackMember Advertisement packet event handler. Upon - * reception of an advertising packet, the packet is forwarded to @p - * callback invoked from @p object. - * - * @return BLE_ERROR_NONE if the device successfully started the scan - * procedure. - * - * @note The parameters used by the procedure are defined by setScanParams(). - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ); - template - ble_error_t startScan( - T *object, - void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (object && callbackMember) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(object, callbackMember); - } - } - - return err; - } - - /** - * Set the device MAC address and type. - * - * The address set is used in subsequent GAP operations: scanning, - * advertising and connection initiation. - * - * @param[in] type Type of the address to set. - * @param[in] address Value of the address to set. It is ordered in - * little endian. This parameter is not considered if the address type - * is RANDOM_PRIVATE_RESOLVABLE or RANDOM_PRIVATE_NON_RESOLVABLE. For those - * types of address, the BLE API itself generates the address. - * - * @note Some implementation may refuse to set a new PUBLIC address. - * @note Random static address set does not change. - * - * @deprecated Starting with mbed-os-5.9.0 this function is deprecated and - * address management is delegated to implementation. Implementations may or - * may not continue to support this function. Compliance with the Bluetooth - * specification and unification of behaviour between implementations are - * the key reasons behind this change: - * - Many implementations do not allow changing of the public address. - * Therefore programs relying on this function are not portable across BLE - * implementations. - * - The Bluetooth specification forbid replacement of the random static - * address; this address can be set once and only once: at startup. - * Depending on the underlying implementation the random address may or - * may not have been set automatically at startup; therefore update of the - * Random Static address after ble initialisation may be a fault. As a - * result calls to this function were not portable. - * Furthermore replacement of the random static address silently - * invalidates the bond stored in the secure database. - - * @return BLE_ERROR_NONE on success. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "Non portable API, use enablePrivacy to enable use of private addresses" - ) - virtual ble_error_t setAddress( - BLEProtocol::AddressType_t type, - const BLEProtocol::AddressBytes_t address - ) { - (void)type; - (void)address; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a connection to a peer. - * - * Once the connection is established, a ConnectionCallbackParams_t event is - * emitted to handlers that have been registered with onConnection(). - * - * @param[in] peerAddr MAC address of the peer. It must be in LSB format. - * @param[in] peerAddrType Address type of the peer. - * @param[in] connectionParams Connection parameters to use. - * @param[in] scanParams Scan parameters used to find the peer. - * - * @deprecated BLEProtocol::AddressType_t is not able to to carry accurate - * meaning when privacy is in use. Please Uses the connect overload that - * accept a PeerAddressType_t as the peer address type. - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallChain (if set) is invoked upon - * a connection event. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "This function won't work if privacy is enabled; You must use the overload " - "accepting PeerAddressType_t." - ) - virtual ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t peerAddrType, - const ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams - ) { - (void)peerAddr; - (void)peerAddrType; - (void)connectionParams; - (void)scanParams; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Initiate a connection to a peer. - * - * @see connect() - * - * @deprecated This funtion overloads Gap::connect( - * const BLEProtocol::Address_t peerAddr, - * BLEProtocol::AddressType_t peerAddrType, - * const ConnectionParams_t *connectionParams, - * const GapScanningParams *scanParams - * ) - * to maintain backward compatibility for changes from Gap::AddressType_t to - * BLEProtocol::AddressType_t. - */ - MBED_DEPRECATED("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead") - ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - DeprecatedAddressType_t peerAddrType, - const ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams - ); - - /** - * Initiate a disconnection procedure. - * - * @deprecated This version of disconnect() doesn't take a connection handle. - * It works reliably only for stacks that are limited to a single connection. - * Use Gap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) - * instead. - * - * @param[in] reason The reason for disconnection; to be sent back to the peer. - * - * @return BLE_ERROR_NONE if disconnection was successful. - */ - MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") - virtual ble_error_t disconnect(DisconnectionReason_t reason) { - (void)reason; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Notify all registered connection event handlers of a connection event. - * - * @attention This function is meant to be called from the BLE stack specific - * implementation when a connection event occurs. - * - * @param[in] handle Handle of the new connection. - * @param[in] role Role of this BLE device in the connection. - * @param[in] peerAddrType Address type of the connected peer. - * @param[in] peerAddr Address of the connected peer. - * @param[in] ownAddrType Address type this device uses for this - * connection. - * @param[in] ownAddr Address this device uses for this connection. - * @param[in] connectionParams Parameters of the connection. - * @param[in] peerResolvableAddr Resolvable address used by the peer. - * @param[in] localResolvableAddr resolvable address used by the local device. - * - * @deprecated The type BLEProtocol::AddressType_t is not suitable when - * privacy is enabled. Use the overload that accepts a PeerAddressType_t - * instead. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." - ) - void processConnectionEvent( - Handle_t handle, - Role_t role, - BLEProtocol::AddressType_t peerAddrType, - const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t ownAddrType, - const BLEProtocol::AddressBytes_t ownAddr, - const ConnectionParams_t *connectionParams, - const uint8_t *peerResolvableAddr = NULL, - const uint8_t *localResolvableAddr = NULL - ); - - /** - * Forward a received advertising packet to all registered event handlers - * listening for scanned packet events. - * - * @attention This function is meant to be called from the BLE stack specific - * implementation when a disconnection event occurs. - * - * @param[in] peerAddr Address of the peer that has emitted the packet. - * @param[in] rssi Value of the RSSI measured for the received packet. - * @param[in] isScanResponse If true, then the packet is a response to a scan - * request. - * @param[in] type Advertising type of the packet. - * @param[in] advertisingDataLen Length of the advertisement data received. - * @param[in] advertisingData Pointer to the advertisement packet's data. - * @param[in] addressType Type of the address of the peer that has emitted the packet. - * - * @deprecated The type BLEProtocol::AddressType_t is not suitable when - * privacy is enabled. Use the overload that accepts a PeerAddressType_t - * instead. - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." - ) - void processAdvertisementReport( - const BLEProtocol::AddressBytes_t peerAddr, - int8_t rssi, - bool isScanResponse, - ble::advertising_type_t type, - uint8_t advertisingDataLen, - const uint8_t *advertisingData, - BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC - ); - - /** - * Stop the ongoing advertising procedure. - * - * @note The current advertising parameters remain in effect. - * - * @retval BLE_ERROR_NONE if the advertising procedure has been successfully - * stopped. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - virtual ble_error_t stopAdvertising(void) - { - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the advertising policy filter mode to be used during the next - * advertising procedure. - * - * @param[in] mode New advertising policy filter mode. - * - * @return BLE_ERROR_NONE if the specified policy filter mode was set - * successfully. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "This setting is now part of advertising paramters." - ) - virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the current advertising policy filter mode. - * - * @return The current advertising policy filter mode. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "This setting is now part of advertising paramters." - ) - virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const - { - return ble::ADV_POLICY_IGNORE_WHITELIST; - } - - /** - * Get the current advertising and connection states of the device. - * - * @return The current GAP state of the device. - * - * @deprecated Deprecated since addition of extended advertising support. - * This is not meaningful when extended advertising is used, please use - * isAdvertisingActive() and getConnectionCount(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use isAdvertisingActive() and getConnectionCount()." - ) - GapState_t getState(void) const - { - return state; - } - - /** - * Get the current advertising parameters. - * - * @return A reference to the current advertising parameters. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - GapAdvertisingParams &getAdvertisingParams(void) - { - return getLegacyAdvertisingParams(); - } - - /** - * Const alternative to Gap::getAdvertisingParams(). - * - * @return A const reference to the current advertising parameters. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - const GapAdvertisingParams &getAdvertisingParams(void) const - { - Gap* self = const_cast(this); - return self->getLegacyAdvertisingParams(); - } - - /** - * Set the advertising parameters. - * - * @param[in] newParams The new advertising parameters. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void setAdvertisingParams(const GapAdvertisingParams &newParams) - { - getLegacyAdvertisingParams() = newParams; - } - - /** - * Set the advertising type to use during the advertising procedure. - * - * @param[in] advType New type of advertising to use. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void setAdvertisingType(ble::advertising_type_t advType) - { - getLegacyAdvertisingParams().setAdvertisingType(advType); - } - - /** - * Set the advertising interval. - * - * @param[in] interval Advertising interval in units of milliseconds. - * Advertising is disabled if interval is 0. If interval is smaller than - * the minimum supported value, then the minimum supported value is used - * instead. This minimum value can be discovered using - * getMinAdvertisingInterval(). - * - * This field must be set to 0 if connectionMode is equal - * to ADV_CONNECTABLE_DIRECTED. - * - * @note Decreasing this value allows central devices to detect a - * peripheral faster, at the expense of the radio using more power - * due to the higher data transmit rate. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void setAdvertisingInterval(uint16_t interval) - { - if (interval == 0) { - stopAdvertising(LEGACY_ADVERTISING_HANDLE); - } else if (interval < getMinAdvertisingInterval()) { - interval = getMinAdvertisingInterval(); - } - getLegacyAdvertisingParams().setInterval(interval); - } - - /** - * Set the advertising duration. - * - * A timeout event is genenerated once the advertising period expired. - * - * @param[in] timeout Advertising timeout (in seconds) between 0x1 and 0x3FFF. - * The special value 0 may be used to disable the advertising timeout. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void setAdvertisingTimeout(uint16_t timeout) - { - getLegacyAdvertisingParams().setTimeout(timeout); - } - - /** - * Start the advertising procedure. - * - * @return BLE_ERROR_NONE if the device started advertising successfully. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t startAdvertising(void) - { - ble_error_t status = startAdvertising(LEGACY_ADVERTISING_HANDLE); - if (status == BLE_ERROR_NONE) { - state.advertising = true; - } - return status; - } - - /** - * Reset the value of the advertising payload advertised. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void clearAdvertisingPayload(void) - { - getLegacyAdvertisingPayload().clear(); - } - - /** - * Set gap flags in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addFlags(flags); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] flags The flags to be added. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t accumulateAdvertisingPayload(uint8_t flags) - { - return getLegacyAdvertisingPayload().addFlags(flags); - } - - /** - * Set the appearance field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addAppearance(app); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] app The appearance to advertise. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) - { - return getLegacyAdvertisingPayload().addAppearance(app); - } - - /** - * Set the Tx Power field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addTxPower(power); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] power Transmit power in dBm used by the controller to advertise. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) - { - return getLegacyAdvertisingPayload().addTxPower(power); - } - - /** - * Add a new field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.addData(type, data, len); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * @param[in] type Identity of the field being added. - * @param[in] data Buffer containing the value of the field. - * @param[in] len Length of the data buffer. - * - * @return BLE_ERROR_NONE if the advertisement payload was updated based on - * matching AD type; otherwise, an appropriate error. - * - * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the - * supplied value is appended to the values previously added to the payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t accumulateAdvertisingPayload( - GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - return getLegacyAdvertisingPayload().addData(type, data, len); - } - - /** - * Update a particular field in the advertising payload. - * - * A call to this function is equivalent to: - * - * @code - * Gap ⪆ - * - * GapAdvertisingData payload = gap.getAdvertisingPayload(); - * payload.updateData(type, data, len); - * gap.setAdvertisingPayload(payload); - * @endcode - * - * - * @param[in] type Id of the field to update. - * @param[in] data data buffer containing the new value of the field. - * @param[in] len Length of the data buffer. - * - * @note If advertisements are enabled, then the update takes effect - * immediately. - * - * @return BLE_ERROR_NONE if the advertisement payload was updated based on - * matching AD type; otherwise, an appropriate error. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t updateAdvertisingPayload( - GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - return getLegacyAdvertisingPayload().updateData(type, data, len); - } - - /** - * Set the value of the payload advertised. - * - * @param[in] payload A reference to a user constructed advertisement - * payload to set. - * - * @return BLE_ERROR_NONE if the advertisement payload was successfully - * set. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) - { - getLegacyAdvertisingPayload() = payload; - return BLE_ERROR_NONE; - } - - /** - * Get a reference to the current advertising payload. - * - * @return A reference to the current advertising payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - const GapAdvertisingData &getAdvertisingPayload(void) const - { - Gap* self = const_cast(this); - return self->getLegacyAdvertisingPayload(); - } - - /** - * Add a new field in the advertising payload. - * - * @param[in] type AD type identifier. - * @param[in] data buffer containing AD data. - * @param[in] len Length of the data buffer. - * - * @return BLE_ERROR_NONE if the data was successfully added to the scan - * response payload. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - ble_error_t accumulateScanResponse( - GapAdvertisingData::DataType type, - const uint8_t *data, - uint8_t len - ) { - return getLegacyAdvertisingScanResponse().addData(type, data, len); - } - - /** - * Reset the content of the scan response. - * - * @note This should be followed by a call to Gap::setAdvertisingPayload() - * or Gap::startAdvertising() before the update takes effect. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - void clearScanResponse(void) { - getLegacyAdvertisingScanResponse().clear(); - } - - /** - * Set the radio's transmit power. - * - * @param[in] txPower Radio's transmit power in dBm. - * - * @return BLE_ERROR_NONE if the new radio's transmit power was set - * correctly. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - virtual ble_error_t setTxPower(int8_t txPower) - { - (void)txPower; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - -private: - /** - * Set the advertising data and scan response in the vendor subsytem. - * - * @param[in] advData Advertising data to set. - * @param[in] scanResponse Scan response to set. - * - * @return BLE_ERROR_NONE if the advertising data was set successfully. - * - * @note Must be implemented in vendor port. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - virtual ble_error_t setAdvertisingData( - const GapAdvertisingData &advData, - const GapAdvertisingData &scanResponse - ) { - (void) advData; - (void) scanResponse; - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - - /** - * Start the advertising procedure. - * - * @param[in] params Advertising parameters to use. - * - * @return BLE_ERROR_NONE if the advertising procedure successfully - * started. - * - * @note Must be implemented in vendor port. - * - * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). - */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ) - virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) { - (void) params; - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } }; /** diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index ea8dfa01f7..9cd6ad6729 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -17,19 +17,6 @@ #ifndef MBED_GAP_ADVERTISING_PARAMS_H__ #define MBED_GAP_ADVERTISING_PARAMS_H__ -#include "BLETypes.h" -#include "BLEProtocol.h" -#include "blecommon.h" -#include "SafeEnum.h" - -/* TODO: std::clamp */ -#define CLAMP(value, min, max) \ - if (value > max) { \ - value = max; \ - } else if (value < min) { \ - value = min; \ - } - /** * @addtogroup ble * @{ @@ -40,8 +27,8 @@ /** * Parameters defining the advertising process. * - * Advertising parameters for legacy advertising are a triplet of three value: - * - The Advertising mode modelled after ble::advertising_type_t. It defines + * Advertising parameters are a triplet of three value: + * - The Advertising mode modeled after AdvertisingType_t. It defines * if the device is connectable and scannable. This value can be set at * construction time, updated with setAdvertisingType() and queried by * getAdvertisingType(). @@ -82,40 +69,48 @@ public: static const unsigned GAP_ADV_PARAMS_TIMEOUT_MAX = 0x3FFF; /** - * Alias for GapAdvertisingParams::ble::advertising_type_t. + * Encapsulates the peripheral advertising modes. + * + * It determine how the device appears to other scanner and peripheral + * devices in the scanning range. + */ + enum AdvertisingType_t { + /** + * Device is connectable, scannable and doesn't expect connection from a + * specific peer. + * + * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. + */ + ADV_CONNECTABLE_UNDIRECTED, + + /** + * Device is connectable and expects connection from a specific peer. + * + * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. + */ + ADV_CONNECTABLE_DIRECTED, + + /** + * Device is scannable but not connectable. + * + * @see Vol 6, Part B, Section 2.3.1.4. + */ + ADV_SCANNABLE_UNDIRECTED, + + /** + * Device is not connectable and not scannable. + * + * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. + */ + ADV_NON_CONNECTABLE_UNDIRECTED + }; + + /** + * Alias for GapAdvertisingParams::AdvertisingType_t. * * @deprecated Future releases will drop this type alias. */ - typedef ble::advertising_type_t AdvertisingType; - - typedef ble::advertising_type_t AdvertisingType_t; - - static const ble::advertising_type_t ADV_CONNECTABLE_UNDIRECTED = ble::ADV_CONNECTABLE_UNDIRECTED; - static const ble::advertising_type_t ADV_CONNECTABLE_DIRECTED = ble::ADV_CONNECTABLE_DIRECTED; - static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; - static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; - - struct own_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address. */ - RANDOM, /**< Random Device Address. */ - RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use the public address. */ - RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use previously set random address. */ - }; - own_address_type_t(type value) : ble::SafeEnum(value) { } - }; - - struct peer_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ - RANDOM /**< Random Device Address or Random (static) Identity Address. */ - }; - peer_address_type_t(type value) : ble::SafeEnum(value) { } - }; + typedef enum AdvertisingType_t AdvertisingType; public: /** @@ -130,42 +125,34 @@ public: * @note If value in input are out of range, they will be normalized. */ GapAdvertisingParams( - ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, + AdvertisingType_t advType = ADV_CONNECTABLE_UNDIRECTED, uint16_t interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, uint16_t timeout = 0 ) : _advType(advType), _interval(interval), - _maxInterval(interval), - _timeout(timeout), - _peerAddressType(peer_address_type_t::PUBLIC), - _ownAddressType(own_address_type_t::PUBLIC), - _policy(ble::ADV_POLICY_IGNORE_WHITELIST), - _primaryPhy(ble::phy_t::LE_1M), - _secondaryPhy(ble::phy_t::LE_1M), - _peerAddress(), - _txPower(127), - _maxSkip(0), - _channel37(1), - _channel38(1), - _channel39(1), - _anonymous(0), - _notifyOnScan(0), - _legacyPDU(1), - _includeHeaderTxPower(0) + _timeout(timeout) { /* Interval checks. */ - if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { + if (_advType == ADV_CONNECTABLE_DIRECTED) { /* Interval must be 0 in directed connectable mode. */ _interval = 0; - _maxInterval = 0; - } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { + } else if (_advType == ADV_NON_CONNECTABLE_UNDIRECTED) { /* Min interval is slightly larger than in other modes. */ - CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); - CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) { + _interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; + } + if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) { + _interval = GAP_ADV_PARAMS_INTERVAL_MAX; + } } else { - CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); - CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + /* Stay within interval limits. */ + if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN) { + _interval = GAP_ADV_PARAMS_INTERVAL_MIN; + } + if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) { + _interval = GAP_ADV_PARAMS_INTERVAL_MAX; + } } /* Timeout checks. */ @@ -177,7 +164,6 @@ public: } } -public: /** * Number of microseconds in 0.625 milliseconds. */ @@ -212,7 +198,7 @@ public: * * @return The advertising type. */ - ble::advertising_type_t getAdvertisingType(void) const + AdvertisingType_t getAdvertisingType(void) const { return _advType; } @@ -253,7 +239,7 @@ public: * * @param[in] newAdvType The new advertising type. */ - void setAdvertisingType(ble::advertising_type_t newAdvType) + void setAdvertisingType(AdvertisingType_t newAdvType) { _advType = newAdvType; } @@ -266,7 +252,6 @@ public: void setInterval(uint16_t newInterval) { _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newInterval); - _maxInterval = _interval; } /** @@ -281,419 +266,21 @@ public: _timeout = newTimeout; } - /** - * Update the advertising type. - * - * @param[in] newAdvType The new advertising type. - */ - void setType( - ble::advertising_type_t newAdvType - ) { - _advType = newAdvType; - } - - /** - * Return advertising type. - * - * @return Advertising type. - */ - ble::advertising_type_t getType() const { - return _advType; - } - - /** Check if advertising is anonymous. - * - * @return True if advertising is anonymous. - */ - bool getAnonymousAdvertising() const { - return _anonymous; - } - - /** Advertise without your own address. - * - * @param enable Advertising anonymous if true. - */ - void setAnonymousAdvertising( - bool enable - ) { - _anonymous = enable; - } - - /** Get the advertising intervals on the primary channels. - * - * @param min Minimum interval in milliseconds. - * @param max Maximum interval in milliseconds. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPrimaryInterval( - uint32_t *min /* ms */, - uint32_t *max /* ms */ - ) const { - if (!min || !max) { - return BLE_ERROR_INVALID_PARAM; - } - *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); - *max = ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); - return BLE_ERROR_NONE; - } - - /** Set the advertising intervals on the primary channels. - * - * @param min Minimum interval in milliseconds. - * @param max Maximum interval in milliseconds. - */ - void setPrimaryInterval( - uint32_t min /* ms */, - uint32_t max /* ms */ - ) { - _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); - _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(max); - } - - /** Get channels set for primary advertising. - * - * @param channel37 Use channel 37. - * @param channel38 Use channel 38. - * @param channel39 Use channel 39. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPrimaryChannels( - bool *channel37, - bool *channel38, - bool *channel39 - ) const { - if (!channel37 || !channel38 || !channel39) { - return BLE_ERROR_INVALID_PARAM; - } - *channel37 = _channel37; - *channel38 = _channel38; - *channel39 = _channel39; - return BLE_ERROR_NONE; - } - - /** Set which channels are to be used for primary advertising. - * At least must be used. If all are set to disabled all channels will be used. - * - * @param channel37 Use channel 37. - * @param channel38 Use channel 38. - * @param channel39 Use channel 39. - */ - void setPrimaryChannels( - bool channel37, - bool channel38, - bool channel39 - ) { - if (!channel37 && !channel38 && !channel39) { - channel37 = channel38 = channel39 = true; - } - _channel37 = channel37; - _channel38 = channel38; - _channel39 = channel39; - } - - /** Get what type of address is to be used as your own address during advertising. - * - * @return Addres tpe used. - */ - own_address_type_t getOwnAddressType() const { - return _ownAddressType; - } - - /** Get what type of address is to be used as your own address during advertising. - */ - void setOwnAddressType( - own_address_type_t addressType - ) { - _ownAddressType = addressType; - } - - /** Get peer address and type used during directed advertising. - * - * @param address Address that will have the peer address written to. - * @param addressType Pointer to type which will have the address type written to. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPeer( - BLEProtocol::AddressBytes_t *address, - peer_address_type_t *addressType - ) const { - if (!address || !addressType) { - return BLE_ERROR_INVALID_PARAM; - } - memcpy(address, _peerAddress, sizeof(BLEProtocol::AddressBytes_t)); - *addressType = _peerAddressType; - return BLE_ERROR_NONE; - }; - - /** Set peer address and type used during directed advertising. - * - * @param address Peer's address bytes. - * @param addressType Peer's address type. - */ - void setPeer( - const BLEProtocol::AddressBytes_t address, - peer_address_type_t addressType - ) { - memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); - _peerAddressType = addressType; - }; - - /** Get the policy of whitelist use during advertising; - * - * @return Policy used. - */ - ble::advertising_policy_mode_t getPolicyMode() const { - return _policy; - } - /** Set the policy of whitelist use during advertising; - * - * @param Policy to use. - */ - void setPolicyMode( - ble::advertising_policy_mode_t mode - ) { - _policy = mode; - } - - /** Get the advertising TX power. - * - * @return Advertising TX power. - */ - int8_t getTxPower() const { - return _txPower; - } - - /** Set the advertising TX power. - * - * @param txPower Advertising TX power. - */ - void setTxPower( - int8_t txPower - ) { - _txPower = txPower; - } - - /** Get PHYs used on primary and secondary advertising channels. - * - * @param primaryPhy,secondaryPhy Pointer where the result is written to. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPhy( - ble::phy_t *primaryPhy, - ble::phy_t *secondaryPhy - ) const { - if (!primaryPhy || !secondaryPhy) { - return BLE_ERROR_INVALID_PARAM; - } - *primaryPhy = _primaryPhy; - *secondaryPhy = _secondaryPhy; - return BLE_ERROR_NONE; - } - - /** Get PHYs used on primary and secondary advertising channels. - * - * @param primaryPhy Primary advertising channels PHY. - * @param secondaryPhy Secondary advertising channels PHY. - */ - void setPhy( - ble::phy_t primaryPhy, - ble::phy_t secondaryPhy - ) { - _primaryPhy = primaryPhy; - _secondaryPhy = secondaryPhy; - } - - /** Return how many events can be skipped on the secondary channel. - * - * @return How many events can be skipped on the secondary channel. - */ - uint8_t getSecondaryMaxSkip() const { - return _maxSkip; - } - - /** Set how many events can be skipped on the secondary channel. - * - * @param eventNumber Number of events that can be skipped. - */ - void setSecondaryMaxSkip( - uint8_t eventNumber - ) { - _maxSkip = eventNumber; - } - - /** Enabled or disable the callback that notifies the user about a scan request. - * - * @param enable Enable callback if true. - */ - void setScanRequestNotification( - bool enable = true - ) { - _notifyOnScan = enable; - } - - /** Return of the callback for scan request is enabled. - * - * @return True if callback is enabled. - */ - bool getScanRequestNotification() const { - return _notifyOnScan; - } - - /** Use legacy PDU during advertising. - * - * @param enable If true legacy PDU will be used. - */ - void setUseLegacyPDU( - bool enable = true - ) { - _legacyPDU = enable; - } - - /** Check if legacy PDU is used during advertising. - * - * @return True legacy PDU will be used. - */ - bool getUseLegacyPDU() const { - return _legacyPDU; - } - - /** Set if TX power should be included in the header. - * - * @param enable If true include the TX power in the header. - */ - void includeTxPowerInHeader( - bool enable = true - ) { - _includeHeaderTxPower = enable; - } - - /** Check if TX power should be included in the header. - * - * @return True if TX power is included in the header. - */ - bool getTxPowerInHeader() const { - return _includeHeaderTxPower; - } - - /** Get the minimum advertisement interval in units of 0.625ms. - * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). - */ - uint16_t getMinPrimaryIntervalInADVUnits() const { - return _interval; - } - - /** Get the maximum advertisement interval in units of 0.625ms. - * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). - */ - uint16_t getMaxPrimaryIntervalInADVUnits() const { - return _maxInterval; - } - - /** Get the minimum advertisement interval in milliseconds. - * - * @return The advertisement interval in milliseconds. - */ - uint32_t getMinPrimaryInterval() const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); - } - - /** Get the maximum advertisement interval in milliseconds. - * - * @return The advertisement interval in milliseconds. - */ - uint32_t getMaxPrimaryInterval() const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); - } - - /** Peer address for directed advertising. - * - * @return Peer address. - */ - const BLEProtocol::AddressBytes_t& getPeerAddress() const { - return _peerAddress; - }; - - /** Peer address type for directed advertising. - * - * @return Peer address type. - */ - peer_address_type_t getPeerAddressType() const { - return _peerAddressType; - }; - - /** Get PHY used for primary advertising. - * - * @return PHY used for primary advertising. - */ - ble::phy_t getPrimaryPhy() const { - return _primaryPhy; - } - - /** Get PHY used for secondary advertising. - * - * @return PHY used for secondary advertising. - */ - ble::phy_t getSecondaryPhy() const { - return _secondaryPhy; - } - - /** Check if channel 37 is used for primary advertising. - * - * @return True if channel used. - */ - bool getChannel37() const { - return _channel37; - } - - - /** Check if channel 38 is used for primary advertising. - * - * @return True if channel used. - */ - bool getChannel38() const { - return _channel37; - } - - - /** Check if channel 39 is used for primary advertising. - * - * @return True if channel used. - */ - bool getChannel39() const { - return _channel37; - } - private: - ble::advertising_type_t _advType; - /* The advertising interval in ADV duration units (in other words, 0.625ms). */ + /** + * The advertising type. + */ + AdvertisingType_t _advType; + + /** + * The advertising interval in ADV duration units (in other words, 0.625ms). + */ uint16_t _interval; - /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ + + /** + * The advertising timeout in seconds. + */ uint16_t _timeout; - /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ - uint16_t _maxInterval; - peer_address_type_t _peerAddressType; - own_address_type_t _ownAddressType; - ble::advertising_policy_mode_t _policy; - ble::phy_t _primaryPhy; - ble::phy_t _secondaryPhy; - BLEProtocol::AddressBytes_t _peerAddress; - uint8_t _txPower; - uint8_t _maxSkip; - uint8_t _channel37:1; - uint8_t _channel38:1; - uint8_t _channel39:1; - uint8_t _anonymous:1; - uint8_t _notifyOnScan:1; - uint8_t _legacyPDU:1; - uint8_t _includeHeaderTxPower:1; }; /** diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 19b188f5f2..f8345ffef2 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -84,7 +84,10 @@ public: ble_error_t destroyAdvertisingSet(AdvHandle_t handle); - ble_error_t setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params); + ble_error_t setAdvertisingParams( + AdvHandle_t handle, + const GapAdvertisingParameters ¶ms + ); ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation = false); @@ -225,12 +228,12 @@ public: /** * @see Gap::setAppearance */ - virtual ble_error_t setAppearance(AdvertisingData::Appearance appearance); + virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance); /** * @see Gap::getAppearance */ - virtual ble_error_t getAppearance(AdvertisingData::Appearance *appearanceP); + virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP); /** * @see Gap::setTxPower @@ -341,9 +344,7 @@ public: /** * @see Gap::startAdvertising */ - virtual ble_error_t startAdvertising( - const GapAdvertisingParams ¶ms - ); + virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms); /** * @see Gap::reset diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index ff6d507c17..93fd4c789e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -16,8 +16,6 @@ #include #include -#include - #include "ble/BLEInstanceBase.h" #include "ble/BLEProtocol.h" @@ -745,12 +743,12 @@ ble_error_t GenericGap::getDeviceName(uint8_t *deviceName, unsigned *lengthP) return BLE_ERROR_NONE; } -ble_error_t GenericGap::setAppearance(AdvertisingData::Appearance appearance) +ble_error_t GenericGap::setAppearance(GapAdvertisingData::Appearance appearance) { return _gap_service.set_appearance(appearance); } -ble_error_t GenericGap::getAppearance(AdvertisingData::Appearance *appearanceP) +ble_error_t GenericGap::getAppearance(GapAdvertisingData::Appearance *appearanceP) { if (appearanceP == NULL) { return BLE_ERROR_INVALID_PARAM; @@ -1626,7 +1624,10 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_INVALID_PARAM; } -ble_error_t GenericGap::setAdvertisingParams(AdvHandle_t handle, const GapAdvertisingParams& params) { +ble_error_t GenericGap::setAdvertisingParams( + AdvHandle_t handle, + const GapAdvertisingParameters ¶ms +) { if (!get_adv_set_bit(_existing_sets, handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1756,7 +1757,7 @@ ble_error_t GenericGap::startAdvertising( if (!is_extended_advertising_enabled()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - return startAdvertising(getLegacyAdvertisingParams()); + return startAdvertising(_advParams); } return BLE_ERROR_NOT_IMPLEMENTED; } From 2c7cf2bbd92bf7296029ce8e983d5741d8124bb9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 21:11:38 +0000 Subject: [PATCH 065/361] BLE: revert GapScanningParams --- features/FEATURE_BLE/ble/GapScanningParams.h | 54 ++++--------------- .../FEATURE_BLE/source/GapScanningParams.cpp | 39 ++------------ 2 files changed, 12 insertions(+), 81 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapScanningParams.h b/features/FEATURE_BLE/ble/GapScanningParams.h index 06ceafc9f9..7ff43295c0 100644 --- a/features/FEATURE_BLE/ble/GapScanningParams.h +++ b/features/FEATURE_BLE/ble/GapScanningParams.h @@ -17,9 +17,6 @@ #ifndef MBED_GAP_SCANNING_PARAMS_H__ #define MBED_GAP_SCANNING_PARAMS_H__ -#include -#include "ble/blecommon.h" - /** * @addtogroup ble * @{ @@ -111,16 +108,10 @@ public: * @note If interval is equal to window */ GapScanningParams( - uint16_t interval = 0, - uint16_t window = 0, + uint16_t interval = SCAN_INTERVAL_MAX, + uint16_t window = SCAN_WINDOW_MAX, uint16_t timeout = 0, - bool activeScanning = false, - ble::scanning_policy_mode_t policy = ble::SCAN_POLICY_IGNORE_WHITELIST, - uint16_t codedInterval = 0, - uint16_t codedWindow = 0, - uint16_t codedTimeout = 0, - bool codedActiveScanning = false, - ble::scanning_policy_mode_t codedPolicy = ble::SCAN_POLICY_IGNORE_WHITELIST + bool activeScanning = false ); /** @@ -212,15 +203,7 @@ public: */ bool getActiveScanning(void) const { - return _active_scanning; - } - - ble::scanning_policy_mode_t getScanningPolicy() { - return _policy; - } - - void setScanningPolicy(ble::scanning_policy_mode_t policy) { - _policy = policy; + return _activeScanning; } private: @@ -239,34 +222,15 @@ private: */ uint16_t _timeout; - /** - * Scan interval in units of 625us (between 2.5ms and 10.24s). - */ - uint16_t _interval_coded; - - /** - * Scan window in units of 625us (between 2.5ms and 10.24s). - */ - uint16_t _window_coded; - - /** - * Scan timeout between 0x0001 and 0xFFFF in seconds; 0x0000 disables timeout. - */ - uint16_t _timeout_coded; - - ble::scanning_policy_mode_t _policy; - ble::scanning_policy_mode_t _policy_coded; - - /** * Obtain the peer device's advertising data and (if possible) scanResponse. */ - uint8_t _active_scanning:1; - uint8_t _active_scanning_coded:1; - - uint8_t _phy_1m:1; - uint8_t _phy_coded:1; + bool _activeScanning; +private: + /* Disallow copy constructor. */ + GapScanningParams(const GapScanningParams &); + GapScanningParams& operator =(const GapScanningParams &in); }; /** diff --git a/features/FEATURE_BLE/source/GapScanningParams.cpp b/features/FEATURE_BLE/source/GapScanningParams.cpp index 02eeda6fd7..1d9f1cb26f 100644 --- a/features/FEATURE_BLE/source/GapScanningParams.cpp +++ b/features/FEATURE_BLE/source/GapScanningParams.cpp @@ -17,31 +17,11 @@ #include "ble/Gap.h" #include "ble/GapScanningParams.h" -GapScanningParams::GapScanningParams( - uint16_t interval, - uint16_t window, - uint16_t timeout, - bool activeScanning, - ble::scanning_policy_mode_t policy, - uint16_t codedInterval, - uint16_t codedWindow, - uint16_t codedTimeout, - bool codedActiveScanning, - ble::scanning_policy_mode_t codedPolicy - ) : +GapScanningParams::GapScanningParams(uint16_t interval, uint16_t window, uint16_t timeout, bool activeScanning) : _interval(MSEC_TO_SCAN_DURATION_UNITS(interval)), _window(MSEC_TO_SCAN_DURATION_UNITS(window)), _timeout(timeout), - _active_scanning(activeScanning), - _policy(policy), - _interval_coded(MSEC_TO_SCAN_DURATION_UNITS(codedWindow)), - _window_coded(MSEC_TO_SCAN_DURATION_UNITS(codedWindow)), - _timeout_coded(codedTimeout), - _active_scanning_coded(codedActiveScanning), - _policy_coded(codedPolicy), - _phy_1m(window != 0), - _phy_coded(codedWindow != 0) { - //TODO: refactor + _activeScanning(activeScanning) { /* stay within limits */ if (_interval < SCAN_INTERVAL_MIN) { _interval = SCAN_INTERVAL_MIN; @@ -55,19 +35,6 @@ GapScanningParams::GapScanningParams( if (_window > SCAN_WINDOW_MAX) { _window = SCAN_WINDOW_MAX; } - - if (_interval_coded < SCAN_INTERVAL_MIN) { - _interval_coded = SCAN_INTERVAL_MIN; - } - if (_interval_coded > SCAN_INTERVAL_MAX) { - _interval_coded = SCAN_INTERVAL_MAX; - } - if (_window_coded < SCAN_WINDOW_MIN) { - _window_coded = SCAN_WINDOW_MIN; - } - if (_window_coded > SCAN_WINDOW_MAX) { - _window_coded = SCAN_WINDOW_MAX; - } } ble_error_t @@ -104,5 +71,5 @@ GapScanningParams::setTimeout(uint16_t newTimeout) void GapScanningParams::setActiveScanning(bool activeScanning) { - _active_scanning = activeScanning; + _activeScanning = activeScanning; } From e4c27e50719a6fdeb5c324ca2794eda7e6f8811d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 21:12:16 +0000 Subject: [PATCH 066/361] BLE: Introduce new type for extended advertising parameters. --- .../FEATURE_BLE/ble/AdvertisingParameters.h | 704 ++++++++++++++++++ 1 file changed, 704 insertions(+) create mode 100644 features/FEATURE_BLE/ble/AdvertisingParameters.h diff --git a/features/FEATURE_BLE/ble/AdvertisingParameters.h b/features/FEATURE_BLE/ble/AdvertisingParameters.h new file mode 100644 index 0000000000..f5898100f4 --- /dev/null +++ b/features/FEATURE_BLE/ble/AdvertisingParameters.h @@ -0,0 +1,704 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef MBED_ADVERTISING_PARAMETERS_H__ +#define MBED_ADVERTISING_PARAMETERS_H__ + +#include "BLETypes.h" +#include "BLEProtocol.h" +#include "blecommon.h" +#include "SafeEnum.h" + +/* TODO: std::clamp */ +#define CLAMP(value, min, max) \ + if (value > max) { \ + value = max; \ + } else if (value < min) { \ + value = min; \ + } + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +/** + * Parameters defining the advertising process. + * + * Advertising parameters for legacy advertising are a triplet of three value: + * - The Advertising mode modelled after ble::advertising_type_t. It defines + * if the device is connectable and scannable. This value can be set at + * construction time, updated with setAdvertisingType() and queried by + * getAdvertisingType(). + * - Time interval between advertisement. It can be set at construction time, + * updated by setInterval() and obtained from getInterval(). + * - Duration of the advertising process. As others, it can be set at + * construction time, modified by setTimeout() and retrieved by getTimeout(). + */ +class GapAdvertisingParameters { +public: + + /** + * Minimum Advertising interval for connectable undirected and connectable + * directed events in 625us units. + * + * @note Equal to 20 ms. + */ + static const unsigned GAP_ADV_PARAMS_INTERVAL_MIN = 0x0020; + + /** + * Minimum Advertising interval for scannable and nonconnectable + * undirected events in 625us units. + * + * @note Equal to 100ms. + */ + static const unsigned GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; + + /** + * Maximum Advertising interval in 625us units. + * + * @note Equal to 10.24s. + */ + static const unsigned GAP_ADV_PARAMS_INTERVAL_MAX = 0x4000; + + /** + * Maximum advertising timeout allowed; in seconds. + */ + static const unsigned GAP_ADV_PARAMS_TIMEOUT_MAX = 0x3FFF; + + /** + * Alias for GapAdvertisingParams::ble::advertising_type_t. + * + * @deprecated Future releases will drop this type alias. + */ + typedef ble::advertising_type_t AdvertisingType; + + typedef ble::advertising_type_t AdvertisingType_t; + + static const ble::advertising_type_t ADV_CONNECTABLE_UNDIRECTED = ble::ADV_CONNECTABLE_UNDIRECTED; + static const ble::advertising_type_t ADV_CONNECTABLE_DIRECTED = ble::ADV_CONNECTABLE_DIRECTED; + static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; + static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; + + struct own_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address. */ + RANDOM, /**< Random Device Address. */ + RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use the public address. */ + RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use previously set random address. */ + }; + own_address_type_t(type value) : ble::SafeEnum(value) { } + }; + + struct peer_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ + RANDOM /**< Random Device Address or Random (static) Identity Address. */ + }; + peer_address_type_t(type value) : ble::SafeEnum(value) { } + }; + +public: + /** + * Construct an instance of GapAdvertisingParams. + * + * @param[in] advType Type of advertising. + * @param[in] interval Time interval between two advertisement in units of + * 0.625ms. + * @param[in] timeout Duration in seconds of the advertising process. A + * value of 0 indicate that there is no timeout of the advertising process. + * + * @note If value in input are out of range, they will be normalized. + */ + GapAdvertisingParameters( + ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, + uint16_t interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, + uint16_t timeout = 0 + ) : + _advType(advType), + _interval(interval), + _maxInterval(interval), + _timeout(timeout), + _peerAddressType(peer_address_type_t::PUBLIC), + _ownAddressType(own_address_type_t::PUBLIC), + _policy(ble::ADV_POLICY_IGNORE_WHITELIST), + _primaryPhy(ble::phy_t::LE_1M), + _secondaryPhy(ble::phy_t::LE_1M), + _peerAddress(), + _txPower(127), + _maxSkip(0), + _channel37(1), + _channel38(1), + _channel39(1), + _anonymous(0), + _notifyOnScan(0), + _legacyPDU(1), + _includeHeaderTxPower(0) + { + /* Interval checks. */ + if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { + /* Interval must be 0 in directed connectable mode. */ + _interval = 0; + _maxInterval = 0; + } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { + /* Min interval is slightly larger than in other modes. */ + CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + } else { + CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + } + + /* Timeout checks. */ + if (timeout) { + /* Stay within timeout limits. */ + if (_timeout > GAP_ADV_PARAMS_TIMEOUT_MAX) { + _timeout = GAP_ADV_PARAMS_TIMEOUT_MAX; + } + } + } + +public: + /** + * Number of microseconds in 0.625 milliseconds. + */ + static const uint16_t UNIT_0_625_MS = 625; + + /** + * Convert milliseconds to units of 0.625ms. + * + * @param[in] durationInMillis Number of milliseconds to convert. + * + * @return The value of @p durationInMillis in units of 0.625ms. + */ + static uint16_t MSEC_TO_ADVERTISEMENT_DURATION_UNITS(uint32_t durationInMillis) + { + return (durationInMillis * 1000) / UNIT_0_625_MS; + } + + /** + * Convert units of 0.625ms to milliseconds. + * + * @param[in] gapUnits The number of units of 0.625ms to convert. + * + * @return The value of @p gapUnits in milliseconds. + */ + static uint16_t ADVERTISEMENT_DURATION_UNITS_TO_MS(uint16_t gapUnits) + { + return (gapUnits * UNIT_0_625_MS) / 1000; + } + + /** + * Get the advertising type. + * + * @return The advertising type. + */ + ble::advertising_type_t getAdvertisingType(void) const + { + return _advType; + } + + /** + * Get the advertising interval in milliseconds. + * + * @return The advertisement interval (in milliseconds). + */ + uint16_t getInterval(void) const + { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + } + + /** + * Get the advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint16_t getIntervalInADVUnits(void) const + { + return _interval; + } + + /** + * Get the advertising timeout. + * + * @return The advertising timeout (in seconds). + */ + uint16_t getTimeout(void) const + { + return _timeout; + } + + /** + * Update the advertising type. + * + * @param[in] newAdvType The new advertising type. + */ + void setAdvertisingType(ble::advertising_type_t newAdvType) + { + _advType = newAdvType; + } + + /** + * Update the advertising interval in milliseconds. + * + * @param[in] newInterval The new advertising interval in milliseconds. + */ + void setInterval(uint16_t newInterval) + { + _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newInterval); + _maxInterval = _interval; + } + + /** + * Update the advertising timeout. + * + * @param[in] newTimeout The new advertising timeout (in seconds). + * + * @note 0 is a special value meaning the advertising process never ends. + */ + void setTimeout(uint16_t newTimeout) + { + _timeout = newTimeout; + } + + /** + * Update the advertising type. + * + * @param[in] newAdvType The new advertising type. + */ + void setType( + ble::advertising_type_t newAdvType + ) { + _advType = newAdvType; + } + + /** + * Return advertising type. + * + * @return Advertising type. + */ + ble::advertising_type_t getType() const { + return _advType; + } + + /** Check if advertising is anonymous. + * + * @return True if advertising is anonymous. + */ + bool getAnonymousAdvertising() const { + return _anonymous; + } + + /** Advertise without your own address. + * + * @param enable Advertising anonymous if true. + */ + void setAnonymousAdvertising( + bool enable + ) { + _anonymous = enable; + } + + /** Get the advertising intervals on the primary channels. + * + * @param min Minimum interval in milliseconds. + * @param max Maximum interval in milliseconds. + * + * @return Error if pointers are invalid. + */ + ble_error_t getPrimaryInterval( + uint32_t *min /* ms */, + uint32_t *max /* ms */ + ) const { + if (!min || !max) { + return BLE_ERROR_INVALID_PARAM; + } + *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + *max = ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); + return BLE_ERROR_NONE; + } + + /** Set the advertising intervals on the primary channels. + * + * @param min Minimum interval in milliseconds. + * @param max Maximum interval in milliseconds. + */ + void setPrimaryInterval( + uint32_t min /* ms */, + uint32_t max /* ms */ + ) { + _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); + _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(max); + } + + /** Get channels set for primary advertising. + * + * @param channel37 Use channel 37. + * @param channel38 Use channel 38. + * @param channel39 Use channel 39. + * + * @return Error if pointers are invalid. + */ + ble_error_t getPrimaryChannels( + bool *channel37, + bool *channel38, + bool *channel39 + ) const { + if (!channel37 || !channel38 || !channel39) { + return BLE_ERROR_INVALID_PARAM; + } + *channel37 = _channel37; + *channel38 = _channel38; + *channel39 = _channel39; + return BLE_ERROR_NONE; + } + + /** Set which channels are to be used for primary advertising. + * At least must be used. If all are set to disabled all channels will be used. + * + * @param channel37 Use channel 37. + * @param channel38 Use channel 38. + * @param channel39 Use channel 39. + */ + void setPrimaryChannels( + bool channel37, + bool channel38, + bool channel39 + ) { + if (!channel37 && !channel38 && !channel39) { + channel37 = channel38 = channel39 = true; + } + _channel37 = channel37; + _channel38 = channel38; + _channel39 = channel39; + } + + /** Get what type of address is to be used as your own address during advertising. + * + * @return Addres tpe used. + */ + own_address_type_t getOwnAddressType() const { + return _ownAddressType; + } + + /** Get what type of address is to be used as your own address during advertising. + */ + void setOwnAddressType( + own_address_type_t addressType + ) { + _ownAddressType = addressType; + } + + /** Get peer address and type used during directed advertising. + * + * @param address Address that will have the peer address written to. + * @param addressType Pointer to type which will have the address type written to. + * + * @return Error if pointers are invalid. + */ + ble_error_t getPeer( + BLEProtocol::AddressBytes_t *address, + peer_address_type_t *addressType + ) const { + if (!address || !addressType) { + return BLE_ERROR_INVALID_PARAM; + } + memcpy(address, _peerAddress, sizeof(BLEProtocol::AddressBytes_t)); + *addressType = _peerAddressType; + return BLE_ERROR_NONE; + }; + + /** Set peer address and type used during directed advertising. + * + * @param address Peer's address bytes. + * @param addressType Peer's address type. + */ + void setPeer( + const BLEProtocol::AddressBytes_t address, + peer_address_type_t addressType + ) { + memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); + _peerAddressType = addressType; + }; + + /** Get the policy of whitelist use during advertising; + * + * @return Policy used. + */ + ble::advertising_policy_mode_t getPolicyMode() const { + return _policy; + } + /** Set the policy of whitelist use during advertising; + * + * @param Policy to use. + */ + void setPolicyMode( + ble::advertising_policy_mode_t mode + ) { + _policy = mode; + } + + /** Get the advertising TX power. + * + * @return Advertising TX power. + */ + int8_t getTxPower() const { + return _txPower; + } + + /** Set the advertising TX power. + * + * @param txPower Advertising TX power. + */ + void setTxPower( + int8_t txPower + ) { + _txPower = txPower; + } + + /** Get PHYs used on primary and secondary advertising channels. + * + * @param primaryPhy,secondaryPhy Pointer where the result is written to. + * + * @return Error if pointers are invalid. + */ + ble_error_t getPhy( + ble::phy_t *primaryPhy, + ble::phy_t *secondaryPhy + ) const { + if (!primaryPhy || !secondaryPhy) { + return BLE_ERROR_INVALID_PARAM; + } + *primaryPhy = _primaryPhy; + *secondaryPhy = _secondaryPhy; + return BLE_ERROR_NONE; + } + + /** Get PHYs used on primary and secondary advertising channels. + * + * @param primaryPhy Primary advertising channels PHY. + * @param secondaryPhy Secondary advertising channels PHY. + */ + void setPhy( + ble::phy_t primaryPhy, + ble::phy_t secondaryPhy + ) { + _primaryPhy = primaryPhy; + _secondaryPhy = secondaryPhy; + } + + /** Return how many events can be skipped on the secondary channel. + * + * @return How many events can be skipped on the secondary channel. + */ + uint8_t getSecondaryMaxSkip() const { + return _maxSkip; + } + + /** Set how many events can be skipped on the secondary channel. + * + * @param eventNumber Number of events that can be skipped. + */ + void setSecondaryMaxSkip( + uint8_t eventNumber + ) { + _maxSkip = eventNumber; + } + + /** Enabled or disable the callback that notifies the user about a scan request. + * + * @param enable Enable callback if true. + */ + void setScanRequestNotification( + bool enable = true + ) { + _notifyOnScan = enable; + } + + /** Return of the callback for scan request is enabled. + * + * @return True if callback is enabled. + */ + bool getScanRequestNotification() const { + return _notifyOnScan; + } + + /** Use legacy PDU during advertising. + * + * @param enable If true legacy PDU will be used. + */ + void setUseLegacyPDU( + bool enable = true + ) { + _legacyPDU = enable; + } + + /** Check if legacy PDU is used during advertising. + * + * @return True legacy PDU will be used. + */ + bool getUseLegacyPDU() const { + return _legacyPDU; + } + + /** Set if TX power should be included in the header. + * + * @param enable If true include the TX power in the header. + */ + void includeTxPowerInHeader( + bool enable = true + ) { + _includeHeaderTxPower = enable; + } + + /** Check if TX power should be included in the header. + * + * @return True if TX power is included in the header. + */ + bool getTxPowerInHeader() const { + return _includeHeaderTxPower; + } + + /** Get the minimum advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint16_t getMinPrimaryIntervalInADVUnits() const { + return _interval; + } + + /** Get the maximum advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint16_t getMaxPrimaryIntervalInADVUnits() const { + return _maxInterval; + } + + /** Get the minimum advertisement interval in milliseconds. + * + * @return The advertisement interval in milliseconds. + */ + uint32_t getMinPrimaryInterval() const { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + } + + /** Get the maximum advertisement interval in milliseconds. + * + * @return The advertisement interval in milliseconds. + */ + uint32_t getMaxPrimaryInterval() const { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); + } + + /** Peer address for directed advertising. + * + * @return Peer address. + */ + const BLEProtocol::AddressBytes_t& getPeerAddress() const { + return _peerAddress; + }; + + /** Peer address type for directed advertising. + * + * @return Peer address type. + */ + peer_address_type_t getPeerAddressType() const { + return _peerAddressType; + }; + + /** Get PHY used for primary advertising. + * + * @return PHY used for primary advertising. + */ + ble::phy_t getPrimaryPhy() const { + return _primaryPhy; + } + + /** Get PHY used for secondary advertising. + * + * @return PHY used for secondary advertising. + */ + ble::phy_t getSecondaryPhy() const { + return _secondaryPhy; + } + + /** Check if channel 37 is used for primary advertising. + * + * @return True if channel used. + */ + bool getChannel37() const { + return _channel37; + } + + + /** Check if channel 38 is used for primary advertising. + * + * @return True if channel used. + */ + bool getChannel38() const { + return _channel37; + } + + + /** Check if channel 39 is used for primary advertising. + * + * @return True if channel used. + */ + bool getChannel39() const { + return _channel37; + } + +private: + ble::advertising_type_t _advType; + /* The advertising interval in ADV duration units (in other words, 0.625ms). */ + uint16_t _interval; + /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ + uint16_t _timeout; + /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ + uint16_t _maxInterval; + peer_address_type_t _peerAddressType; + own_address_type_t _ownAddressType; + ble::advertising_policy_mode_t _policy; + ble::phy_t _primaryPhy; + ble::phy_t _secondaryPhy; + BLEProtocol::AddressBytes_t _peerAddress; + uint8_t _txPower; + uint8_t _maxSkip; + uint8_t _channel37:1; + uint8_t _channel38:1; + uint8_t _channel39:1; + uint8_t _anonymous:1; + uint8_t _notifyOnScan:1; + uint8_t _legacyPDU:1; + uint8_t _includeHeaderTxPower:1; +}; + +/** + * @} + * @} + */ + +#endif /* ifndef MBED_ADVERTISING_PARAMETERS_H__ */ From 7f9be995a2224fc637bd53a812824b827ef7065f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 21:22:59 +0000 Subject: [PATCH 067/361] BLE: Revert GapAdvertisingdata and create new type for extened Advertising data. --- features/FEATURE_BLE/ble/Gap.h | 1 + features/FEATURE_BLE/ble/GapAdvertisingData.h | 214 ++-- .../FEATURE_BLE/ble/gap/AdvertisingData.h | 967 ++++++++++++++++++ 3 files changed, 1044 insertions(+), 138 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingData.h diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 965fe82f86..84a8bc9295 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -20,6 +20,7 @@ #include "BLETypes.h" #include "BLEProtocol.h" #include "GapAdvertisingData.h" +#include "ble/gap/AdvertisingData.h" #include "GapAdvertisingParams.h" #include "GapScanningParams.h" #include "GapEvents.h" diff --git a/features/FEATURE_BLE/ble/GapAdvertisingData.h b/features/FEATURE_BLE/ble/GapAdvertisingData.h index 562a072946..2131234818 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingData.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingData.h @@ -14,16 +14,13 @@ * limitations under the License. */ -#ifndef MBED_GAP_ADVERTISING_DATA_H__ -#define MBED_GAP_ADVERTISING_DATA_H__ +#ifndef MBED_GAP_ADVERTISING_DATA__LEGACY_H__ +#define MBED_GAP_ADVERTISING_DATA__LEGACY_H__ #include #include -#include #include "blecommon.h" -#include "platform/Span.h" -#include "NonCopyable.h" /** * @addtogroup ble @@ -42,7 +39,7 @@ * in an advertisement payload. * * After construction, the advertising payload contained in the instance of - * AdvertisingData is empty. Adding new states and named fields can be + * GapAdvertisingData is empty. Adding new states and named fields can be * achieved by invoking the function addData(), and updating existing state * involves calling the function updateData(). * @@ -61,17 +58,17 @@ * static const uint8_t device_name[] = "HRM"; * * // construct an empty advertising payload - * AdvertisingData advertising_data; + * GapAdvertisingData advertising_data; * * // set the flags of the advertising device * advertising_data.addFlags( - * AdvertisingData::LE_GENERAL_DISCOVERABLE | - * AdvertisingData::BREDR_NOT_SUPPORTED + * GapAdvertisingData::LE_GENERAL_DISCOVERABLE | + * GapAdvertisingData::BREDR_NOT_SUPPORTED * ); * * // set the advertised name of the device * advertising_data.addData( - * AdvertisingData::COMPLETE_LOCAL_NAME, + * GapAdvertisingData::COMPLETE_LOCAL_NAME, * device_name, * sizeof(device_name) * ); @@ -96,7 +93,7 @@ * * @par * For convenience, all appropriate AD types are encapsulated in - * AdvertisingData::DataType. + * GapAdvertisingData::DataType. * * @par * Before the AD Types and their payload (if any) can be inserted into @@ -112,8 +109,12 @@ * some basic checks on the payload length and tries to avoid common * errors such as adding an exclusive AD field twice in the advertising * or scan response payload. + * + * @deprecated Use AdvertisingData instead. + * This version provides the buffer backing for the advertising data + * but it's only big enough for legacy advertising. */ -class AdvertisingData +class GapAdvertisingData { public: /*! @@ -129,7 +130,7 @@ public: */ enum DataType_t { /** - * Flags, refer to AdvertisingData::Flags_t. + * Flags, refer to GapAdvertisingData::Flags_t. */ FLAGS = 0x01, @@ -199,7 +200,7 @@ public: SERVICE_DATA = 0x16, /** - * Appearance, refer to AdvertisingData::Appearance_t. + * Appearance, refer to GapAdvertisingData::Appearance_t. */ APPEARANCE = 0x19, @@ -216,7 +217,7 @@ public: }; /** - * Alias for AdvertisingData::DataType_t. + * Alias for GapAdvertisingData::DataType_t. * * @deprecated Future releases will drop this type alias. */ @@ -262,7 +263,7 @@ public: }; /** - * Alias for AdvertisingData::Flags_t. + * Alias for GapAdvertisingData::Flags_t. * * @deprecated Future releases will drop this type alias. */ @@ -528,77 +529,19 @@ public: }; /** - * Alias for AdvertisingData::Appearance_t. + * Alias for GapAdvertisingData::Appearance_t. * * @deprecated Future releases will drop this type alias. */ typedef enum Appearance_t Appearance; - /** Advertising data needs a user provided buffer to store the data. - * - * @param buffer Buffer used to store the data. - * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. - */ - AdvertisingData(mbed::Span buffer) : - _buffer(buffer), - _payloadLen(0) { - } - - /** Advertising data needs a user provided buffer to store the data. - * - * @param buffer Pointer to buffer to be used for storing advertising data. - * @param buffer_size Size of the buffer. - * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. - */ - AdvertisingData(uint8_t* buffer, size_t buffer_size) : - _buffer(buffer, buffer_size), - _payloadLen(0) { - } - - /** Return maximum size of the data that can be stored. - * - * @return Size of the buffer used to store the data. - */ - size_t getBufferSize() const { - return _buffer.size(); - } - /** - * Get the subspan of the buffer containing valid data. - * - * @return A Span containing the payload. + * Construct a GapAdvertising instance with an empty payload. */ - void getData(mbed::Span &data) { - data = mbed::make_Span(_buffer.data(), _payloadLen); - } - - /** - * Get the pointer to the advertising payload bytes. - * - * @return A pointer to the payload. - */ - const uint8_t *getPayload() const - { - return _buffer.data(); - } - - /** - * Get the pointer to the advertising payload bytes. - * - * @return A pointer to the payload. - */ - uint8_t *getPayload() { - return _buffer.data(); - } - - /** - * Get the payload length. - * - * @return The payload length in bytes. - */ - uint8_t getPayloadLen(void) const - { - return _payloadLen; + GapAdvertisingData(void) : + _payload(), + _payloadLen(0), + _appearance(GENERIC_TAG) { } /** @@ -671,11 +614,12 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * AdvertisingData::APPEARANCE as the field type. + * GapAdvertisingData::APPEARANCE as the field type. */ ble_error_t addAppearance(Appearance appearance = GENERIC_TAG) { - return addData(AdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); + _appearance = appearance; + return addData(GapAdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); } /** @@ -689,11 +633,11 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * AdvertisingData::FLAGS as the field type. + * GapAdvertisingData::FLAGS as the field type. */ ble_error_t addFlags(uint8_t flags = LE_GENERAL_DISCOVERABLE) { - return addData(AdvertisingData::FLAGS, &flags, 1); + return addData(GapAdvertisingData::FLAGS, &flags, 1); } /** @@ -706,12 +650,12 @@ public: * advertising buffer to overflow. * * @note This call is equivalent to calling addData() with - * AdvertisingData::TX_POWER_LEVEL as the field type. + * GapAdvertisingData::TX_POWER_LEVEL as the field type. */ ble_error_t addTxPower(int8_t txPower) { /* To Do: Basic error checking to make sure txPower is in range. */ - return addData(AdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); + return addData(GapAdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); } /** @@ -721,10 +665,30 @@ public: */ void clear(void) { - memset(_buffer.data(), 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); + memset(&_payload, 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); _payloadLen = 0; } + /** + * Get the pointer to the advertising payload bytes. + * + * @return A pointer to the payload. + */ + const uint8_t *getPayload(void) const + { + return _payload; + } + + /** + * Get the payload length. + * + * @return The payload length in bytes. + */ + uint8_t getPayloadLen(void) const + { + return _payloadLen; + } + /** * Get the appearance set. * @@ -734,12 +698,7 @@ public: */ uint16_t getAppearance(void) const { - uint16_t appearance = GENERIC_TAG; - const uint8_t *field = findField(AdvertisingData::APPEARANCE); - if (field) { - memcpy((uint8_t*)&appearance, field, 2); - } - return appearance; + return (uint16_t)_appearance; } /** @@ -755,14 +714,14 @@ public: { /* Scan through advertisement data */ for (uint8_t idx = 0; idx < _payloadLen; ) { - uint8_t fieldType = _buffer[idx + 1]; + uint8_t fieldType = _payload[idx + 1]; if (fieldType == type) { - return (_buffer.data() + idx); + return &_payload[idx]; } /* Advance to next field */ - idx += _buffer[idx] + 1; + idx += _payload[idx] + 1; } /* Field not found */ @@ -790,15 +749,15 @@ private: } /* Field length. */ - memset(_buffer.data() + _payloadLen, len + 1, 1); + memset(&_payload[_payloadLen], len + 1, 1); _payloadLen++; /* Field ID. */ - memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); + memset(&_payload[_payloadLen], (uint8_t)advDataType, 1); _payloadLen++; /* Payload. */ - memcpy(_buffer.data() + _payloadLen, payload, len); + memcpy(&_payload[_payloadLen], payload, len); _payloadLen += len; return BLE_ERROR_NONE; @@ -816,7 +775,7 @@ private: uint8_t* findField(DataType_t type) { return const_cast( - static_cast(this)->findField(type) + static_cast(this)->findField(type) ); } @@ -857,13 +816,13 @@ private: case COMPLETE_LIST_128BIT_SERVICE_IDS: case LIST_128BIT_SOLICITATION_IDS: { /* Check if data fits */ - if ((_payloadLen + len) <= _buffer.size()) { + if ((_payloadLen + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { /* * Make room for new field by moving the remainder of the * advertisement payload "to the right" starting after the * TYPE field. */ - uint8_t* end = _buffer.data() +_payloadLen; + uint8_t* end = &_payload[_payloadLen]; while (&field[1] < end) { end[len] = *end; @@ -928,7 +887,7 @@ private: if ((_payloadLen - dataLength + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { /* Remove old field */ - while ((field + dataLength + 2) < _buffer.data() + _payloadLen) { + while ((field + dataLength + 2) < &_payload[_payloadLen]) { *field = field[dataLength + 2]; field++; } @@ -944,42 +903,21 @@ private: return result; } -protected: - AdvertisingData(const AdvertisingData& other) : - _buffer(other._buffer), - _payloadLen(other._payloadLen) { - } - -protected: - /** The memory backing the the data provided by the user. */ - mbed::Span _buffer; - - /** Length of the data added to the advertising buffer. */ - uint8_t _payloadLen; -}; - -/** @deprecated Use AdvertisingData instead. - * This version provides the buffer backing for the advertising data - * but it's only big enough for legacy advertising. - */ -class GapAdvertisingData : public AdvertisingData -{ -public: - GapAdvertisingData() : - AdvertisingData(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) { } - - GapAdvertisingData(const GapAdvertisingData& other) : - AdvertisingData(_payload, GAP_ADVERTISING_DATA_MAX_PAYLOAD) - { - memcpy(_payload, other.getPayload(), GAP_ADVERTISING_DATA_MAX_PAYLOAD); - _payloadLen = other.getPayloadLen(); - } - -private: - /** Advertising data buffer. */ + /** + * Advertising data buffer. + */ uint8_t _payload[GAP_ADVERTISING_DATA_MAX_PAYLOAD]; -}; + /** + * Length of the data added to the advertising buffer. + */ + uint8_t _payloadLen; + + /** + * Appearance value. + */ + uint16_t _appearance; +}; /** * @} @@ -987,4 +925,4 @@ private: */ -#endif /* ifndef MBED_GAP_ADVERTISING_DATA_H__ */ +#endif /* ifndef MBED_GAP_ADVERTISING_DATA__LEGACY_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingData.h b/features/FEATURE_BLE/ble/gap/AdvertisingData.h new file mode 100644 index 0000000000..c669cb6cc6 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingData.h @@ -0,0 +1,967 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_GAP_ADVERTISING_DATA_H__ +#define MBED_GAP_ADVERTISING_DATA_H__ + +#include +#include +#include + +#include "blecommon.h" +#include "platform/Span.h" +#include "NonCopyable.h" + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +#define GAP_ADVERTISING_DATA_MAX_PAYLOAD (31) + +/** + * GAP advertising data builder. + * + * Advertising data are used by broadcaster or peripheral to advertise state + * about the device. This class offers the function to add and update states present + * in an advertisement payload. + * + * After construction, the advertising payload contained in the instance of + * AdvertisingData is empty. Adding new states and named fields can be + * achieved by invoking the function addData(), and updating existing state + * involves calling the function updateData(). + * + * Fields present in the payload can be retrieved by a call to the function + * findField. + * + * This class includes shorthand for the most common fields: + * - FLAGS: addFlags(). + * - APPEARANCE: addAppearance(). + * - TX_POWER_LEVEL: addTxPower(). + * + * @code + * + * Gap ⪆ + * + * static const uint8_t device_name[] = "HRM"; + * + * // construct an empty advertising payload + * AdvertisingData advertising_data; + * + * // set the flags of the advertising device + * advertising_data.addFlags( + * AdvertisingData::LE_GENERAL_DISCOVERABLE | + * AdvertisingData::BREDR_NOT_SUPPORTED + * ); + * + * // set the advertised name of the device + * advertising_data.addData( + * AdvertisingData::COMPLETE_LOCAL_NAME, + * device_name, + * sizeof(device_name) + * ); + * + * // update the advertising data of the gap payload + * gap.setAdvertisingPayload(advertising_data); + * + * @endcode + * + * @note See Bluetooth Specification 4.0 (Vol. 3), Part C, Sections 11 and 18 + * for further information on advertising and scan response data. + * + * @par Advertising and Scan Response Payloads + * Advertising data and scan response data are organized around a set of + * data types called 'AD types' in Bluetooth 4.0 (see the Bluetooth Core + * Specification v4.0, Vol. 3, Part C, Sections 11 and 18). + * + * @par + * Each AD type has its own standardized assigned number, as + * the Bluetooth SIG defines: + * https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. + * + * @par + * For convenience, all appropriate AD types are encapsulated in + * AdvertisingData::DataType. + * + * @par + * Before the AD Types and their payload (if any) can be inserted into + * the advertising or scan response frames, they need to be formatted as + * follows: + * + * @li @c Record length (1 byte). + * @li @c AD Type (1 byte). + * @li @c AD payload (optional; only present if record length > 1). + * + * @par + * This class takes care of properly formatting the payload, performs + * some basic checks on the payload length and tries to avoid common + * errors such as adding an exclusive AD field twice in the advertising + * or scan response payload. + */ +class AdvertisingData +{ +public: + /*! + * List of standard Advertising Data types. + * + * These AD types are used to describe the capabilities of the peripheral + * and are inserted inside the advertising or scan response payloads. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. + * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. + */ + enum DataType_t { + /** + * Flags, refer to AdvertisingData::Flags_t. + */ + FLAGS = 0x01, + + /** + * Incomplete list of 16-bit Service IDs. + */ + INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, + + /** + * Complete list of 16-bit Service IDs. + */ + COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, + + /** + * Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, + + /** + * Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, + + /** + * Incomplete list of 128-bit Service IDs. + */ + INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, + + /** + * Complete list of 128-bit Service IDs. + */ + COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, + + /** + * Shortened Local Name. + */ + SHORTENED_LOCAL_NAME = 0x08, + + /** + * Complete Local Name. + */ + COMPLETE_LOCAL_NAME = 0x09, + + /** + * TX Power Level (in dBm). + */ + TX_POWER_LEVEL = 0x0A, + + /** + * Device ID. + */ + DEVICE_ID = 0x10, + + /** + * Slave Connection Interval Range. + */ + SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, + + /** + * List of 128-bit service UUIDs the device is looking for. + */ + LIST_128BIT_SOLICITATION_IDS = 0x15, + + /** + * Service Data. + */ + SERVICE_DATA = 0x16, + + /** + * Appearance, refer to AdvertisingData::Appearance_t. + */ + APPEARANCE = 0x19, + + /** + * Advertising Interval. + */ + ADVERTISING_INTERVAL = 0x1A, + + /** + * Manufacturer Specific Data. + */ + MANUFACTURER_SPECIFIC_DATA = 0xFF + + }; + + /** + * Alias for AdvertisingData::DataType_t. + * + * @deprecated Future releases will drop this type alias. + */ + typedef enum DataType_t DataType; + + /** + * Enumeration of allowed flags for DataType_t::FLAGS. + * + * @note DataType_t::FLAGS may contain several flags that the bitwise + * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. + */ + enum Flags_t { + /** + * Peripheral device is discoverable for a limited period of time. + */ + LE_LIMITED_DISCOVERABLE = 0x01, + + /** + * Peripheral device is discoverable at any moment. + */ + LE_GENERAL_DISCOVERABLE = 0x02, + + /** + * Peripheral device is LE only and does not support Bluetooth Enhanced + * DataRate. + */ + BREDR_NOT_SUPPORTED = 0x04, + + /** + * Not relevant - dual mode only. + */ + SIMULTANEOUS_LE_BREDR_C = 0x08, + + /** + * Not relevant - dual mode only. + */ + SIMULTANEOUS_LE_BREDR_H = 0x10 + + }; + + /** + * Alias for AdvertisingData::Flags_t. + * + * @deprecated Future releases will drop this type alias. + */ + typedef enum Flags_t Flags; + + /** + * Enumeration of values for the DataType_t::APPEARANCE. + * + * These values describe the physical shape or appearance of the device. + * + * @par Source + * + * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. + * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. + */ + enum Appearance_t { + /** + * Unknown or unspecified appearance type. + */ + UNKNOWN = 0, + + /** + * Generic Phone. + */ + GENERIC_PHONE = 64, + + /** + * Generic Computer. + */ + GENERIC_COMPUTER = 128, + + /** + * Generic Watch. + */ + GENERIC_WATCH = 192, + + /** + * Sports Watch. + */ + WATCH_SPORTS_WATCH = 193, + + /** + * Generic Clock. + */ + GENERIC_CLOCK = 256, + + /** + * Generic Display. + */ + GENERIC_DISPLAY = 320, + + /** + * Generic Remote Control. + */ + GENERIC_REMOTE_CONTROL = 384, + + /** + * Generic Eye Glasses. + */ + GENERIC_EYE_GLASSES = 448, + + /** + * Generic Tag. + */ + GENERIC_TAG = 512, + + /** + * Generic Keyring. + */ + GENERIC_KEYRING = 576, + + /** + * Generic Media Player. + */ + GENERIC_MEDIA_PLAYER = 640, + + /** + * Generic Bar Code Scanner. + */ + GENERIC_BARCODE_SCANNER = 704, + + /** + * Generic Thermometer. + */ + GENERIC_THERMOMETER = 768, + + /** + * Ear Thermometer. + */ + THERMOMETER_EAR = 769, + + /** + * Generic Heart Rate Sensor. + */ + GENERIC_HEART_RATE_SENSOR = 832, + + /** + * Belt Heart Rate Sensor. + */ + HEART_RATE_SENSOR_HEART_RATE_BELT = 833, + + /** + * Generic Blood Pressure. + */ + GENERIC_BLOOD_PRESSURE = 896, + + /** + * Arm Blood Pressure. + */ + BLOOD_PRESSURE_ARM = 897, + + /** + * Wrist Blood Pressure. + */ + BLOOD_PRESSURE_WRIST = 898, + + /** + * Human Interface Device (HID). + */ + HUMAN_INTERFACE_DEVICE_HID = 960, + + /** + * Keyboard. + */ + KEYBOARD = 961, + + /** + * Mouse. + */ + MOUSE = 962, + + /** + * Joystick. + */ + JOYSTICK = 963, + + /** + * Gamepad. + */ + GAMEPAD = 964, + + /** + * Digitizer Tablet. + */ + DIGITIZER_TABLET = 965, + + /** + * Card Reader. + */ + CARD_READER = 966, + + /** + * Digital Pen. + */ + DIGITAL_PEN = 967, + + /** + * Bar Code Scanner. + */ + BARCODE_SCANNER = 968, + + /** + * Generic Glucose Meter. + */ + GENERIC_GLUCOSE_METER = 1024, + + /** + * Generic Running/Walking Sensor. + */ + GENERIC_RUNNING_WALKING_SENSOR = 1088, + + /** + * In Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_IN_SHOE = 1089, + + /** + * On Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_SHOE = 1090, + + /** + * On Hip Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_HIP = 1091, + + /** + * Generic Cycling. + */ + GENERIC_CYCLING = 1152, + + /** + * Cycling Computer. + */ + CYCLING_CYCLING_COMPUTER = 1153, + + /** + * Cycling Speed Sensor. + */ + CYCLING_SPEED_SENSOR = 1154, + + /** + * Cycling Cadence Sensor. + */ + CYCLING_CADENCE_SENSOR = 1155, + + /** + * Cycling Power Sensor. + */ + CYCLING_POWER_SENSOR = 1156, + + /** + * Cycling Speed and Cadence Sensor. + */ + CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, + + /** + * Generic Pulse Oximeter. + */ + PULSE_OXIMETER_GENERIC = 3136, + + /** + * Fingertip Pulse Oximeter. + */ + PULSE_OXIMETER_FINGERTIP = 3137, + + /** + * Wrist Worn Pulse Oximeter. + */ + PULSE_OXIMETER_WRIST_WORN = 3138, + + /** + * Generic Weight Scale. + */ + GENERIC_WEIGHT_SCALE = 3200, + + /** + * Generic Outdoor. + */ + OUTDOOR_GENERIC = 5184, + + /** + * Outdoor Location Display Device. + */ + OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, + + /** + * Outdoor Location and Navigation Display Device. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, + + /** + * Outdoor Location Pod. + */ + OUTDOOR_LOCATION_POD = 5187, + + /** + * Outdoor Location and Navigation Pod. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 + + }; + + /** + * Alias for AdvertisingData::Appearance_t. + * + * @deprecated Future releases will drop this type alias. + */ + typedef enum Appearance_t Appearance; + + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Buffer used to store the data. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ + AdvertisingData(mbed::Span buffer) : + _buffer(buffer), + _payloadLen(0) { + } + + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Pointer to buffer to be used for storing advertising data. + * @param buffer_size Size of the buffer. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ + AdvertisingData(uint8_t* buffer, size_t buffer_size) : + _buffer(buffer, buffer_size), + _payloadLen(0) { + } + + /** Return maximum size of the data that can be stored. + * + * @return Size of the buffer used to store the data. + */ + size_t getBufferSize() const { + return _buffer.size(); + } + + /** + * Get the subspan of the buffer containing valid data. + * + * @return A Span containing the payload. + */ + void getData(mbed::Span &data) { + data = mbed::make_Span(_buffer.data(), _payloadLen); + } + + /** + * Get the pointer to the advertising payload bytes. + * + * @return A pointer to the payload. + */ + const uint8_t *getPayload() const + { + return _buffer.data(); + } + + /** + * Get the pointer to the advertising payload bytes. + * + * @return A pointer to the payload. + */ + uint8_t *getPayload() { + return _buffer.data(); + } + + /** + * Get the payload length. + * + * @return The payload length in bytes. + */ + uint8_t getPayloadLen(void) const + { + return _payloadLen; + } + + /** + * Adds a new field into the payload. + * + * If the supplied advertising data type is already present in the + * advertising payload, then the value is updated. + * + * @param[in] advDataType The type of the field to add. + * @param[in] payload Pointer to the value of the field to add. + * @param[in] len Size in bytes of the value to add. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the advertising + * buffer to overflow. + * + * @note When the specified data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the + * supplied value is appended to the values present in the payload. + */ + ble_error_t addData(DataType_t advDataType, const uint8_t *payload, uint8_t len) + { + /* Find field */ + uint8_t* field = findField(advDataType); + + if (field) { + /* Field type already exists, either add to field or replace */ + return addField(advDataType, payload, len, field); + } else { + /* Field doesn't exist, insert new */ + return appendField(advDataType, payload, len); + } + } + + /** + * Update a specific field in the advertising payload. + * + * @param[in] advDataType The type of the field to update. + * @param[in] payload Pointer to the updated value of the field. + * @param[in] len Size of the new value in bytes. + * + * @return BLE_ERROR_NONE returned on success. + * @return BLE_ERROR_UNSPECIFIED if the specified field is not found, + * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the + * advertising buffer to overflow. + */ + ble_error_t updateData(DataType_t advDataType, const uint8_t *payload, uint8_t len) + { + /* Find field */ + uint8_t* field = findField(advDataType); + + if (field) { + /* Field type already exists, replace field contents */ + return updateField(advDataType, payload, len, field); + } else { + /* field doesn't exist, return an error */ + return BLE_ERROR_UNSPECIFIED; + } + } + + /** + * Add device appearance in the advertising payload. + * + * @param[in] appearance The appearance to advertise. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * AdvertisingData::APPEARANCE as the field type. + */ + ble_error_t addAppearance(Appearance appearance = GENERIC_TAG) + { + return addData(AdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); + } + + /** + * Add BLE flags in the advertising payload. + * + * @param[in] flags Bitfield describing the capability of the device. See + * allowed flags in Flags_t. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * AdvertisingData::FLAGS as the field type. + */ + ble_error_t addFlags(uint8_t flags = LE_GENERAL_DISCOVERABLE) + { + return addData(AdvertisingData::FLAGS, &flags, 1); + } + + /** + * Add the advertising TX in the advertising payload. + * + * @param[in] txPower Transmission power level in dB. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * AdvertisingData::TX_POWER_LEVEL as the field type. + */ + ble_error_t addTxPower(int8_t txPower) + { + /* To Do: Basic error checking to make sure txPower is in range. */ + return addData(AdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); + } + + /** + * Clears the advertising data payload. + * + * @post getPayloadLen() returns 0. + */ + void clear(void) + { + memset(_buffer.data(), 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); + _payloadLen = 0; + } + + /** + * Get the appearance set. + * + * If no value has been set, this function returns GENERIC_TAG. + * + * @return The appearance value set for this device. + */ + uint16_t getAppearance(void) const + { + uint16_t appearance = GENERIC_TAG; + const uint8_t *field = findField(AdvertisingData::APPEARANCE); + if (field) { + memcpy((uint8_t*)&appearance, field, 2); + } + return appearance; + } + + /** + * Search advertisement data for a specific field. + * + * @param[in] type The type of the field to find. + * + * @return A pointer to the first element in the field if found. The first + * element being the length of the field followed by the value of the field. + * @return NULL if the field is not present in the payload. + */ + const uint8_t* findField(DataType_t type) const + { + /* Scan through advertisement data */ + for (uint8_t idx = 0; idx < _payloadLen; ) { + uint8_t fieldType = _buffer[idx + 1]; + + if (fieldType == type) { + return (_buffer.data() + idx); + } + + /* Advance to next field */ + idx += _buffer[idx] + 1; + } + + /* Field not found */ + return NULL; + } + +private: + /** + * Append advertising data based on the specified type. + * + * @param[in] advDataType Type of the new data. + * @param[in] payload Pointer to the data to be appended to the advertising + * payload. + * @param[in] len Length of the data pointed to by @p payload. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + */ + ble_error_t appendField(DataType advDataType, const uint8_t *payload, uint8_t len) + { + /* Make sure we don't exceed the 31-byte payload limit */ + if (_payloadLen + len + 2 > GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* Field length. */ + memset(_buffer.data() + _payloadLen, len + 1, 1); + _payloadLen++; + + /* Field ID. */ + memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); + _payloadLen++; + + /* Payload. */ + memcpy(_buffer.data() + _payloadLen, payload, len); + _payloadLen += len; + + return BLE_ERROR_NONE; + } + + /** + * Search advertisement data for a specific field. + * + * @param[in] type The type of the field to find. + * + * @return A pointer to the first element in the field if found. The first + * element being the length of the field followed by the value of the field. + * @return NULL if the field is not present in the payload. + */ + uint8_t* findField(DataType_t type) + { + return const_cast( + static_cast(this)->findField(type) + ); + } + + /** + * Update in place the value of a field in the advertising payload. + * + * @param[in] advDataType Type of the new data. + * @param[in] payload Pointer to the data to be added to the advertising + * payload. + * @param[in] len Length of the data pointed to by @p payload. + * @param[in] field Pointer to the field of type @p advDataType in the + * advertising buffer. + * + * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the + * supplied value is appended to the values previously added to the + * payload. + * + * @return BLE_ERROR_NONE on success. + */ + ble_error_t addField( + DataType_t advDataType, + const uint8_t *payload, + uint8_t len, + uint8_t* field + ) { + ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; + + switch(advDataType) { + /* These fields have the new data appended if there is sufficient space. */ + case INCOMPLETE_LIST_16BIT_SERVICE_IDS: + case COMPLETE_LIST_16BIT_SERVICE_IDS: + case INCOMPLETE_LIST_32BIT_SERVICE_IDS: + case COMPLETE_LIST_32BIT_SERVICE_IDS: + case INCOMPLETE_LIST_128BIT_SERVICE_IDS: + case COMPLETE_LIST_128BIT_SERVICE_IDS: + case LIST_128BIT_SOLICITATION_IDS: { + /* Check if data fits */ + if ((_payloadLen + len) <= _buffer.size()) { + /* + * Make room for new field by moving the remainder of the + * advertisement payload "to the right" starting after the + * TYPE field. + */ + uint8_t* end = _buffer.data() +_payloadLen; + + while (&field[1] < end) { + end[len] = *end; + end--; + } + + /* Insert new data */ + for (uint8_t idx = 0; idx < len; idx++) { + field[2 + idx] = payload[idx]; + } + + /* Increment lengths */ + field[0] += len; + _payloadLen += len; + + result = BLE_ERROR_NONE; + } + + break; + } + /* These fields are overwritten with the new value */ + default: { + result = updateField(advDataType, payload, len, field); + + break; + } + } + + return result; + } + + /** + * Update in place the value of a field in the advertising payload. + * + * @param[in] advDataType Type of the new data. + * @param[in] payload Pointer to the data to be added to the advertising + * payload. + * @param[in] len Length of the data pointed to by @p payload. + * @param[in] field Pointer to the field of type @p advDataType in the + * advertising buffer. + * + * @return BLE_ERROR_NONE on success. + */ + ble_error_t updateField( + DataType_t advDataType, + const uint8_t *payload, + uint8_t len, + uint8_t* field + ) { + ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; + uint8_t dataLength = field[0] - 1; + + /* New data has same length, do in-order replacement */ + if (len == dataLength) { + for (uint8_t idx = 0; idx < dataLength; idx++) { + field[2 + idx] = payload[idx]; + } + + result = BLE_ERROR_NONE; + } else { + /* Check if data fits */ + if ((_payloadLen - dataLength + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + + /* Remove old field */ + while ((field + dataLength + 2) < _buffer.data() + _payloadLen) { + *field = field[dataLength + 2]; + field++; + } + + /* Reduce length */ + _payloadLen -= dataLength + 2; + + /* Add new field */ + result = appendField(advDataType, payload, len); + } + } + + return result; + } + +protected: + AdvertisingData(const AdvertisingData& other) : + _buffer(other._buffer), + _payloadLen(other._payloadLen) { + } + +protected: + /** The memory backing the the data provided by the user. */ + mbed::Span _buffer; + + /** Length of the data added to the advertising buffer. */ + uint8_t _payloadLen; +}; + +/** + * @} + * @} + */ + + +#endif /* ifndef MBED_GAP_ADVERTISING_DATA_H__ */ From e24fcdd12a5e9d62c1c3aef6c8408ce16eede7da Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 21:25:45 +0000 Subject: [PATCH 068/361] BLE: move extended advertising parameter in ble/gap folder --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/{ => gap}/AdvertisingParameters.h | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename features/FEATURE_BLE/ble/{ => gap}/AdvertisingParameters.h (100%) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 84a8bc9295..87392d6f1a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -28,7 +28,7 @@ #include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" -#include "AdvertisingParameters.h" +#include "gap/AdvertisingParameters.h" /* Forward declarations for classes that are only used for pointers or references. */ diff --git a/features/FEATURE_BLE/ble/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h similarity index 100% rename from features/FEATURE_BLE/ble/AdvertisingParameters.h rename to features/FEATURE_BLE/ble/gap/AdvertisingParameters.h From 6a55d65660118360de10df1b1ba421c65ddefb6a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 9 Nov 2018 22:38:22 +0000 Subject: [PATCH 069/361] BLE: Create advertising payload builder. This change set use a data buffer to set data and scan responses. --- features/FEATURE_BLE/ble/Gap.h | 18 +- .../FEATURE_BLE/ble/gap/AdvertisingData.h | 967 ------------------ .../ble/gap/AdvertisingDataBuilder.h | 552 ++++++++++ features/FEATURE_BLE/ble/generic/GenericGap.h | 29 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 42 +- 5 files changed, 619 insertions(+), 989 deletions(-) delete mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingData.h create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 87392d6f1a..2b4d4e7db7 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -20,7 +20,7 @@ #include "BLETypes.h" #include "BLEProtocol.h" #include "GapAdvertisingData.h" -#include "ble/gap/AdvertisingData.h" +#include "ble/gap/AdvertisingDataBuilder.h" #include "GapAdvertisingParams.h" #include "GapScanningParams.h" #include "GapEvents.h" @@ -1705,17 +1705,27 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, - bool minimiseFragmentation = false) { + virtual ble_error_t setAdvertisingPayload( + AdvHandle_t handle, + mbed::Span payload, + bool minimiseFragmentation = false + ) + { (void) handle; (void) payload; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response) { + virtual ble_error_t setAdvertisingScanResponse( + AdvHandle_t handle, + mbed::Span response, + bool minimiseFragmentation + ) + { (void) handle; (void) response; + (void) minimiseFragmentation; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingData.h b/features/FEATURE_BLE/ble/gap/AdvertisingData.h deleted file mode 100644 index c669cb6cc6..0000000000 --- a/features/FEATURE_BLE/ble/gap/AdvertisingData.h +++ /dev/null @@ -1,967 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef MBED_GAP_ADVERTISING_DATA_H__ -#define MBED_GAP_ADVERTISING_DATA_H__ - -#include -#include -#include - -#include "blecommon.h" -#include "platform/Span.h" -#include "NonCopyable.h" - -/** - * @addtogroup ble - * @{ - * @addtogroup gap - * @{ - */ - -#define GAP_ADVERTISING_DATA_MAX_PAYLOAD (31) - -/** - * GAP advertising data builder. - * - * Advertising data are used by broadcaster or peripheral to advertise state - * about the device. This class offers the function to add and update states present - * in an advertisement payload. - * - * After construction, the advertising payload contained in the instance of - * AdvertisingData is empty. Adding new states and named fields can be - * achieved by invoking the function addData(), and updating existing state - * involves calling the function updateData(). - * - * Fields present in the payload can be retrieved by a call to the function - * findField. - * - * This class includes shorthand for the most common fields: - * - FLAGS: addFlags(). - * - APPEARANCE: addAppearance(). - * - TX_POWER_LEVEL: addTxPower(). - * - * @code - * - * Gap ⪆ - * - * static const uint8_t device_name[] = "HRM"; - * - * // construct an empty advertising payload - * AdvertisingData advertising_data; - * - * // set the flags of the advertising device - * advertising_data.addFlags( - * AdvertisingData::LE_GENERAL_DISCOVERABLE | - * AdvertisingData::BREDR_NOT_SUPPORTED - * ); - * - * // set the advertised name of the device - * advertising_data.addData( - * AdvertisingData::COMPLETE_LOCAL_NAME, - * device_name, - * sizeof(device_name) - * ); - * - * // update the advertising data of the gap payload - * gap.setAdvertisingPayload(advertising_data); - * - * @endcode - * - * @note See Bluetooth Specification 4.0 (Vol. 3), Part C, Sections 11 and 18 - * for further information on advertising and scan response data. - * - * @par Advertising and Scan Response Payloads - * Advertising data and scan response data are organized around a set of - * data types called 'AD types' in Bluetooth 4.0 (see the Bluetooth Core - * Specification v4.0, Vol. 3, Part C, Sections 11 and 18). - * - * @par - * Each AD type has its own standardized assigned number, as - * the Bluetooth SIG defines: - * https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. - * - * @par - * For convenience, all appropriate AD types are encapsulated in - * AdvertisingData::DataType. - * - * @par - * Before the AD Types and their payload (if any) can be inserted into - * the advertising or scan response frames, they need to be formatted as - * follows: - * - * @li @c Record length (1 byte). - * @li @c AD Type (1 byte). - * @li @c AD payload (optional; only present if record length > 1). - * - * @par - * This class takes care of properly formatting the payload, performs - * some basic checks on the payload length and tries to avoid common - * errors such as adding an exclusive AD field twice in the advertising - * or scan response payload. - */ -class AdvertisingData -{ -public: - /*! - * List of standard Advertising Data types. - * - * These AD types are used to describe the capabilities of the peripheral - * and are inserted inside the advertising or scan response payloads. - * - * @par Source - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. - * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. - */ - enum DataType_t { - /** - * Flags, refer to AdvertisingData::Flags_t. - */ - FLAGS = 0x01, - - /** - * Incomplete list of 16-bit Service IDs. - */ - INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, - - /** - * Complete list of 16-bit Service IDs. - */ - COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, - - /** - * Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). - */ - INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, - - /** - * Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). - */ - COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, - - /** - * Incomplete list of 128-bit Service IDs. - */ - INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, - - /** - * Complete list of 128-bit Service IDs. - */ - COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, - - /** - * Shortened Local Name. - */ - SHORTENED_LOCAL_NAME = 0x08, - - /** - * Complete Local Name. - */ - COMPLETE_LOCAL_NAME = 0x09, - - /** - * TX Power Level (in dBm). - */ - TX_POWER_LEVEL = 0x0A, - - /** - * Device ID. - */ - DEVICE_ID = 0x10, - - /** - * Slave Connection Interval Range. - */ - SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, - - /** - * List of 128-bit service UUIDs the device is looking for. - */ - LIST_128BIT_SOLICITATION_IDS = 0x15, - - /** - * Service Data. - */ - SERVICE_DATA = 0x16, - - /** - * Appearance, refer to AdvertisingData::Appearance_t. - */ - APPEARANCE = 0x19, - - /** - * Advertising Interval. - */ - ADVERTISING_INTERVAL = 0x1A, - - /** - * Manufacturer Specific Data. - */ - MANUFACTURER_SPECIFIC_DATA = 0xFF - - }; - - /** - * Alias for AdvertisingData::DataType_t. - * - * @deprecated Future releases will drop this type alias. - */ - typedef enum DataType_t DataType; - - /** - * Enumeration of allowed flags for DataType_t::FLAGS. - * - * @note DataType_t::FLAGS may contain several flags that the bitwise - * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. - * - * @par Source - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. - */ - enum Flags_t { - /** - * Peripheral device is discoverable for a limited period of time. - */ - LE_LIMITED_DISCOVERABLE = 0x01, - - /** - * Peripheral device is discoverable at any moment. - */ - LE_GENERAL_DISCOVERABLE = 0x02, - - /** - * Peripheral device is LE only and does not support Bluetooth Enhanced - * DataRate. - */ - BREDR_NOT_SUPPORTED = 0x04, - - /** - * Not relevant - dual mode only. - */ - SIMULTANEOUS_LE_BREDR_C = 0x08, - - /** - * Not relevant - dual mode only. - */ - SIMULTANEOUS_LE_BREDR_H = 0x10 - - }; - - /** - * Alias for AdvertisingData::Flags_t. - * - * @deprecated Future releases will drop this type alias. - */ - typedef enum Flags_t Flags; - - /** - * Enumeration of values for the DataType_t::APPEARANCE. - * - * These values describe the physical shape or appearance of the device. - * - * @par Source - * - * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. - * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. - */ - enum Appearance_t { - /** - * Unknown or unspecified appearance type. - */ - UNKNOWN = 0, - - /** - * Generic Phone. - */ - GENERIC_PHONE = 64, - - /** - * Generic Computer. - */ - GENERIC_COMPUTER = 128, - - /** - * Generic Watch. - */ - GENERIC_WATCH = 192, - - /** - * Sports Watch. - */ - WATCH_SPORTS_WATCH = 193, - - /** - * Generic Clock. - */ - GENERIC_CLOCK = 256, - - /** - * Generic Display. - */ - GENERIC_DISPLAY = 320, - - /** - * Generic Remote Control. - */ - GENERIC_REMOTE_CONTROL = 384, - - /** - * Generic Eye Glasses. - */ - GENERIC_EYE_GLASSES = 448, - - /** - * Generic Tag. - */ - GENERIC_TAG = 512, - - /** - * Generic Keyring. - */ - GENERIC_KEYRING = 576, - - /** - * Generic Media Player. - */ - GENERIC_MEDIA_PLAYER = 640, - - /** - * Generic Bar Code Scanner. - */ - GENERIC_BARCODE_SCANNER = 704, - - /** - * Generic Thermometer. - */ - GENERIC_THERMOMETER = 768, - - /** - * Ear Thermometer. - */ - THERMOMETER_EAR = 769, - - /** - * Generic Heart Rate Sensor. - */ - GENERIC_HEART_RATE_SENSOR = 832, - - /** - * Belt Heart Rate Sensor. - */ - HEART_RATE_SENSOR_HEART_RATE_BELT = 833, - - /** - * Generic Blood Pressure. - */ - GENERIC_BLOOD_PRESSURE = 896, - - /** - * Arm Blood Pressure. - */ - BLOOD_PRESSURE_ARM = 897, - - /** - * Wrist Blood Pressure. - */ - BLOOD_PRESSURE_WRIST = 898, - - /** - * Human Interface Device (HID). - */ - HUMAN_INTERFACE_DEVICE_HID = 960, - - /** - * Keyboard. - */ - KEYBOARD = 961, - - /** - * Mouse. - */ - MOUSE = 962, - - /** - * Joystick. - */ - JOYSTICK = 963, - - /** - * Gamepad. - */ - GAMEPAD = 964, - - /** - * Digitizer Tablet. - */ - DIGITIZER_TABLET = 965, - - /** - * Card Reader. - */ - CARD_READER = 966, - - /** - * Digital Pen. - */ - DIGITAL_PEN = 967, - - /** - * Bar Code Scanner. - */ - BARCODE_SCANNER = 968, - - /** - * Generic Glucose Meter. - */ - GENERIC_GLUCOSE_METER = 1024, - - /** - * Generic Running/Walking Sensor. - */ - GENERIC_RUNNING_WALKING_SENSOR = 1088, - - /** - * In Shoe Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_IN_SHOE = 1089, - - /** - * On Shoe Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_ON_SHOE = 1090, - - /** - * On Hip Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_ON_HIP = 1091, - - /** - * Generic Cycling. - */ - GENERIC_CYCLING = 1152, - - /** - * Cycling Computer. - */ - CYCLING_CYCLING_COMPUTER = 1153, - - /** - * Cycling Speed Sensor. - */ - CYCLING_SPEED_SENSOR = 1154, - - /** - * Cycling Cadence Sensor. - */ - CYCLING_CADENCE_SENSOR = 1155, - - /** - * Cycling Power Sensor. - */ - CYCLING_POWER_SENSOR = 1156, - - /** - * Cycling Speed and Cadence Sensor. - */ - CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, - - /** - * Generic Pulse Oximeter. - */ - PULSE_OXIMETER_GENERIC = 3136, - - /** - * Fingertip Pulse Oximeter. - */ - PULSE_OXIMETER_FINGERTIP = 3137, - - /** - * Wrist Worn Pulse Oximeter. - */ - PULSE_OXIMETER_WRIST_WORN = 3138, - - /** - * Generic Weight Scale. - */ - GENERIC_WEIGHT_SCALE = 3200, - - /** - * Generic Outdoor. - */ - OUTDOOR_GENERIC = 5184, - - /** - * Outdoor Location Display Device. - */ - OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, - - /** - * Outdoor Location and Navigation Display Device. - */ - OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, - - /** - * Outdoor Location Pod. - */ - OUTDOOR_LOCATION_POD = 5187, - - /** - * Outdoor Location and Navigation Pod. - */ - OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 - - }; - - /** - * Alias for AdvertisingData::Appearance_t. - * - * @deprecated Future releases will drop this type alias. - */ - typedef enum Appearance_t Appearance; - - /** Advertising data needs a user provided buffer to store the data. - * - * @param buffer Buffer used to store the data. - * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. - */ - AdvertisingData(mbed::Span buffer) : - _buffer(buffer), - _payloadLen(0) { - } - - /** Advertising data needs a user provided buffer to store the data. - * - * @param buffer Pointer to buffer to be used for storing advertising data. - * @param buffer_size Size of the buffer. - * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. - */ - AdvertisingData(uint8_t* buffer, size_t buffer_size) : - _buffer(buffer, buffer_size), - _payloadLen(0) { - } - - /** Return maximum size of the data that can be stored. - * - * @return Size of the buffer used to store the data. - */ - size_t getBufferSize() const { - return _buffer.size(); - } - - /** - * Get the subspan of the buffer containing valid data. - * - * @return A Span containing the payload. - */ - void getData(mbed::Span &data) { - data = mbed::make_Span(_buffer.data(), _payloadLen); - } - - /** - * Get the pointer to the advertising payload bytes. - * - * @return A pointer to the payload. - */ - const uint8_t *getPayload() const - { - return _buffer.data(); - } - - /** - * Get the pointer to the advertising payload bytes. - * - * @return A pointer to the payload. - */ - uint8_t *getPayload() { - return _buffer.data(); - } - - /** - * Get the payload length. - * - * @return The payload length in bytes. - */ - uint8_t getPayloadLen(void) const - { - return _payloadLen; - } - - /** - * Adds a new field into the payload. - * - * If the supplied advertising data type is already present in the - * advertising payload, then the value is updated. - * - * @param[in] advDataType The type of the field to add. - * @param[in] payload Pointer to the value of the field to add. - * @param[in] len Size in bytes of the value to add. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the advertising - * buffer to overflow. - * - * @note When the specified data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the - * supplied value is appended to the values present in the payload. - */ - ble_error_t addData(DataType_t advDataType, const uint8_t *payload, uint8_t len) - { - /* Find field */ - uint8_t* field = findField(advDataType); - - if (field) { - /* Field type already exists, either add to field or replace */ - return addField(advDataType, payload, len, field); - } else { - /* Field doesn't exist, insert new */ - return appendField(advDataType, payload, len); - } - } - - /** - * Update a specific field in the advertising payload. - * - * @param[in] advDataType The type of the field to update. - * @param[in] payload Pointer to the updated value of the field. - * @param[in] len Size of the new value in bytes. - * - * @return BLE_ERROR_NONE returned on success. - * @return BLE_ERROR_UNSPECIFIED if the specified field is not found, - * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the - * advertising buffer to overflow. - */ - ble_error_t updateData(DataType_t advDataType, const uint8_t *payload, uint8_t len) - { - /* Find field */ - uint8_t* field = findField(advDataType); - - if (field) { - /* Field type already exists, replace field contents */ - return updateField(advDataType, payload, len, field); - } else { - /* field doesn't exist, return an error */ - return BLE_ERROR_UNSPECIFIED; - } - } - - /** - * Add device appearance in the advertising payload. - * - * @param[in] appearance The appearance to advertise. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - * - * @note This call is equivalent to calling addData() with - * AdvertisingData::APPEARANCE as the field type. - */ - ble_error_t addAppearance(Appearance appearance = GENERIC_TAG) - { - return addData(AdvertisingData::APPEARANCE, (uint8_t *)&appearance, 2); - } - - /** - * Add BLE flags in the advertising payload. - * - * @param[in] flags Bitfield describing the capability of the device. See - * allowed flags in Flags_t. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - * - * @note This call is equivalent to calling addData() with - * AdvertisingData::FLAGS as the field type. - */ - ble_error_t addFlags(uint8_t flags = LE_GENERAL_DISCOVERABLE) - { - return addData(AdvertisingData::FLAGS, &flags, 1); - } - - /** - * Add the advertising TX in the advertising payload. - * - * @param[in] txPower Transmission power level in dB. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - * - * @note This call is equivalent to calling addData() with - * AdvertisingData::TX_POWER_LEVEL as the field type. - */ - ble_error_t addTxPower(int8_t txPower) - { - /* To Do: Basic error checking to make sure txPower is in range. */ - return addData(AdvertisingData::TX_POWER_LEVEL, (uint8_t *)&txPower, 1); - } - - /** - * Clears the advertising data payload. - * - * @post getPayloadLen() returns 0. - */ - void clear(void) - { - memset(_buffer.data(), 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); - _payloadLen = 0; - } - - /** - * Get the appearance set. - * - * If no value has been set, this function returns GENERIC_TAG. - * - * @return The appearance value set for this device. - */ - uint16_t getAppearance(void) const - { - uint16_t appearance = GENERIC_TAG; - const uint8_t *field = findField(AdvertisingData::APPEARANCE); - if (field) { - memcpy((uint8_t*)&appearance, field, 2); - } - return appearance; - } - - /** - * Search advertisement data for a specific field. - * - * @param[in] type The type of the field to find. - * - * @return A pointer to the first element in the field if found. The first - * element being the length of the field followed by the value of the field. - * @return NULL if the field is not present in the payload. - */ - const uint8_t* findField(DataType_t type) const - { - /* Scan through advertisement data */ - for (uint8_t idx = 0; idx < _payloadLen; ) { - uint8_t fieldType = _buffer[idx + 1]; - - if (fieldType == type) { - return (_buffer.data() + idx); - } - - /* Advance to next field */ - idx += _buffer[idx] + 1; - } - - /* Field not found */ - return NULL; - } - -private: - /** - * Append advertising data based on the specified type. - * - * @param[in] advDataType Type of the new data. - * @param[in] payload Pointer to the data to be appended to the advertising - * payload. - * @param[in] len Length of the data pointed to by @p payload. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - */ - ble_error_t appendField(DataType advDataType, const uint8_t *payload, uint8_t len) - { - /* Make sure we don't exceed the 31-byte payload limit */ - if (_payloadLen + len + 2 > GAP_ADVERTISING_DATA_MAX_PAYLOAD) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* Field length. */ - memset(_buffer.data() + _payloadLen, len + 1, 1); - _payloadLen++; - - /* Field ID. */ - memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); - _payloadLen++; - - /* Payload. */ - memcpy(_buffer.data() + _payloadLen, payload, len); - _payloadLen += len; - - return BLE_ERROR_NONE; - } - - /** - * Search advertisement data for a specific field. - * - * @param[in] type The type of the field to find. - * - * @return A pointer to the first element in the field if found. The first - * element being the length of the field followed by the value of the field. - * @return NULL if the field is not present in the payload. - */ - uint8_t* findField(DataType_t type) - { - return const_cast( - static_cast(this)->findField(type) - ); - } - - /** - * Update in place the value of a field in the advertising payload. - * - * @param[in] advDataType Type of the new data. - * @param[in] payload Pointer to the data to be added to the advertising - * payload. - * @param[in] len Length of the data pointed to by @p payload. - * @param[in] field Pointer to the field of type @p advDataType in the - * advertising buffer. - * - * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the - * supplied value is appended to the values previously added to the - * payload. - * - * @return BLE_ERROR_NONE on success. - */ - ble_error_t addField( - DataType_t advDataType, - const uint8_t *payload, - uint8_t len, - uint8_t* field - ) { - ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; - - switch(advDataType) { - /* These fields have the new data appended if there is sufficient space. */ - case INCOMPLETE_LIST_16BIT_SERVICE_IDS: - case COMPLETE_LIST_16BIT_SERVICE_IDS: - case INCOMPLETE_LIST_32BIT_SERVICE_IDS: - case COMPLETE_LIST_32BIT_SERVICE_IDS: - case INCOMPLETE_LIST_128BIT_SERVICE_IDS: - case COMPLETE_LIST_128BIT_SERVICE_IDS: - case LIST_128BIT_SOLICITATION_IDS: { - /* Check if data fits */ - if ((_payloadLen + len) <= _buffer.size()) { - /* - * Make room for new field by moving the remainder of the - * advertisement payload "to the right" starting after the - * TYPE field. - */ - uint8_t* end = _buffer.data() +_payloadLen; - - while (&field[1] < end) { - end[len] = *end; - end--; - } - - /* Insert new data */ - for (uint8_t idx = 0; idx < len; idx++) { - field[2 + idx] = payload[idx]; - } - - /* Increment lengths */ - field[0] += len; - _payloadLen += len; - - result = BLE_ERROR_NONE; - } - - break; - } - /* These fields are overwritten with the new value */ - default: { - result = updateField(advDataType, payload, len, field); - - break; - } - } - - return result; - } - - /** - * Update in place the value of a field in the advertising payload. - * - * @param[in] advDataType Type of the new data. - * @param[in] payload Pointer to the data to be added to the advertising - * payload. - * @param[in] len Length of the data pointed to by @p payload. - * @param[in] field Pointer to the field of type @p advDataType in the - * advertising buffer. - * - * @return BLE_ERROR_NONE on success. - */ - ble_error_t updateField( - DataType_t advDataType, - const uint8_t *payload, - uint8_t len, - uint8_t* field - ) { - ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; - uint8_t dataLength = field[0] - 1; - - /* New data has same length, do in-order replacement */ - if (len == dataLength) { - for (uint8_t idx = 0; idx < dataLength; idx++) { - field[2 + idx] = payload[idx]; - } - - result = BLE_ERROR_NONE; - } else { - /* Check if data fits */ - if ((_payloadLen - dataLength + len) <= GAP_ADVERTISING_DATA_MAX_PAYLOAD) { - - /* Remove old field */ - while ((field + dataLength + 2) < _buffer.data() + _payloadLen) { - *field = field[dataLength + 2]; - field++; - } - - /* Reduce length */ - _payloadLen -= dataLength + 2; - - /* Add new field */ - result = appendField(advDataType, payload, len); - } - } - - return result; - } - -protected: - AdvertisingData(const AdvertisingData& other) : - _buffer(other._buffer), - _payloadLen(other._payloadLen) { - } - -protected: - /** The memory backing the the data provided by the user. */ - mbed::Span _buffer; - - /** Length of the data added to the advertising buffer. */ - uint8_t _payloadLen; -}; - -/** - * @} - * @} - */ - - -#endif /* ifndef MBED_GAP_ADVERTISING_DATA_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h new file mode 100644 index 0000000000..8272145faa --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -0,0 +1,552 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef MBED_GAP_ADVERTISING_DATA_H__ +#define MBED_GAP_ADVERTISING_DATA_H__ + +#include +#include +#include + +#include "blecommon.h" +#include "platform/Span.h" +#include "NonCopyable.h" + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +struct GapAdvertisingConstant { + /*! + * List of standard Advertising Data types. + * + * These AD types are used to describe the capabilities of the peripheral + * and are inserted inside the advertising or scan response payloads. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. + * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. + */ + enum DataType { + /** + * Flags, refer to AdvertisingData::Flags_t. + */ + FLAGS = 0x01, + + /** + * Incomplete list of 16-bit Service IDs. + */ + INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, + + /** + * Complete list of 16-bit Service IDs. + */ + COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, + + /** + * Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, + + /** + * Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, + + /** + * Incomplete list of 128-bit Service IDs. + */ + INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, + + /** + * Complete list of 128-bit Service IDs. + */ + COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, + + /** + * Shortened Local Name. + */ + SHORTENED_LOCAL_NAME = 0x08, + + /** + * Complete Local Name. + */ + COMPLETE_LOCAL_NAME = 0x09, + + /** + * TX Power Level (in dBm). + */ + TX_POWER_LEVEL = 0x0A, + + /** + * Device ID. + */ + DEVICE_ID = 0x10, + + /** + * Slave Connection Interval Range. + */ + SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, + + /** + * List of 128-bit service UUIDs the device is looking for. + */ + LIST_128BIT_SOLICITATION_IDS = 0x15, + + /** + * Service Data. + */ + SERVICE_DATA = 0x16, + + /** + * Appearance, refer to AdvertisingData::Appearance_t. + */ + APPEARANCE = 0x19, + + /** + * Advertising Interval. + */ + ADVERTISING_INTERVAL = 0x1A, + + /** + * Manufacturer Specific Data. + */ + MANUFACTURER_SPECIFIC_DATA = 0xFF + }; + + /** + * Enumeration of allowed flags for DataType_t::FLAGS. + * + * @note DataType_t::FLAGS may contain several flags that the bitwise + * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. + */ + enum Flags { + /** + * Peripheral device is discoverable for a limited period of time. + */ + LE_LIMITED_DISCOVERABLE = 0x01, + + /** + * Peripheral device is discoverable at any moment. + */ + LE_GENERAL_DISCOVERABLE = 0x02, + + /** + * Peripheral device is LE only and does not support Bluetooth Enhanced + * DataRate. + */ + BREDR_NOT_SUPPORTED = 0x04, + + /** + * Not relevant - dual mode only. + */ + SIMULTANEOUS_LE_BREDR_C = 0x08, + + /** + * Not relevant - dual mode only. + */ + SIMULTANEOUS_LE_BREDR_H = 0x10 + + }; + + /** + * Enumeration of values for the DataType_t::APPEARANCE. + * + * These values describe the physical shape or appearance of the device. + * + * @par Source + * + * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. + * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. + */ + enum Appearance { + /** + * Unknown or unspecified appearance type. + */ + UNKNOWN = 0, + + /** + * Generic Phone. + */ + GENERIC_PHONE = 64, + + /** + * Generic Computer. + */ + GENERIC_COMPUTER = 128, + + /** + * Generic Watch. + */ + GENERIC_WATCH = 192, + + /** + * Sports Watch. + */ + WATCH_SPORTS_WATCH = 193, + + /** + * Generic Clock. + */ + GENERIC_CLOCK = 256, + + /** + * Generic Display. + */ + GENERIC_DISPLAY = 320, + + /** + * Generic Remote Control. + */ + GENERIC_REMOTE_CONTROL = 384, + + /** + * Generic Eye Glasses. + */ + GENERIC_EYE_GLASSES = 448, + + /** + * Generic Tag. + */ + GENERIC_TAG = 512, + + /** + * Generic Keyring. + */ + GENERIC_KEYRING = 576, + + /** + * Generic Media Player. + */ + GENERIC_MEDIA_PLAYER = 640, + + /** + * Generic Bar Code Scanner. + */ + GENERIC_BARCODE_SCANNER = 704, + + /** + * Generic Thermometer. + */ + GENERIC_THERMOMETER = 768, + + /** + * Ear Thermometer. + */ + THERMOMETER_EAR = 769, + + /** + * Generic Heart Rate Sensor. + */ + GENERIC_HEART_RATE_SENSOR = 832, + + /** + * Belt Heart Rate Sensor. + */ + HEART_RATE_SENSOR_HEART_RATE_BELT = 833, + + /** + * Generic Blood Pressure. + */ + GENERIC_BLOOD_PRESSURE = 896, + + /** + * Arm Blood Pressure. + */ + BLOOD_PRESSURE_ARM = 897, + + /** + * Wrist Blood Pressure. + */ + BLOOD_PRESSURE_WRIST = 898, + + /** + * Human Interface Device (HID). + */ + HUMAN_INTERFACE_DEVICE_HID = 960, + + /** + * Keyboard. + */ + KEYBOARD = 961, + + /** + * Mouse. + */ + MOUSE = 962, + + /** + * Joystick. + */ + JOYSTICK = 963, + + /** + * Gamepad. + */ + GAMEPAD = 964, + + /** + * Digitizer Tablet. + */ + DIGITIZER_TABLET = 965, + + /** + * Card Reader. + */ + CARD_READER = 966, + + /** + * Digital Pen. + */ + DIGITAL_PEN = 967, + + /** + * Bar Code Scanner. + */ + BARCODE_SCANNER = 968, + + /** + * Generic Glucose Meter. + */ + GENERIC_GLUCOSE_METER = 1024, + + /** + * Generic Running/Walking Sensor. + */ + GENERIC_RUNNING_WALKING_SENSOR = 1088, + + /** + * In Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_IN_SHOE = 1089, + + /** + * On Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_SHOE = 1090, + + /** + * On Hip Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_HIP = 1091, + + /** + * Generic Cycling. + */ + GENERIC_CYCLING = 1152, + + /** + * Cycling Computer. + */ + CYCLING_CYCLING_COMPUTER = 1153, + + /** + * Cycling Speed Sensor. + */ + CYCLING_SPEED_SENSOR = 1154, + + /** + * Cycling Cadence Sensor. + */ + CYCLING_CADENCE_SENSOR = 1155, + + /** + * Cycling Power Sensor. + */ + CYCLING_POWER_SENSOR = 1156, + + /** + * Cycling Speed and Cadence Sensor. + */ + CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, + + /** + * Generic Pulse Oximeter. + */ + PULSE_OXIMETER_GENERIC = 3136, + + /** + * Fingertip Pulse Oximeter. + */ + PULSE_OXIMETER_FINGERTIP = 3137, + + /** + * Wrist Worn Pulse Oximeter. + */ + PULSE_OXIMETER_WRIST_WORN = 3138, + + /** + * Generic Weight Scale. + */ + GENERIC_WEIGHT_SCALE = 3200, + + /** + * Generic Outdoor. + */ + OUTDOOR_GENERIC = 5184, + + /** + * Outdoor Location Display Device. + */ + OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, + + /** + * Outdoor Location and Navigation Display Device. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, + + /** + * Outdoor Location Pod. + */ + OUTDOOR_LOCATION_POD = 5187, + + /** + * Outdoor Location and Navigation Pod. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 + + }; +}; + + +class AdvertisingDataBuilder +{ +public: + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Buffer used to store the data. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ + AdvertisingDataBuilder(mbed::Span buffer) : + _buffer(buffer), + _payloadLen(0) { + } + + /** Advertising data needs a user provided buffer to store the data. + * + * @param buffer Pointer to buffer to be used for storing advertising data. + * @param buffer_size Size of the buffer. + * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. + */ + AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size) : + _buffer(buffer, buffer_size), + _payloadLen(0) { + } + + /** + * Get the subspan of the buffer containing valid data. + * + * @return A Span containing the payload. + */ + mbed::Span getAdvertisingData() const { + return _buffer.first(_payloadLen); + } + + /** + * Adds a new field into the payload. + * + * If the supplied advertising data type is already present in the + * advertising payload, then the value is updated. + * + * @param[in] advDataType The type of the field to add. + * @param[in] payload Pointer to the value of the field to add. + * @param[in] len Size in bytes of the value to add. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the advertising + * buffer to overflow. + * + * @note When the specified data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the + * supplied value is appended to the values present in the payload. + */ + ble_error_t addData(GapAdvertisingConstant::DataType advDataType, const uint8_t *payload, uint8_t len) + { + return appendField(advDataType, payload, len); + } + + /** + * Clears the advertising data payload. + * + * @post getPayloadLen() returns 0. + */ + void clear(void) + { + memset(_buffer.data(), 0, _buffer.size()); + _payloadLen = 0; + } + +private: + /** + * Append advertising data based on the specified type. + * + * @param[in] advDataType Type of the new data. + * @param[in] payload Pointer to the data to be appended to the advertising + * payload. + * @param[in] len Length of the data pointed to by @p payload. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + */ + ble_error_t appendField(GapAdvertisingConstant::DataType advDataType, const uint8_t *payload, uint8_t len) + { + /* Make sure we don't exceed the buffer size */ + if (_payloadLen + len + 2 > _buffer.size()) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* Field length. */ + memset(_buffer.data() + _payloadLen, len + 1, 1); + _payloadLen++; + + /* Field ID. */ + memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); + _payloadLen++; + + /* Payload. */ + memcpy(_buffer.data() + _payloadLen, payload, len); + _payloadLen += len; + + return BLE_ERROR_NONE; + } + +protected: + /** The memory backing the the data provided by the user. */ + mbed::Span _buffer; + + /** Length of the data added to the advertising buffer. */ + uint8_t _payloadLen; +}; + +/** + * @} + * @} + */ + + +#endif /* ifndef MBED_GAP_ADVERTISING_DATA_H__ */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index f8345ffef2..0bb8c3da2a 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -89,11 +89,23 @@ public: const GapAdvertisingParameters ¶ms ); - ble_error_t setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation = false); + ble_error_t setAdvertisingPayload( + AdvHandle_t handle, + mbed::Span payload, + bool minimiseFragmentation + ); - ble_error_t setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response, bool minimiseFragmentation = false); + ble_error_t setAdvertisingScanResponse( + AdvHandle_t handle, + mbed::Span response, + bool minimiseFragmentation + ); - ble_error_t startAdvertising(AdvHandle_t handle, uint8_t maxEvents = 0, uint32_t maxDuration = 0); + ble_error_t startAdvertising( + AdvHandle_t handle, + uint8_t maxEvents = 0, + uint32_t maxDuration = 0 + ); ble_error_t stopAdvertising(AdvHandle_t handle); @@ -383,7 +395,12 @@ public: ); private: - ble_error_t setAdvertisingData(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation, bool scan_reponse); + ble_error_t setAdvertisingData( + AdvHandle_t handle, + mbed::Span payload, + bool minimiseFragmentation, + bool scan_response + ); /** @note Implements ConnectionEventMonitor. * @copydoc ConnectionEventMonitor::set_connection_event_handler @@ -528,13 +545,13 @@ private: pal::scanning_filter_policy_t _scanning_filter_policy; pal::advertising_filter_policy_t _advertising_filter_policy; mutable Whitelist_t _whitelist; - + bool _privacy_enabled; PeripheralPrivacyConfiguration_t _peripheral_privacy_configuration; CentralPrivacyConfiguration_t _central_privacy_configuration; ble::address_t _random_static_identity_address; bool _random_address_rotating; - + mbed::Timeout _advertising_timeout; mbed::Timeout _scan_timeout; mbed::Ticker _address_rotation_ticker; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 93fd4c789e..3477702da0 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1670,39 +1670,57 @@ ble_error_t GenericGap::setAdvertisingParams( ); } -ble_error_t GenericGap::setAdvertisingPayload(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation) { +ble_error_t GenericGap::setAdvertisingPayload( + AdvHandle_t handle, + mbed::Span payload, + bool minimiseFragmentation +) { return setAdvertisingData(handle, payload, minimiseFragmentation, false); } -ble_error_t GenericGap::setAdvertisingScanResponse(AdvHandle_t handle, const AdvertisingData& response, bool minimiseFragmentation) { +ble_error_t GenericGap::setAdvertisingScanResponse( + AdvHandle_t handle, + mbed::Span response, + bool minimiseFragmentation +) { return setAdvertisingData(handle, response, minimiseFragmentation, true); } -ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const AdvertisingData& payload, bool minimiseFragmentation, bool scan_reponse) { +ble_error_t GenericGap::setAdvertisingData( + AdvHandle_t handle, + mbed::Span payload, + bool minimiseFragmentation, + bool scan_response +) { if (!get_adv_set_bit(_existing_sets, handle)) { return BLE_ERROR_INVALID_PARAM; } if (!is_extended_advertising_enabled()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - if (scan_reponse) { + if (payload.size() < GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + return BLE_ERROR_INVALID_PARAM; + } + if (scan_response) { return _pal_gap.set_advertising_data( - payload.getPayloadLen(), - pal::advertising_data_t(payload.getPayload(), payload.getPayloadLen()) + payload.size(), + pal::advertising_data_t(payload.data(), payload.size()) ); } else { return _pal_gap.set_scan_response_data( - payload.getPayloadLen(), - pal::advertising_data_t(payload.getPayload(), payload.getPayloadLen()) + payload.size(), + pal::advertising_data_t(payload.data(), payload.size()) ); } + } else { + return BLE_ERROR_INVALID_PARAM; } return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t status = BLE_ERROR_NONE; uint16_t index = 0; - const uint16_t& length = payload.getPayloadLen(); + const uint16_t& length = payload.size(); uint16_t packet_data_length = length; typedef pal::advertising_fragment_description_t op_t; @@ -1716,13 +1734,13 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising operation = op_t::LAST_FRAGMENT; } - if (scan_reponse) { + if (scan_response) { status = _pal_gap.set_extended_scan_response_data( handle, operation, minimiseFragmentation, packet_data_length, - payload.getPayload() + index + &payload[index] ); } else { status = _pal_gap.set_extended_advertising_data( @@ -1730,7 +1748,7 @@ ble_error_t GenericGap::setAdvertisingData(AdvHandle_t handle, const Advertising operation, minimiseFragmentation, packet_data_length, - payload.getPayload() + index + &payload[index] ); } From 87014b71b67093720ebc7ad11f0f5896baddb48a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 13:40:55 +0000 Subject: [PATCH 070/361] BLE: reorder declaration. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 0bb8c3da2a..d2efb2d1dd 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -113,6 +113,14 @@ public: void init_extended_advertising(); + virtual ble_error_t setScanParameters(const GapScanParameters ¶ms); + + virtual ble_error_t startScan( + scanning_filter_duplicates_t filtering, + uint16_t duration_ms, + uint16_t period_ms + ); + /** * @see Gap::setAddress */ @@ -386,14 +394,6 @@ public: DisconnectionReason_t reason ); - virtual ble_error_t setScanParameters(const GapScanParameters ¶ms); - - virtual ble_error_t startScan( - scanning_filter_duplicates_t filtering, - uint16_t duration_ms, - uint16_t period_ms - ); - private: ble_error_t setAdvertisingData( AdvHandle_t handle, From ad3f3c86a5304c4fe709877ce43c6ee1ebd9cf75 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 13:42:07 +0000 Subject: [PATCH 071/361] BLE: Move implementation to cpp file. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 37 ++--------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 40 +++++++++++++++++++ 2 files changed, 44 insertions(+), 33 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index d2efb2d1dd..eba86bbc60 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -564,42 +564,13 @@ private: mutable bool _non_deprecated_scan_api_used : 1; private: - bool is_extended_advertising_enabled() { - return _pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING); - } + bool is_extended_advertising_enabled(); - static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - bool value = ((*bytes) >> bit) & 0x01; - return value; - } + static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number); - static bool set_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - *bytes = *bytes | (0x01 >> bit); - return true; - } + static bool set_adv_set_bit(uint8_t *bytes, uint8_t bit_number); - static bool clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - *bytes = *bytes & (0x00 >> bit); - return true; - } + static bool clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number); }; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3477702da0..463f57cc5d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2042,5 +2042,45 @@ void GenericGap::use_non_deprecated_scan_api() const _non_deprecated_scan_api_used = true; } +bool GenericGap::is_extended_advertising_enabled() +{ + return _pal_gap.is_feature_supported( + pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING + ); +} + +bool GenericGap::get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte; + bool value = ((*bytes) >> bit) & 0x01; + return value; +} + +bool GenericGap::set_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte; + *bytes = *bytes | (0x01 >> bit); + return true; +} + +bool GenericGap::clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { + if (bit_number > MAX_ADVERTISING_SETS) { + return false; + } + uint8_t byte = bit_number / 8; + uint8_t bit = bit_number - byte; + bytes += byte; + *bytes = *bytes & (0x00 >> bit); + return true; +} + } // namespace generic } // namespace ble From a628eba212556a652b3b478c6b73312ced70e83d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 13:42:47 +0000 Subject: [PATCH 072/361] BLE: cosmetic fixes. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 463f57cc5d..3f5ab6082b 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1576,18 +1576,21 @@ void GenericGap::set_connection_event_handler(pal::ConnectionEventMonitor::Event _connection_event_handler = connection_event_handler; } -uint8_t GenericGap::getMaxAdvertisingSetNumber() { +uint8_t GenericGap::getMaxAdvertisingSetNumber() +{ uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); set_number = MAX_ADVERTISING_SETS < set_number ? MAX_ADVERTISING_SETS : set_number; return set_number; } -uint8_t GenericGap::getMaxAdvertisingDataLength() { +uint8_t GenericGap::getMaxAdvertisingDataLength() +{ return _pal_gap.get_maximum_advertising_data_length(); } -ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) { if (_pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING)) { +ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) +{ return BLE_ERROR_OPERATION_NOT_PERMITTED; } From d63c7bc948f14ef4eb6578805c710f9461f001a1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 13:43:18 +0000 Subject: [PATCH 073/361] BLE: use std::min where appropriate. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index eba86bbc60..b6486a7424 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -48,7 +48,7 @@ class GenericGap : public ::Gap, public: /* TODO: move to config */ - static const size_t MAX_ADVERTISING_SETS = 15; + static const uint8_t MAX_ADVERTISING_SETS = 15; static const size_t MAX_HCI_DATA_LENGTH = 251; /** * Construct a GenericGap instance for a given BLE instance ID. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3f5ab6082b..74364cfce8 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1579,8 +1579,7 @@ void GenericGap::set_connection_event_handler(pal::ConnectionEventMonitor::Event uint8_t GenericGap::getMaxAdvertisingSetNumber() { uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); - set_number = MAX_ADVERTISING_SETS < set_number ? MAX_ADVERTISING_SETS : set_number; - return set_number; + return std::min(MAX_ADVERTISING_SETS, set_number); } uint8_t GenericGap::getMaxAdvertisingDataLength() From f6ceafa3e9455cbda5880dd5a24e2e48d2243040 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 13:43:45 +0000 Subject: [PATCH 074/361] BLE: use helper function where appropriate. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 74364cfce8..24336e1811 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1587,9 +1587,9 @@ uint8_t GenericGap::getMaxAdvertisingDataLength() return _pal_gap.get_maximum_advertising_data_length(); } - if (_pal_gap.is_feature_supported(pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING)) { ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) { + if (is_extended_advertising_enabled()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } From 7882bb30160036b75dc3df76d254e28f5da50397 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 14:00:25 +0000 Subject: [PATCH 075/361] BLE: Fix bit access to mapped advertising set. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 24336e1811..cbc711fe7f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2055,21 +2055,18 @@ bool GenericGap::get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { if (bit_number > MAX_ADVERTISING_SETS) { return false; } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - bool value = ((*bytes) >> bit) & 0x01; - return value; + uint8_t byte_index = bit_number / 8; + uint8_t bit_index = bit_number % 8; + return (bytes[byte_index] >> bit_index) & 0x01; } bool GenericGap::set_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { if (bit_number > MAX_ADVERTISING_SETS) { return false; } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - *bytes = *bytes | (0x01 >> bit); + uint8_t byte_index = bit_number / 8; + uint8_t bit_index = bit_number % 8; + bytes[byte_index] |= (0x01 << bit_index); return true; } @@ -2077,10 +2074,9 @@ bool GenericGap::clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { if (bit_number > MAX_ADVERTISING_SETS) { return false; } - uint8_t byte = bit_number / 8; - uint8_t bit = bit_number - byte; - bytes += byte; - *bytes = *bytes & (0x00 >> bit); + uint8_t byte_index = bit_number / 8; + uint8_t bit_index = bit_number % 8; + bytes[byte_index] &= ~(0x01 << bit_index); return true; } From ed012adab3e55ff931a158dbb64649f0d5988c51 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 14:21:52 +0000 Subject: [PATCH 076/361] BLE: Fix create and destroy advertising set. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index cbc711fe7f..a669de3fa6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1594,23 +1594,25 @@ ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) } uint8_t new_handle = LEGACY_ADVERTISING_HANDLE + 1; + uint8_t end = getMaxAdvertisingSetNumber(); - while (get_adv_set_bit(_existing_sets, new_handle)) { - new_handle++; - } - - /* if we went over the limit this set will fail safely */ - if (set_adv_set_bit(_existing_sets, new_handle)) { - *handle = new_handle; - return BLE_ERROR_NONE; + for (; new_handle < end; ++new_handle) { + if (get_adv_set_bit(_existing_sets, new_handle)) { + set_adv_set_bit(_existing_sets, new_handle); + *handle = new_handle; + return BLE_ERROR_NONE; + } } *handle = INVALID_ADVERTISING_HANDLE; - - return BLE_ERROR_OPERATION_NOT_PERMITTED; + return BLE_ERROR_NO_MEM; } ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (get_adv_set_bit(_existing_sets, handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1619,11 +1621,8 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } - if (set_adv_set_bit(_existing_sets, handle)) { - return _pal_gap.remove_advertising_set(handle); - } - - return BLE_ERROR_INVALID_PARAM; + clear_adv_set_bit(_existing_sets, handle); + return BLE_ERROR_NONE; } ble_error_t GenericGap::setAdvertisingParams( From 2e8389d4fdb4b3624370ea040eb060203f01ad21 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 15:21:31 +0000 Subject: [PATCH 077/361] BLE: Create and destroy advertising sets in the controller. --- features/FEATURE_BLE/ble/Gap.h | 6 ++++- features/FEATURE_BLE/ble/generic/GenericGap.h | 10 ++++++- .../FEATURE_BLE/source/generic/GenericGap.cpp | 27 ++++++++++++++++++- 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 2b4d4e7db7..1681de5494 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1683,7 +1683,11 @@ public: return 0x1F; } - virtual ble_error_t createAdvertisingSet(AdvHandle_t* handle) { + virtual ble_error_t createAdvertisingSet( + AdvHandle_t *handle, + const GapAdvertisingParameters ¶meters + ) + { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index b6486a7424..1fe3480d90 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -80,7 +80,10 @@ public: uint8_t getMaxAdvertisingDataLength(); - ble_error_t createAdvertisingSet(AdvHandle_t* handle); + ble_error_t createAdvertisingSet( + AdvHandle_t *handle, + const GapAdvertisingParameters ¶meters + ); ble_error_t destroyAdvertisingSet(AdvHandle_t handle); @@ -564,6 +567,11 @@ private: mutable bool _non_deprecated_scan_api_used : 1; private: + ble_error_t set_extended_advertising_parameters( + AdvHandle_t handle, + const GapAdvertisingParameters& parameters + ); + bool is_extended_advertising_enabled(); static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index a669de3fa6..11bfcbe3ad 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1587,7 +1587,10 @@ uint8_t GenericGap::getMaxAdvertisingDataLength() return _pal_gap.get_maximum_advertising_data_length(); } -ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) +ble_error_t GenericGap::createAdvertisingSet( + AdvHandle_t *handle, + const GapAdvertisingParameters ¶meters +) { if (is_extended_advertising_enabled()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; @@ -1598,6 +1601,14 @@ ble_error_t GenericGap::createAdvertisingSet(AdvHandle_t* handle) for (; new_handle < end; ++new_handle) { if (get_adv_set_bit(_existing_sets, new_handle)) { + ble_error_t err = set_extended_advertising_parameters( + new_handle, + parameters + ); + if (err) { + return err; + } + set_adv_set_bit(_existing_sets, new_handle); *handle = new_handle; return BLE_ERROR_NONE; @@ -1621,6 +1632,11 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } + ble_error_t err = _pal_gap.remove_advertising_set(handle); + if (err) { + return err; + } + clear_adv_set_bit(_existing_sets, handle); return BLE_ERROR_NONE; } @@ -2043,6 +2059,15 @@ void GenericGap::use_non_deprecated_scan_api() const _non_deprecated_scan_api_used = true; } +ble_error_t GenericGap::set_extended_advertising_parameters( + AdvHandle_t handle, + const GapAdvertisingParameters& parameters +) +{ + // FIXME implement + return BLE_ERROR_NOT_IMPLEMENTED; +} + bool GenericGap::is_extended_advertising_enabled() { return _pal_gap.is_feature_supported( From df5e01bf45a9ede6badbd54160520dd304e053d4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 16:33:09 +0000 Subject: [PATCH 078/361] BLE: wrap bitstream manipulation into a BitArray class. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 44 +++++++++++--- .../FEATURE_BLE/source/generic/GenericGap.cpp | 58 +++++-------------- 2 files changed, 49 insertions(+), 53 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 1fe3480d90..278e8296e0 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -559,8 +559,42 @@ private: mbed::Timeout _scan_timeout; mbed::Ticker _address_rotation_ticker; pal::ConnectionEventMonitor::EventHandler *_connection_event_handler; - uint8_t _existing_sets[(MAX_ADVERTISING_SETS / 8) + 1]; - uint8_t _active_sets[(MAX_ADVERTISING_SETS / 8) + 1]; + + template + struct BitArray { + BitArray() : data() { } + + bool get(size_t index) const { + position p(index); + return (data[p.byte_index] >> p.bit_index) & 0x01; + } + + void set(size_t index) { + position p(index); + data[p.byte_index] |= (0x01 << p.bit_index); + } + + void clear(size_t index) { + position p(index); + data[p.byte_index] &= ~(0x01 << p.bit_index); + } + + private: + struct position { + position(size_t bit_number) : + byte_index(bit_number / 8), + bit_index(bit_number % 8) + { } + + size_t byte_index; + uint8_t bit_index; + }; + + uint8_t data[bit_size / 8 + 1]; + }; + + BitArray _existing_sets; + BitArray _active_sets; // deprecation flags mutable bool _deprecated_scan_api_used : 1; @@ -573,12 +607,6 @@ private: ); bool is_extended_advertising_enabled(); - - static bool get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number); - - static bool set_adv_set_bit(uint8_t *bytes, uint8_t bit_number); - - static bool clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number); }; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 11bfcbe3ad..5307d42355 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -432,10 +432,7 @@ GenericGap::GenericGap( _pal_gap.set_event_handler(this); - memset(_active_sets, 0, MAX_ADVERTISING_SETS); - memset(_existing_sets, 0, MAX_ADVERTISING_SETS); - /* legacy advertising always exists */ - *_existing_sets = 0x01; + // FIXME: lazy initialization of the legacy advertising set } GenericGap::~GenericGap() @@ -1600,7 +1597,7 @@ ble_error_t GenericGap::createAdvertisingSet( uint8_t end = getMaxAdvertisingSetNumber(); for (; new_handle < end; ++new_handle) { - if (get_adv_set_bit(_existing_sets, new_handle)) { + if (_existing_sets.get(new_handle)) { ble_error_t err = set_extended_advertising_parameters( new_handle, parameters @@ -1609,7 +1606,7 @@ ble_error_t GenericGap::createAdvertisingSet( return err; } - set_adv_set_bit(_existing_sets, new_handle); + _existing_sets.set(new_handle); *handle = new_handle; return BLE_ERROR_NONE; } @@ -1624,11 +1621,11 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_INVALID_PARAM; } - if (get_adv_set_bit(_existing_sets, handle)) { + if (_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } - if (get_adv_set_bit(_active_sets, handle)) { + if (_active_sets.get(handle)) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1637,7 +1634,7 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return err; } - clear_adv_set_bit(_existing_sets, handle); + _existing_sets.clear(handle); return BLE_ERROR_NONE; } @@ -1645,7 +1642,7 @@ ble_error_t GenericGap::setAdvertisingParams( AdvHandle_t handle, const GapAdvertisingParameters ¶ms ) { - if (!get_adv_set_bit(_existing_sets, handle)) { + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1709,7 +1706,7 @@ ble_error_t GenericGap::setAdvertisingData( bool minimiseFragmentation, bool scan_response ) { - if (!get_adv_set_bit(_existing_sets, handle)) { + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1786,7 +1783,7 @@ ble_error_t GenericGap::startAdvertising( uint8_t maxEvents, uint32_t maxDuration ) { - if (!get_adv_set_bit(_existing_sets, handle)) { + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1809,14 +1806,14 @@ ble_error_t GenericGap::startAdvertising( ); if (status == BLE_ERROR_NONE) { - set_adv_set_bit(_active_sets, handle); + _active_sets.set(handle); } return status; } ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { - if (get_adv_set_bit(_existing_sets, handle)) { + if (_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1837,7 +1834,7 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { } bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { - return get_adv_set_bit(_active_sets, handle); + return _active_sets.get(handle); } void GenericGap::on_enhanced_connection_complete( @@ -1928,7 +1925,7 @@ void GenericGap::on_advertising_set_terminated( uint8_t number_of_completed_extended_advertising_events ) { - clear_adv_set_bit(_active_sets, advertising_handle); + _active_sets.clear(advertising_handle); if (_eventHandler) { _eventHandler->onAdvertisingEnd( @@ -2075,34 +2072,5 @@ bool GenericGap::is_extended_advertising_enabled() ); } -bool GenericGap::get_adv_set_bit(const uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte_index = bit_number / 8; - uint8_t bit_index = bit_number % 8; - return (bytes[byte_index] >> bit_index) & 0x01; -} - -bool GenericGap::set_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte_index = bit_number / 8; - uint8_t bit_index = bit_number % 8; - bytes[byte_index] |= (0x01 << bit_index); - return true; -} - -bool GenericGap::clear_adv_set_bit(uint8_t *bytes, uint8_t bit_number) { - if (bit_number > MAX_ADVERTISING_SETS) { - return false; - } - uint8_t byte_index = bit_number / 8; - uint8_t bit_index = bit_number % 8; - bytes[byte_index] &= ~(0x01 << bit_index); - return true; -} - } // namespace generic } // namespace ble From 413908d594dddbfee86bcbb33e569e6a6cf0de97 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 16:36:20 +0000 Subject: [PATCH 079/361] BLE: Renaming GenericGap::is_extended_advertising_enabled become GenericGap::is_extended_advertising_available --- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 278e8296e0..983e897e41 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -606,7 +606,7 @@ private: const GapAdvertisingParameters& parameters ); - bool is_extended_advertising_enabled(); + bool is_extended_advertising_available(); }; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 5307d42355..8f45403def 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -528,7 +528,7 @@ ble_error_t GenericGap::stopAdvertising() ble_error_t GenericGap::stopScan() { ble_error_t err; - if (is_extended_advertising_enabled()) { + if (is_extended_advertising_available()) { err = _pal_gap.extended_scan_enable(false, pal::duplicates_filter_t::DISABLE, 0, 0); } else { err = _pal_gap.scan_enable(false, false); @@ -1589,7 +1589,7 @@ ble_error_t GenericGap::createAdvertisingSet( const GapAdvertisingParameters ¶meters ) { - if (is_extended_advertising_enabled()) { + if (is_extended_advertising_available()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1710,7 +1710,7 @@ ble_error_t GenericGap::setAdvertisingData( return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_enabled()) { + if (!is_extended_advertising_available()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { if (payload.size() < GAP_ADVERTISING_DATA_MAX_PAYLOAD) { return BLE_ERROR_INVALID_PARAM; @@ -1787,7 +1787,7 @@ ble_error_t GenericGap::startAdvertising( return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_enabled()) { + if (!is_extended_advertising_available()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { return startAdvertising(_advParams); } @@ -1817,7 +1817,7 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_enabled()) { + if (!is_extended_advertising_available()) { if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { return stopAdvertising(); } @@ -1960,7 +1960,7 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) // FIXME: validate parameters // FIXME: deal with random address rotation - if (is_extended_advertising_enabled()) { + if (is_extended_advertising_available()) { bool active_scanning[] = { params.get_1m_configuration().active_scanning, params.get_coded_configuration().active_scanning @@ -2007,7 +2007,7 @@ ble_error_t GenericGap::startScan( use_non_deprecated_scan_api(); // FIXME: deal with random address rotation - if (is_extended_advertising_enabled()) { + if (is_extended_advertising_available()) { return _pal_gap.extended_scan_enable( /* enable */true, (pal::duplicates_filter_t::type) filtering, @@ -2065,7 +2065,7 @@ ble_error_t GenericGap::set_extended_advertising_parameters( return BLE_ERROR_NOT_IMPLEMENTED; } -bool GenericGap::is_extended_advertising_enabled() +bool GenericGap::is_extended_advertising_available() { return _pal_gap.is_feature_supported( pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING From 0d90671842521fd8749724b05fe58f69cad7cc3a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 17:24:14 +0000 Subject: [PATCH 080/361] BLE: Fix release of advertising sets. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 8f45403def..9b5921ff8f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1617,11 +1617,15 @@ ble_error_t GenericGap::createAdvertisingSet( } ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { + if (is_extended_advertising_available()) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } - if (_existing_sets.get(handle)) { + if (_existing_sets.get(handle) == false) { return BLE_ERROR_INVALID_PARAM; } From d2773e9731b4201faf68261e68b70a0dd9884817 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 17:36:33 +0000 Subject: [PATCH 081/361] BLE: Reduce complexity of GenericGap::setAdvertisingData --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 118 +++++++++--------- 1 file changed, 62 insertions(+), 56 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9b5921ff8f..3c0337a869 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1710,76 +1710,82 @@ ble_error_t GenericGap::setAdvertisingData( bool minimiseFragmentation, bool scan_response ) { + // type declarations + typedef pal::advertising_fragment_description_t op_t; + typedef ble_error_t (pal::Gap::*legacy_set_data_fn_t)( + uint8_t , + const pal::advertising_data_t& + ); + typedef ble_error_t (pal::Gap::*set_data_fn_t)( + advertising_handle_t advertising_handle, + op_t operation, + bool minimize_fragmentation, + uint8_t scan_response_data_size, + const uint8_t *scan_response_data + ); + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } + // handle special case of legacy advertising if (!is_extended_advertising_available()) { - if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - if (payload.size() < GAP_ADVERTISING_DATA_MAX_PAYLOAD) { - return BLE_ERROR_INVALID_PARAM; - } - if (scan_response) { - return _pal_gap.set_advertising_data( - payload.size(), - pal::advertising_data_t(payload.data(), payload.size()) - ); - } else { - return _pal_gap.set_scan_response_data( - payload.size(), - pal::advertising_data_t(payload.data(), payload.size()) - ); - } - } else { + if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } - return BLE_ERROR_NOT_IMPLEMENTED; + + if (payload.size() < GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + return BLE_ERROR_INVALID_PARAM; + } + + // select the pal function + legacy_set_data_fn_t set_data = scan_response ? + &pal::Gap::set_scan_response_data : + &pal::Gap::set_advertising_data; + + // set the payload + return (_pal_gap.*set_data)( + payload.size(), + pal::advertising_data_t(payload.data(), payload.size()) + ); } - ble_error_t status = BLE_ERROR_NONE; - uint16_t index = 0; - const uint16_t& length = payload.size(); - uint16_t packet_data_length = length; + // select the pal function + set_data_fn_t set_data = scan_response ? + &pal::Gap::set_extended_scan_response_data : + &pal::Gap::set_extended_advertising_data; - typedef pal::advertising_fragment_description_t op_t; - op_t operation = (length > MAX_HCI_DATA_LENGTH) ? op_t::FIRST_FRAGMENT : op_t::COMPLETE_FRAGMENT; - - while (index < length) { - if ((length - index) > MAX_HCI_DATA_LENGTH) { - packet_data_length = MAX_HCI_DATA_LENGTH; - } else { - packet_data_length = length - index; - operation = op_t::LAST_FRAGMENT; + for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { + // select the operation based on the index + op_t op(op_t::INTERMEDIATE_FRAGMENT); + if (end < MAX_HCI_DATA_LENGTH) { + op = op_t::COMPLETE_FRAGMENT; + } else if (i == 0) { + op = op_t::FIRST_FRAGMENT; + } else if ((end - i) <= MAX_HCI_DATA_LENGTH) { + op = op_t::LAST_FRAGMENT; } - if (scan_response) { - status = _pal_gap.set_extended_scan_response_data( - handle, - operation, - minimiseFragmentation, - packet_data_length, - &payload[index] - ); - } else { - status = _pal_gap.set_extended_advertising_data( - handle, - operation, - minimiseFragmentation, - packet_data_length, - &payload[index] - ); + // extract the payload + mbed::Span sub_payload = payload.subspan( + i, + std::min(MAX_HCI_DATA_LENGTH, (end - i)) + ); + + // set the payload + ble_error_t err = (_pal_gap.*set_data)( + handle, + op, + minimiseFragmentation, + sub_payload.size(), + sub_payload.data() + ); + + if (err) { + return err; } - - if (status != BLE_ERROR_NONE) { - return status; - } - - index += packet_data_length; - - operation = op_t::INTERMEDIATE_FRAGMENT; } - - return status; + return BLE_ERROR_NONE; } ble_error_t GenericGap::startAdvertising( From b825ffc1f6aa93d34dc913ffd463e3e390fc84fc Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 19:24:04 +0000 Subject: [PATCH 082/361] BLE: Handle setAdvertisingParameters on legacy controllers. --- .../ble/gap/AdvertisingParameters.h | 72 +++++++++++------ features/FEATURE_BLE/ble/generic/GenericGap.h | 4 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 77 +++++++++++-------- 3 files changed, 96 insertions(+), 57 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index f5898100f4..99322cb574 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -122,7 +122,7 @@ public: * Construct an instance of GapAdvertisingParams. * * @param[in] advType Type of advertising. - * @param[in] interval Time interval between two advertisement in units of + * @param[in] minInterval Time interval between two advertisement in units of * 0.625ms. * @param[in] timeout Duration in seconds of the advertising process. A * value of 0 indicate that there is no timeout of the advertising process. @@ -130,13 +130,14 @@ public: * @note If value in input are out of range, they will be normalized. */ GapAdvertisingParameters( - ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, - uint16_t interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, + ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, + uint32_t minInterval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, + uint32_t maxInterval = GAP_ADV_PARAMS_INTERVAL_MAX, uint16_t timeout = 0 ) : _advType(advType), - _interval(interval), - _maxInterval(interval), + _minInterval(minInterval), + _maxInterval(maxInterval), _timeout(timeout), _peerAddressType(peer_address_type_t::PUBLIC), _ownAddressType(own_address_type_t::PUBLIC), @@ -157,14 +158,14 @@ public: /* Interval checks. */ if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { /* Interval must be 0 in directed connectable mode. */ - _interval = 0; + _minInterval = 0; _maxInterval = 0; } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { /* Min interval is slightly larger than in other modes. */ - CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); } else { - CLAMP(_interval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + CLAMP(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); } @@ -222,9 +223,9 @@ public: * * @return The advertisement interval (in milliseconds). */ - uint16_t getInterval(void) const + uint32_t getMinInterval(void) const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); } /** @@ -233,9 +234,30 @@ public: * @return The advertisement interval in advertisement duration units * (0.625ms units). */ - uint16_t getIntervalInADVUnits(void) const + uint32_t getMinIntervalInADVUnits(void) const { - return _interval; + return _minInterval; + } + + /** + * Get the max advertising interval in milliseconds. + * + * @return The advertisement interval (in milliseconds). + */ + uint32_t getMaxInterval(void) const + { + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); + } + + /** + * Get the max advertisement interval in units of 0.625ms. + * + * @return The advertisement interval in advertisement duration units + * (0.625ms units). + */ + uint32_t getMaxIntervalInADVUnits(void) const + { + return _maxInterval; } /** @@ -261,12 +283,12 @@ public: /** * Update the advertising interval in milliseconds. * - * @param[in] newInterval The new advertising interval in milliseconds. + * @param[in] newMinInterval The new advertising interval in milliseconds. */ - void setInterval(uint16_t newInterval) + void setInterval(uint32_t newMinInterval, uint32_t newMaxInterval) { - _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newInterval); - _maxInterval = _interval; + _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newMinInterval); + _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newMaxInterval); } /** @@ -333,7 +355,7 @@ public: if (!min || !max) { return BLE_ERROR_INVALID_PARAM; } - *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); *max = ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); return BLE_ERROR_NONE; } @@ -347,7 +369,7 @@ public: uint32_t min /* ms */, uint32_t max /* ms */ ) { - _interval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); + _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(max); } @@ -584,8 +606,8 @@ public: * @return The advertisement interval in advertisement duration units * (0.625ms units). */ - uint16_t getMinPrimaryIntervalInADVUnits() const { - return _interval; + uint32_t getMinPrimaryIntervalInADVUnits() const { + return _minInterval; } /** Get the maximum advertisement interval in units of 0.625ms. @@ -593,7 +615,7 @@ public: * @return The advertisement interval in advertisement duration units * (0.625ms units). */ - uint16_t getMaxPrimaryIntervalInADVUnits() const { + uint32_t getMaxPrimaryIntervalInADVUnits() const { return _maxInterval; } @@ -602,7 +624,7 @@ public: * @return The advertisement interval in milliseconds. */ uint32_t getMinPrimaryInterval() const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_interval); + return ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); } /** Get the maximum advertisement interval in milliseconds. @@ -674,11 +696,11 @@ public: private: ble::advertising_type_t _advType; /* The advertising interval in ADV duration units (in other words, 0.625ms). */ - uint16_t _interval; + uint32_t _minInterval; + /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ + uint32_t _maxInterval; /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ uint16_t _timeout; - /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ - uint16_t _maxInterval; peer_address_type_t _peerAddressType; own_address_type_t _ownAddressType; ble::advertising_policy_mode_t _policy; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 983e897e41..054c0a3f24 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -601,9 +601,9 @@ private: mutable bool _non_deprecated_scan_api_used : 1; private: - ble_error_t set_extended_advertising_parameters( + ble_error_t setExtendedAdvertisingParameters( AdvHandle_t handle, - const GapAdvertisingParameters& parameters + const GapAdvertisingParameters ¶meters ); bool is_extended_advertising_available(); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3c0337a869..2ed0d3cacf 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1598,7 +1598,7 @@ ble_error_t GenericGap::createAdvertisingSet( for (; new_handle < end; ++new_handle) { if (_existing_sets.get(new_handle)) { - ble_error_t err = set_extended_advertising_parameters( + ble_error_t err = setExtendedAdvertisingParameters( new_handle, parameters ); @@ -1649,41 +1649,67 @@ ble_error_t GenericGap::setAdvertisingParams( if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } - - pal::advertising_event_properties_t event_properties((pal::advertising_type_t::type)params.getType()); + if (!is_extended_advertising_available()) { + if (handle != LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + pal::advertising_channel_map_t channel_map( + params.getChannel37(), + params.getChannel38(), + params.getChannel39() + ); + + // FIXME: check min and max adv value ??? or truncate ??? + + return _pal_gap.set_advertising_parameters( + params.getMinIntervalInADVUnits(), + params.getMaxIntervalInADVUnits(), + (pal::advertising_type_t::type) params.getType(), + (pal::own_address_type_t::type) params.getOwnAddressType().value(), + (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), + params.getPeerAddress(), + channel_map, + (pal::advertising_filter_policy_t::type) params.getPolicyMode() + ); + } else { + return setExtendedAdvertisingParameters(handle, params); + } +} + +ble_error_t GenericGap::setExtendedAdvertisingParameters( + AdvHandle_t handle, + const GapAdvertisingParameters ¶ms +) +{ + pal::advertising_event_properties_t event_properties( + (pal::advertising_type_t::type)params.getType()); event_properties.include_tx_power = params.getTxPowerInHeader(); event_properties.omit_advertiser_address = params.getAnonymousAdvertising(); event_properties.use_legacy_pdu = params.getUseLegacyPDU(); - pal::advertising_channel_map_t channel_map(params.getChannel37(), params.getChannel38(), params.getChannel39()); - pal::own_address_type_t own_address_type = (pal::own_address_type_t::type)params.getOwnAddressType().value(); - - if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - AddressUseType_t use_type = PERIPHERAL_CONNECTABLE; - if ((params.getAdvertisingType() == ADV_SCANNABLE_UNDIRECTED) || - (params.getAdvertisingType() == ADV_NON_CONNECTABLE_UNDIRECTED)) { - use_type = PERIPHERAL_NON_CONNECTABLE; - } - - own_address_type = (pal::own_address_type_t) get_own_address_type(use_type); - } + pal::advertising_channel_map_t channel_map( + params.getChannel37(), + params.getChannel38(), + params.getChannel39() + ); return _pal_gap.set_extended_advertising_parameters( handle, event_properties, - (pal::advertising_interval_t)params.getMinPrimaryIntervalInADVUnits(), - (pal::advertising_interval_t)params.getMaxPrimaryIntervalInADVUnits(), + params.getMinPrimaryIntervalInADVUnits(), + params.getMaxPrimaryIntervalInADVUnits(), channel_map, - own_address_type, - (pal::advertising_peer_address_type_t::type)params.getPeerAddressType().value(), + (pal::own_address_type_t::type) params.getOwnAddressType().value(), + (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), (pal::advertising_filter_policy_t::type) params.getPolicyMode(), - (pal::advertising_power_t) params.getTxPower(), + params.getTxPower(), params.getPrimaryPhy(), params.getSecondaryMaxSkip(), params.getSecondaryPhy(), - (handle % 0x10), + /* SID */ (handle % 0x10), params.getScanRequestNotification() ); } @@ -2066,15 +2092,6 @@ void GenericGap::use_non_deprecated_scan_api() const _non_deprecated_scan_api_used = true; } -ble_error_t GenericGap::set_extended_advertising_parameters( - AdvHandle_t handle, - const GapAdvertisingParameters& parameters -) -{ - // FIXME implement - return BLE_ERROR_NOT_IMPLEMENTED; -} - bool GenericGap::is_extended_advertising_available() { return _pal_gap.is_feature_supported( From 74356aa7f05808d935bcb8ea03a4ca224c8426b0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 19:44:22 +0000 Subject: [PATCH 083/361] BLE: Rework GenericGap::startAdvertising --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 50 ++++++++++++------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 2ed0d3cacf..4777c4f29a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1824,28 +1824,42 @@ ble_error_t GenericGap::startAdvertising( } if (!is_extended_advertising_available()) { - if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - return startAdvertising(_advParams); + if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + ble_error_t err = _pal_gap.advertising_enable(true); + if (err) { + return err; + } + + _advertising_timeout.detach(); + if (maxDuration) { + _advertising_timeout.attach_us( + mbed::callback(this, &GenericGap::on_advertising_timeout), + maxDuration + ); + } + + } else { + /* round up */ + uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; + ble_error_t err = _pal_gap.extended_advertising_enable( + /* enable */ true, + /* number of advertising sets */ 1, + &handle, + &duration_10ms, + &maxEvents + ); + + if (err) { + return err; } - return BLE_ERROR_NOT_IMPLEMENTED; } - /* round up */ - uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; + _active_sets.set(handle); - ble_error_t status = _pal_gap.extended_advertising_enable( - true, - 1, - &handle, - &duration_10ms, - &maxEvents - ); - - if (status == BLE_ERROR_NONE) { - _active_sets.set(handle); - } - - return status; + return BLE_ERROR_NONE; } ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { From d6d1ea5c2a408967918f16770f66ea864e1bd3c0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 20:02:44 +0000 Subject: [PATCH 084/361] BLE: rework GenericGap::stopAdvertising(AdvHandle) --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 4777c4f29a..fe44081e77 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1840,7 +1840,6 @@ ble_error_t GenericGap::startAdvertising( maxDuration ); } - } else { /* round up */ uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; @@ -1868,15 +1867,21 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { } if (!is_extended_advertising_available()) { - if (handle == Gap::LEGACY_ADVERTISING_HANDLE) { - return stopAdvertising(); + if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; } - return BLE_ERROR_NOT_IMPLEMENTED; + + ble_error_t err = _pal_gap.advertising_enable(false); + if (err) { + return err; + } + _advertising_timeout.detach(); + // FIXME: Handle random address rotation of this advertising set } return _pal_gap.extended_advertising_enable( - true, - 1, + /*enable ? */ false, + /* number of advertising sets */ 1, &handle, NULL, NULL From 06b3ccd322e07d0baf59206f38315350417714d0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 21:29:09 +0000 Subject: [PATCH 085/361] BLE: refactor parameters order of Gap::startAdvertising --- features/FEATURE_BLE/ble/Gap.h | 7 ++++--- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 ++++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 1681de5494..23d5b9c028 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1736,9 +1736,10 @@ public: virtual ble_error_t startAdvertising( AdvHandle_t handle, - uint8_t maxEvents = 0, - uint32_t maxDuration = 0 - ) { + uint32_t maxDuration = 0, + uint8_t maxEvents = 0 + ) + { (void) maxEvents; (void) maxDuration; /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 054c0a3f24..f41f079ded 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -106,8 +106,8 @@ public: ble_error_t startAdvertising( AdvHandle_t handle, - uint8_t maxEvents = 0, - uint32_t maxDuration = 0 + uint32_t maxDuration, + uint8_t maxEvents ); ble_error_t stopAdvertising(AdvHandle_t handle); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index fe44081e77..0dc1c650d9 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1816,9 +1816,10 @@ ble_error_t GenericGap::setAdvertisingData( ble_error_t GenericGap::startAdvertising( AdvHandle_t handle, - uint8_t maxEvents, - uint32_t maxDuration -) { + uint32_t maxDuration, + uint8_t maxEvents +) +{ if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } From 5236a706187a92b5d975891f4cde3c96f5ec4d8f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 21:30:19 +0000 Subject: [PATCH 086/361] BLE: Add default minimiseFragmentationValue for Gap::setAdvertisingScanresponse. --- features/FEATURE_BLE/ble/Gap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 23d5b9c028..9755d5c43a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1724,7 +1724,7 @@ public: virtual ble_error_t setAdvertisingScanResponse( AdvHandle_t handle, mbed::Span response, - bool minimiseFragmentation + bool minimiseFragmentation = false ) { (void) handle; From b1c6914e34e3185153c9cd38929db2b5ce655ba2 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 10 Nov 2018 23:10:03 +0000 Subject: [PATCH 087/361] BLE: Add periodic sync advertisement management. --- features/FEATURE_BLE/ble/BLETypes.h | 7 + features/FEATURE_BLE/ble/Gap.h | 110 ++++++- features/FEATURE_BLE/ble/generic/GenericGap.h | 49 ++- .../FEATURE_BLE/source/generic/GenericGap.cpp | 293 ++++++++++++++++++ 4 files changed, 454 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index f720dc01c3..0b5dabbd77 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -55,6 +55,13 @@ typedef uint16_t attribute_handle_t; */ typedef uint8_t advertising_handle_t; +/** + * Handle of a sync representing a periodic advertiser. + * + * @note Range of valid handle is comprised between 0x0000 and 0xFFFF. + */ +typedef uint16_t periodic_sync_handle_t; + /** * Inclusive range of GATT attributes handles. * diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9755d5c43a..b6f930e38a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1124,6 +1124,7 @@ public: GapShutdownCallbackChain_t; typedef ble::advertising_handle_t AdvHandle_t; + typedef ble::periodic_sync_handle_t PeriodicSyncHandle_t; typedef ble::advertising_event_t AdvertisingEventType_t; static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; @@ -1753,11 +1754,52 @@ public: } virtual bool isAdvertisingActive(AdvHandle_t handle) const { - if (handle != LEGACY_ADVERTISING_HANDLE) { - return false; - } + return false; + } + + virtual ble_error_t setPeriodicAdvertisingParameters( + AdvHandle_t handle, + uint16_t periodicAdvertisingIntervalMinMs, + uint16_t periodicAdvertisingIntervalMaxMs, + bool advertiseTxPower = true + ) { + (void) handle; + (void) periodicAdvertisingIntervalMinMs; + (void) periodicAdvertisingIntervalMaxMs; + (void) advertiseTxPower; /* Requesting action from porter(s): override this API if this capability is supported. */ - return state.advertising; + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t setPeriodicAdvertisingData( + AdvHandle_t handle, + mbed::Span payload + ) { + (void) handle; + (void) payload; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle) + { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle) + { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle) + { + (void) handle; + /* Requesting action from porter(s): override this API if this capability is supported. */ + return false; } /* scanning */ @@ -1776,9 +1818,69 @@ public: uint16_t period = 0 ) { use_non_deprecated_scan_api(); + /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; }; + virtual ble_error_t createSync( + PeerAddressType_t peerAddressType, + Address_t peerAddress, + uint8_t sid, + uint16_t maxPacketSkip, + uint32_t timeoutMs + ) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t createSync( + uint16_t maxPacketSkip, + uint32_t timeoutMs + ) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t cancelCreateSync() + { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle) + { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t addDeviceToPeriodicAdvertiserList( + PeerAddressType_t peerAddressType, + Address_t peerAddress, + uint8_t sid + ) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( + PeerAddressType_t peerAddressType, + Address_t peerAddress, + uint8_t sid + ) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual ble_error_t clearPeriodicAdvertiserList() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + + virtual uint8_t getMaxPeriodicAdvertiserListSize() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0; + } + protected: /* Override the following in the underlying adaptation layer to provide the * functionality of scanning. */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index f41f079ded..d0ac3bd61a 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -114,7 +114,23 @@ public: bool isAdvertisingActive(AdvHandle_t handle) const; - void init_extended_advertising(); + virtual ble_error_t setPeriodicAdvertisingParameters( + AdvHandle_t handle, + uint16_t periodicAdvertisingIntervalMinMs, + uint16_t periodicAdvertisingIntervalMaxMs, + bool advertiseTxPower + ); + + virtual ble_error_t setPeriodicAdvertisingData( + AdvHandle_t handle, + mbed::Span payload + ); + + virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle); + + virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle); + + virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle); virtual ble_error_t setScanParameters(const GapScanParameters ¶ms); @@ -124,6 +140,36 @@ public: uint16_t period_ms ); + virtual ble_error_t createSync( + PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid, + uint16_t maxPacketSkip, + uint32_t timeoutMs + ); + + virtual ble_error_t createSync(uint16_t maxPacketSkip, uint32_t timeoutMs); + + virtual ble_error_t cancelCreateSync(); + + virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle); + + virtual ble_error_t addDeviceToPeriodicAdvertiserList( + PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid + ); + + virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( + PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid + ); + + virtual ble_error_t clearPeriodicAdvertiserList(); + + virtual uint8_t getMaxPeriodicAdvertiserListSize(); + /** * @see Gap::setAddress */ @@ -595,6 +641,7 @@ private: BitArray _existing_sets; BitArray _active_sets; + BitArray _active_periodic_sets; // deprecation flags mutable bool _deprecated_scan_api_used : 1; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0dc1c650d9..820a2e8fcf 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1893,6 +1893,143 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { return _active_sets.get(handle); } +ble_error_t GenericGap::setPeriodicAdvertisingParameters( + Gap::AdvHandle_t handle, + uint16_t periodicAdvertisingIntervalMinMs, + uint16_t periodicAdvertisingIntervalMaxMs, + bool advertiseTxPower +) +{ + uint16_t interval_min = (periodicAdvertisingIntervalMinMs * 100) / 125; + uint16_t interval_max = (periodicAdvertisingIntervalMinMs * 100) / 125; + + if (interval_min < 6) { + return BLE_ERROR_INVALID_PARAM; + } + + if (interval_max < 6) { + return BLE_ERROR_INVALID_PARAM; + } + + if (interval_min > interval_max) { + return BLE_ERROR_INVALID_PARAM; + } + + if (handle == LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + if (!_existing_sets.get(handle)) { + return BLE_ERROR_INVALID_STATE; + } + + return _pal_gap.set_periodic_advertising_parameters( + handle, + interval_min, + interval_max, + advertiseTxPower + ); +} + +ble_error_t GenericGap::setPeriodicAdvertisingData( + Gap::AdvHandle_t handle, + mbed::Span payload +) +{ + if (handle == LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + if (!_existing_sets.get(handle)) { + return BLE_ERROR_INVALID_STATE; + } + + typedef pal::advertising_fragment_description_t op_t; + + for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { + // select the operation based on the index + op_t op(op_t::INTERMEDIATE_FRAGMENT); + if (end < MAX_HCI_DATA_LENGTH) { + op = op_t::COMPLETE_FRAGMENT; + } else if (i == 0) { + op = op_t::FIRST_FRAGMENT; + } else if ((end - i) <= MAX_HCI_DATA_LENGTH) { + op = op_t::LAST_FRAGMENT; + } + + // extract the payload + mbed::Span sub_payload = payload.subspan( + i, + std::min(MAX_HCI_DATA_LENGTH, (end - i)) + ); + + ble_error_t err = _pal_gap.set_periodic_advertising_data( + handle, + op, + sub_payload.size(), + sub_payload.data() + ); + + if (err) { + return err; + } + } + + return BLE_ERROR_NONE; +} + +ble_error_t GenericGap::startPeriodicAdvertising(Gap::AdvHandle_t handle) +{ + if (handle == LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + if (!_existing_sets.get(handle)) { + return BLE_ERROR_INVALID_STATE; + } + + if (_active_periodic_sets.get(handle) == true) { + return BLE_ERROR_INVALID_STATE; + } + + ble_error_t err = _pal_gap.periodic_advertising_enable(true, handle); + if (err) { + return err; + } + + _active_periodic_sets.set(handle); + return BLE_ERROR_NONE; +} + +ble_error_t GenericGap::stopPeriodicAdvertising(Gap::AdvHandle_t handle) +{ + if (handle == LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + if (!_existing_sets.get(handle)) { + return BLE_ERROR_INVALID_STATE; + } + + if (_active_periodic_sets.get(handle) == false) { + return BLE_ERROR_INVALID_STATE; + } + + + ble_error_t err = _pal_gap.periodic_advertising_enable(false, handle); + if (err) { + return err; + } + + _active_periodic_sets.clear(handle); + return BLE_ERROR_NONE; +} + +bool GenericGap::isPeriodicAdvertisingActive(Gap::AdvHandle_t handle) +{ + return _active_periodic_sets.get(handle); +} + void GenericGap::on_enhanced_connection_complete( pal::hci_error_code_t status, connection_handle_t connection_handle, @@ -2096,6 +2233,162 @@ ble_error_t GenericGap::startScan( } } +ble_error_t GenericGap::createSync( + Gap::PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid, + uint16_t maxPacketSkip, + uint32_t timeoutMs +) +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + if (peerAddressType != PeerAddressType_t::PUBLIC || + peerAddressType != PeerAddressType_t::RANDOM + ) { + return BLE_ERROR_INVALID_PARAM; + } + + if (sid > 0x0F) { + return BLE_ERROR_INVALID_PARAM; + } + + if (maxPacketSkip > 0x1F3) { + return BLE_ERROR_INVALID_PARAM; + } + + uint32_t timeout = timeoutMs / 10; + if (timeout < 0x000A || timeout > 0x4000) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.periodic_advertising_create_sync( + /* use advertiser list */ false, + sid, + (peer_address_type_t::type) peerAddressType.value(), + peerAddress, + maxPacketSkip, + timeout + ); +} + +ble_error_t GenericGap::createSync(uint16_t maxPacketSkip, uint32_t timeoutMs) +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + if (maxPacketSkip > 0x1F3) { + return BLE_ERROR_INVALID_PARAM; + } + + uint32_t timeout = timeoutMs / 10; + if (timeout < 0x000A || timeout > 0x4000) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.periodic_advertising_create_sync( + /* use advertiser list */ true, + /* sid - not used */ 0x00, + /* N/A */ peer_address_type_t::PUBLIC, + /* N/A */ ble::address_t(), + maxPacketSkip, + timeout + ); +} + +ble_error_t GenericGap::cancelCreateSync() +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + return _pal_gap.cancel_periodic_advertising_create_sync(); +} + +ble_error_t GenericGap::terminateSync(Gap::PeriodicSyncHandle_t handle) +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + return _pal_gap.periodic_advertising_terminate_sync(handle); +} + +ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( + Gap::PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid +) +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + if (peerAddressType != PeerAddressType_t::PUBLIC || + peerAddressType != PeerAddressType_t::RANDOM + ) { + return BLE_ERROR_INVALID_PARAM; + } + + if (sid > 0x0F) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.add_device_to_periodic_advertiser_list( + (pal::advertising_peer_address_type_t::type) peerAddressType.value(), + peerAddress, + sid + ); +} + +ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( + Gap::PeerAddressType_t peerAddressType, + uint8_t *peerAddress, + uint8_t sid +) +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + if (peerAddressType != PeerAddressType_t::PUBLIC || + peerAddressType != PeerAddressType_t::RANDOM + ) { + return BLE_ERROR_INVALID_PARAM; + } + + if (sid > 0x0F) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.remove_device_from_periodic_advertiser_list( + (pal::advertising_peer_address_type_t::type) peerAddressType.value(), + peerAddress, + sid + ); +} + +ble_error_t GenericGap::clearPeriodicAdvertiserList() +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + return _pal_gap.clear_periodic_advertiser_list(); +} + +uint8_t GenericGap::getMaxPeriodicAdvertiserListSize() +{ + if (is_extended_advertising_available() == false) { + return BLE_ERROR_NOT_IMPLEMENTED; + } + + return _pal_gap.read_periodic_advertiser_list_size(); +} + void GenericGap::use_deprecated_scan_api() const { if (_non_deprecated_scan_api_used) { From eefdc638f717fe2c7b930c15f150763fbe1691e8 Mon Sep 17 00:00:00 2001 From: Paul Szczepanek Date: Sun, 11 Nov 2018 14:44:41 +0000 Subject: [PATCH 088/361] BLE: fix condition in advertising set allocation. Co-Authored-By: pan- --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 820a2e8fcf..05c99d265d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1597,7 +1597,7 @@ ble_error_t GenericGap::createAdvertisingSet( uint8_t end = getMaxAdvertisingSetNumber(); for (; new_handle < end; ++new_handle) { - if (_existing_sets.get(new_handle)) { + if (!_existing_sets.get(new_handle)) { ble_error_t err = setExtendedAdvertisingParameters( new_handle, parameters From 01b0de2175ded9b1ce3b8b1e747e15337bcd9585 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 14:39:53 +0000 Subject: [PATCH 089/361] BLE: rename Gap:setPeriodicAdvertisingData into setPeriodicAdvertisingPayload. --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index b6f930e38a..9e384ab330 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1771,7 +1771,7 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual ble_error_t setPeriodicAdvertisingData( + virtual ble_error_t setPeriodicAdvertisingPayload( AdvHandle_t handle, mbed::Span payload ) { diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index d0ac3bd61a..12421b7dd6 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -121,7 +121,7 @@ public: bool advertiseTxPower ); - virtual ble_error_t setPeriodicAdvertisingData( + virtual ble_error_t setPeriodicAdvertisingPayload( AdvHandle_t handle, mbed::Span payload ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 05c99d265d..6ce825aec5 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1931,7 +1931,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( ); } -ble_error_t GenericGap::setPeriodicAdvertisingData( +ble_error_t GenericGap::setPeriodicAdvertisingPayload( Gap::AdvHandle_t handle, mbed::Span payload ) From 24e6b89ade0b554782bf00bcaf3e59624a81e9c2 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 14:41:34 +0000 Subject: [PATCH 090/361] BLE: use uint32_t to describe ms interval in Gap::setPeriodicAdvertisingParameters --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9e384ab330..8179144253 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1759,8 +1759,8 @@ public: virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - uint16_t periodicAdvertisingIntervalMinMs, - uint16_t periodicAdvertisingIntervalMaxMs, + uint32_t periodicAdvertisingIntervalMinMs, + uint32_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower = true ) { (void) handle; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 12421b7dd6..d81cfd2a09 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -116,8 +116,8 @@ public: virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - uint16_t periodicAdvertisingIntervalMinMs, - uint16_t periodicAdvertisingIntervalMaxMs, + uint32_t periodicAdvertisingIntervalMinMs, + uint32_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 6ce825aec5..3f9cf5218f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1895,8 +1895,8 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { ble_error_t GenericGap::setPeriodicAdvertisingParameters( Gap::AdvHandle_t handle, - uint16_t periodicAdvertisingIntervalMinMs, - uint16_t periodicAdvertisingIntervalMaxMs, + uint32_t periodicAdvertisingIntervalMinMs, + uint32_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower ) { From 297ad78452a1d3effe3a68aafb9d0feb52233632 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 15:00:21 +0000 Subject: [PATCH 091/361] BLE: check for periodic advertising enabled in GenericGap::destroyAdvertisingSet --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3f9cf5218f..5f4665da87 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1633,6 +1633,10 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } + if (_active_periodic_sets.get(handle)) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } + ble_error_t err = _pal_gap.remove_advertising_set(handle); if (err) { return err; From d23bd2f2680153473b695b99cb853a1781fd51d9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 17:10:56 +0000 Subject: [PATCH 092/361] BLE: Fix compilation error. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 5f4665da87..bdfc07787f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2129,7 +2129,7 @@ void GenericGap::on_advertising_set_terminated( advertising_handle, connection_handle, number_of_completed_extended_advertising_events, - (SUCCESS == status) + status == pal::hci_error_code_t::SUCCESS ); } } From 3eebcc49adcc352a2c85650d0a38536d051d3cb9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 18:02:37 +0000 Subject: [PATCH 093/361] BLE: Add more precondition check to GenericGap. --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 65 +++++++++++++++++-- 3 files changed, 63 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8179144253..03a6407226 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1753,7 +1753,7 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - virtual bool isAdvertisingActive(AdvHandle_t handle) const { + virtual bool isAdvertisingActive(AdvHandle_t handle) { return false; } diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index d81cfd2a09..a83da63caa 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -112,7 +112,7 @@ public: ble_error_t stopAdvertising(AdvHandle_t handle); - bool isAdvertisingActive(AdvHandle_t handle) const; + bool isAdvertisingActive(AdvHandle_t handle); virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index bdfc07787f..ed1256449a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1650,6 +1650,10 @@ ble_error_t GenericGap::setAdvertisingParams( AdvHandle_t handle, const GapAdvertisingParameters ¶ms ) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1687,6 +1691,10 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( const GapAdvertisingParameters ¶ms ) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + pal::advertising_event_properties_t event_properties( (pal::advertising_type_t::type)params.getType()); event_properties.include_tx_power = params.getTxPowerInHeader(); @@ -1754,6 +1762,10 @@ ble_error_t GenericGap::setAdvertisingData( const uint8_t *scan_response_data ); + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1764,7 +1776,7 @@ ble_error_t GenericGap::setAdvertisingData( return BLE_ERROR_INVALID_PARAM; } - if (payload.size() < GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + if (payload.size() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) { return BLE_ERROR_INVALID_PARAM; } @@ -1780,6 +1792,10 @@ ble_error_t GenericGap::setAdvertisingData( ); } + if (payload.size() > getMaxAdvertisingDataLength()) { + return BLE_ERROR_INVALID_PARAM; + } + // select the pal function set_data_fn_t set_data = scan_response ? &pal::Gap::set_extended_scan_response_data : @@ -1824,6 +1840,10 @@ ble_error_t GenericGap::startAdvertising( uint8_t maxEvents ) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1867,6 +1887,10 @@ ble_error_t GenericGap::startAdvertising( } ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (_existing_sets.get(handle)) { return BLE_ERROR_INVALID_PARAM; } @@ -1893,7 +1917,11 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { ); } -bool GenericGap::isAdvertisingActive(AdvHandle_t handle) const { +bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + return _active_sets.get(handle); } @@ -1907,11 +1935,11 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( uint16_t interval_min = (periodicAdvertisingIntervalMinMs * 100) / 125; uint16_t interval_max = (periodicAdvertisingIntervalMinMs * 100) / 125; - if (interval_min < 6) { + if (interval_min < 6 || interval_min > 0xFFFF) { return BLE_ERROR_INVALID_PARAM; } - if (interval_max < 6) { + if (interval_max < 6 || interval_max > 0xFFFF) { return BLE_ERROR_INVALID_PARAM; } @@ -1923,6 +1951,10 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( return BLE_ERROR_INVALID_PARAM; } + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_STATE; } @@ -1944,10 +1976,18 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( return BLE_ERROR_INVALID_PARAM; } + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_STATE; } + if (payload.size() > getMaxAdvertisingDataLength()) { + return BLE_ERROR_INVALID_PARAM; + } + typedef pal::advertising_fragment_description_t op_t; for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { @@ -1988,10 +2028,19 @@ ble_error_t GenericGap::startPeriodicAdvertising(Gap::AdvHandle_t handle) return BLE_ERROR_INVALID_PARAM; } + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_STATE; } + if (_active_sets.get(handle) == false) { + // FIXME: should we start periodic advertising behind the user's back ? + return BLE_ERROR_INVALID_STATE; + } + if (_active_periodic_sets.get(handle) == true) { return BLE_ERROR_INVALID_STATE; } @@ -2011,6 +2060,10 @@ ble_error_t GenericGap::stopPeriodicAdvertising(Gap::AdvHandle_t handle) return BLE_ERROR_INVALID_PARAM; } + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + if (!_existing_sets.get(handle)) { return BLE_ERROR_INVALID_STATE; } @@ -2031,6 +2084,10 @@ ble_error_t GenericGap::stopPeriodicAdvertising(Gap::AdvHandle_t handle) bool GenericGap::isPeriodicAdvertisingActive(Gap::AdvHandle_t handle) { + if (handle >= getMaxAdvertisingSetNumber()) { + return BLE_ERROR_INVALID_PARAM; + } + return _active_periodic_sets.get(handle); } From 31e028f22ff31ccc56edea671e708d257e39130b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 18:03:06 +0000 Subject: [PATCH 094/361] BLE: fix integer overflow in setPeriodicAdvertisingParameters --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index ed1256449a..65c4481893 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1932,8 +1932,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( bool advertiseTxPower ) { - uint16_t interval_min = (periodicAdvertisingIntervalMinMs * 100) / 125; - uint16_t interval_max = (periodicAdvertisingIntervalMinMs * 100) / 125; + uint32_t interval_min = (periodicAdvertisingIntervalMinMs * 100) / 125; + uint32_t interval_max = (periodicAdvertisingIntervalMaxMs * 100) / 125; if (interval_min < 6 || interval_min > 0xFFFF) { return BLE_ERROR_INVALID_PARAM; From 5661bf6bbb59217c196f3826cd10ed7aaae03366 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 18:21:07 +0000 Subject: [PATCH 095/361] BLE: remove dead code. --- features/FEATURE_BLE/ble/Gap.h | 49 ---------------------------------- 1 file changed, 49 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 03a6407226..9e26856228 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -30,12 +30,6 @@ #include "platform/mbed_toolchain.h" #include "gap/AdvertisingParameters.h" -/* Forward declarations for classes that are only used for pointers or - references. */ -class GapAdvertisingParams; -class GapScanningParams; -class GapAdvertisingData; - /** * @addtogroup ble * @{ @@ -3678,49 +3672,6 @@ private: /* Disallow copy and assignment. */ Gap(const Gap &); Gap& operator=(const Gap &); -#if 0 - - /* ----------------------- anything beyond this line is deprecated ------------------------- */ - - /* backwards compatibility with deprecated functions */ - -protected: - GapAdvertisingParams& getLegacyAdvertisingParams() { - if (!_advParams) { - _advParams = new GapAdvertisingParams(); - } - MBED_ASSERT(_advParams); - /* this setting is now read from the params */ - _advParams->setPolicyMode(getAdvertisingPolicyMode()); - return *_advParams; - } - - GapAdvertisingData& getLegacyAdvertisingPayload() { - if (!_advPayload) { - _advPayload = new GapAdvertisingData(); - } - MBED_ASSERT(_advPayload); - return *_advPayload; - } - - GapAdvertisingData& getLegacyAdvertisingScanResponse() { - if (!_scanResponse) { - _scanResponse = new GapAdvertisingData(); - } - MBED_ASSERT(_scanResponse); - return *_scanResponse; - } - - void legacyAdvertisingReset() { - delete _advParams; - _advParams = NULL; - delete _advPayload; - _advPayload = NULL; - delete _scanResponse; - _scanResponse = NULL; - } -#endif - }; /** From 651bf321dbcbdd8fe671932fcb44e43aaaa5ed93 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 11 Nov 2018 18:22:02 +0000 Subject: [PATCH 096/361] BLE: Use typedef in signature. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index a83da63caa..66aa7d7483 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -156,7 +156,7 @@ public: virtual ble_error_t addDeviceToPeriodicAdvertiserList( PeerAddressType_t peerAddressType, - uint8_t *peerAddress, + Address_t peerAddress, uint8_t sid ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 65c4481893..3f64494b51 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2380,7 +2380,7 @@ ble_error_t GenericGap::terminateSync(Gap::PeriodicSyncHandle_t handle) ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( Gap::PeerAddressType_t peerAddressType, - uint8_t *peerAddress, + Address_t peerAddress, uint8_t sid ) { From 2f8e336635f4d8175272e88d1fd066d4ed6d352c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 12 Nov 2018 11:56:08 +0000 Subject: [PATCH 097/361] BLE: tag missing documentation block. --- features/FEATURE_BLE/ble/BLETypes.h | 102 ++++++++++++++ features/FEATURE_BLE/ble/Gap.h | 198 +++++++++++++++++++++++++++- 2 files changed, 298 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 0b5dabbd77..45712ce492 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -175,7 +175,13 @@ enum advertising_type_t { ADV_CONNECTABLE_DIRECTED_LOW_DUTY }; +/** + * FIXME + */ struct advertising_data_status_t : SafeEnum{ + /** + * FIXME + */ enum type { COMPLETE = 0x00, INCOMPLETE_MORE_DATA = 0x01, @@ -198,9 +204,20 @@ struct advertising_data_status_t : SafeEnum(value & (1 << 0)); } + /** + * FIXME + * @param v + * @return + */ advertising_event_t& connectable(bool v) { if (v) { @@ -239,11 +268,20 @@ struct advertising_event_t { return *this; } + /** + * FIXME + * @return + */ bool scannable_advertising() const { return static_cast(value & (1 << 1)); } + /** + * FIXME + * @param v + * @return + */ advertising_event_t& scannable_advertising(bool v) { if (v) { @@ -254,11 +292,20 @@ struct advertising_event_t { return *this; } + /** + * FIXME + * @return + */ bool directed_advertising() const { return static_cast(value & (1 << 2)); } + /** + * FIXME + * @param v + * @return + */ advertising_event_t& directed_advertising(bool v) { if (v) { @@ -269,11 +316,20 @@ struct advertising_event_t { return *this; } + /** + * FIXME + * @return + */ bool scan_response() const { return static_cast(value & (1 << 3)); } + /** + * FIXME + * @param v + * @return + */ advertising_event_t& scan_response(bool v) { if (v) { @@ -284,11 +340,20 @@ struct advertising_event_t { return *this; } + /** + * FIXME + * @return + */ bool legacy_advertising() const { return static_cast(value & (1 << 4)); } + /** + * FIXME + * @param v + * @return + */ advertising_event_t& legacy_advertising(bool v) { if (v) { @@ -299,26 +364,48 @@ struct advertising_event_t { return *this; } + /** + * FIXME + * @return + */ advertising_data_status_t data_status() const { return static_cast((value >> 5) & 0x03); } + /** + * FIXME + * @return + */ bool complete() const { return data_status() == advertising_data_status_t::COMPLETE; } + /** + * FIXME + * @return + */ bool more_data_to_come() const { return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; } + /** + * FIXME + * @return + */ bool truncated() const { return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; } + /** + * FIXME + * @param lhs + * @param rhs + * @return + */ friend bool operator==( const advertising_event_t &lhs, const advertising_event_t &rhs @@ -327,6 +414,12 @@ struct advertising_event_t { return lhs.value == rhs.value; } + /** + * FIXME + * @param lhs + * @param rhs + * @return + */ friend bool operator!=( const advertising_event_t &lhs, const advertising_event_t &rhs @@ -391,8 +484,17 @@ enum scanning_policy_mode_t { * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. */ enum scanning_filter_duplicates_t { + /** + * FIXME + */ SCAN_FILTER_DUPLICATES_DISABLED = 0, + /** + * FIXME + */ SCAN_FILTER_DUPLICATES_ENABLED = 1, + /** + * FIXME + */ SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 }; diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9e26856228..3ac8b8e151 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1117,18 +1117,41 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; + /** + * FIXME + */ typedef ble::advertising_handle_t AdvHandle_t; + + /** + * FIXME + */ typedef ble::periodic_sync_handle_t PeriodicSyncHandle_t; + + /** + * FIXME + */ typedef ble::advertising_event_t AdvertisingEventType_t; + /** + * FIXME + */ static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; + + /** + * FIXME + */ static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; /** * Definition of the general handler of Gap related events. */ struct EventHandler { - + /** + * FIXME + * @param advHandle + * @param peerAddressType + * @param peerAddress + */ virtual void onScanRequest( AdvHandle_t advHandle, PeerAddressType_t peerAddressType, @@ -1139,6 +1162,13 @@ public: (void) peerAddress; } + /** + * FIXME + * @param advHandle + * @param connection + * @param completed_events + * @param connected + */ virtual void onAdvertisingEnd( AdvHandle_t advHandle, Handle_t connection, @@ -1151,6 +1181,21 @@ public: (void) connected; } + /** + * FIXME + * @param type + * @param peerAddressType + * @param peerAddress + * @param primaryPhy + * @param secondaryPhy + * @param SID + * @param txPower + * @param rssi + * @param periodicInterval + * @param directAddressType + * @param directAddress + * @param advertisingData + */ void onAdvertisingReport( AdvertisingEventType_t type, PeerAddressType_t peerAddressType, @@ -1668,16 +1713,30 @@ public: /* advertising */ + /** + * FIXME + * @return + */ virtual uint8_t getMaxAdvertisingSetNumber() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 1; } + /** + * FIXME + * @return + */ virtual uint8_t getMaxAdvertisingDataLength() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 0x1F; } + /** + * FIXME + * @param handle + * @param parameters + * @return + */ virtual ble_error_t createAdvertisingSet( AdvHandle_t *handle, const GapAdvertisingParameters ¶meters @@ -1688,12 +1747,23 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @return + */ virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @param params + * @return + */ virtual ble_error_t setAdvertisingParams( AdvHandle_t handle, const GapAdvertisingParameters ¶ms @@ -1704,6 +1774,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @param payload + * @param minimiseFragmentation + * @return + */ virtual ble_error_t setAdvertisingPayload( AdvHandle_t handle, mbed::Span payload, @@ -1716,6 +1793,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @param response + * @param minimiseFragmentation + * @return + */ virtual ble_error_t setAdvertisingScanResponse( AdvHandle_t handle, mbed::Span response, @@ -1729,6 +1813,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @param maxDuration + * @param maxEvents + * @return + */ virtual ble_error_t startAdvertising( AdvHandle_t handle, uint32_t maxDuration = 0, @@ -1740,17 +1831,35 @@ public: /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - + + /** + * FIXME + * @param handle + * @return + */ virtual ble_error_t stopAdvertising(AdvHandle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @return + */ virtual bool isAdvertisingActive(AdvHandle_t handle) { return false; } + /** + * FIXME + * @param handle + * @param periodicAdvertisingIntervalMinMs + * @param periodicAdvertisingIntervalMaxMs + * @param advertiseTxPower + * @return + */ virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, uint32_t periodicAdvertisingIntervalMinMs, @@ -1765,6 +1874,12 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @param payload + * @return + */ virtual ble_error_t setPeriodicAdvertisingPayload( AdvHandle_t handle, mbed::Span payload @@ -1775,6 +1890,11 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @return + */ virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle) { (void) handle; @@ -1782,6 +1902,11 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @return + */ virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle) { (void) handle; @@ -1789,6 +1914,11 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param handle + * @return + */ virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle) { (void) handle; @@ -1798,6 +1928,11 @@ public: /* scanning */ + /** + * FIXME + * @param params + * @return + */ virtual ble_error_t setScanParameters( const GapScanParameters& params ) { @@ -1806,6 +1941,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; }; + /** + * FIXME + * @param filtering + * @param duration + * @param period + * @return + */ virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, uint16_t duration = 0, @@ -1816,6 +1958,15 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; }; + /** + * FIXME + * @param peerAddressType + * @param peerAddress + * @param sid + * @param maxPacketSkip + * @param timeoutMs + * @return + */ virtual ble_error_t createSync( PeerAddressType_t peerAddressType, Address_t peerAddress, @@ -1827,6 +1978,12 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param maxPacketSkip + * @param timeoutMs + * @return + */ virtual ble_error_t createSync( uint16_t maxPacketSkip, uint32_t timeoutMs @@ -1835,18 +1992,32 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @return + */ virtual ble_error_t cancelCreateSync() { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + */ virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param peerAddressType + * @param peerAddress + * @param sid + * @return + */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( PeerAddressType_t peerAddressType, Address_t peerAddress, @@ -1856,6 +2027,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @param peerAddressType + * @param peerAddress + * @param sid + * @return + */ virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( PeerAddressType_t peerAddressType, Address_t peerAddress, @@ -1865,11 +2043,19 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @return + */ virtual ble_error_t clearPeriodicAdvertiserList() { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } + /** + * FIXME + * @return + */ virtual uint8_t getMaxPeriodicAdvertiserListSize() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 0; @@ -1878,7 +2064,15 @@ public: protected: /* Override the following in the underlying adaptation layer to provide the * functionality of scanning. */ + + /** + * FIXME + */ virtual void use_deprecated_scan_api() const { } + + /** + * FIXME + */ virtual void use_non_deprecated_scan_api() const { } public: From afadc1d8c063696e8c0671dd086cd5624bd88013 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 17:19:22 +0000 Subject: [PATCH 098/361] convert to correct time units --- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 99322cb574..9069deae4d 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -176,6 +176,9 @@ public: _timeout = GAP_ADV_PARAMS_TIMEOUT_MAX; } } + + _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(_minInterval); + _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(_maxInterval); } public: From 4c4743db7bb06cc83f57626cb7e3c56bf432213c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 19:15:02 +0000 Subject: [PATCH 099/361] extended connection API --- features/FEATURE_BLE/ble/BLETypes.h | 22 ++++ features/FEATURE_BLE/ble/Gap.h | 36 +++--- .../ble/gap/AdvertisingParameters.h | 40 ++----- .../ble/gap/ExtendedConnectParameters.h | 109 ++++++++++++++++++ 4 files changed, 163 insertions(+), 44 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 45712ce492..bbe3dc2ad9 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -955,6 +955,28 @@ struct peer_address_type_t :SafeEnum { SafeEnum(PUBLIC) { } }; +struct own_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address. */ + RANDOM, /**< Random Device Address. */ + RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use the public address. */ + RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use previously set random address. */ + }; + own_address_type_t(type value) : ble::SafeEnum(value) { } +}; + +struct target_peer_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ + RANDOM /**< Random Device Address or Random (static) Identity Address. */ + }; + target_peer_address_type_t(type value) : ble::SafeEnum(value) { } +}; + /** * Type that describes a bluetooth PHY(sical) transport. */ diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 3ac8b8e151..3be484d9f7 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -21,6 +21,7 @@ #include "BLEProtocol.h" #include "GapAdvertisingData.h" #include "ble/gap/AdvertisingDataBuilder.h" +#include "ble/gap/ExtendedConnectParameters.h" #include "GapAdvertisingParams.h" #include "GapScanningParams.h" #include "GapEvents.h" @@ -564,6 +565,21 @@ public: */ typedef ble::peer_address_type_t PeerAddressType_t; + /** + * Enumeration of own address types + */ + typedef ble::own_address_type_t OwnAddressType_t; + + /** + * Enumeration of peer address types + */ + typedef ble::target_peer_address_type_t TargetPeerAddressType_t; + + /** + * Scanning filter policy based on the whitelist + */ + typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; + /** * Enumeration of BLE PHY */ @@ -1513,23 +1529,17 @@ public: * a connection event. */ virtual ble_error_t connect( - const BLEProtocol::AddressBytes_t peerAddr, - PeerAddressType_t peerAddrType, - const ConnectionParams_t *connectionParams1M, - const GapScanningParams *scanParams1M, - const ConnectionParams_t *connectionParams2M = NULL, - const GapScanningParams *scanParams2M = NULL, - const ConnectionParams_t *connectionParamsCoded = NULL, - const GapScanningParams *scanParamsCoded = NULL + TargetPeerAddressType_t peerAddressType, + const BLEProtocol::AddressBytes_t peerAddress, + const ExtendedConnectParameters_t &connectionParams ) { - (void)peerAddr; - (void)peerAddrType; + (void)filterPolicy; + (void)ownAddressType; + (void)peerAddressType; + (void)peerAddress; (void)connectionParams1M; - (void)scanParams1M; (void)connectionParams2M; - (void)scanParams2M; (void)connectionParamsCoded; - (void)scanParamsCoded; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 9069deae4d..5c0a563fa5 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -95,28 +95,6 @@ public: static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; - struct own_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address. */ - RANDOM, /**< Random Device Address. */ - RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use the public address. */ - RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use previously set random address. */ - }; - own_address_type_t(type value) : ble::SafeEnum(value) { } - }; - - struct peer_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ - RANDOM /**< Random Device Address or Random (static) Identity Address. */ - }; - peer_address_type_t(type value) : ble::SafeEnum(value) { } - }; - public: /** * Construct an instance of GapAdvertisingParams. @@ -139,8 +117,8 @@ public: _minInterval(minInterval), _maxInterval(maxInterval), _timeout(timeout), - _peerAddressType(peer_address_type_t::PUBLIC), - _ownAddressType(own_address_type_t::PUBLIC), + _peerAddressType(ble::target_peer_address_type_t::PUBLIC), + _ownAddressType(ble::own_address_type_t::PUBLIC), _policy(ble::ADV_POLICY_IGNORE_WHITELIST), _primaryPhy(ble::phy_t::LE_1M), _secondaryPhy(ble::phy_t::LE_1M), @@ -422,14 +400,14 @@ public: * * @return Addres tpe used. */ - own_address_type_t getOwnAddressType() const { + ble::own_address_type_t getOwnAddressType() const { return _ownAddressType; } /** Get what type of address is to be used as your own address during advertising. */ void setOwnAddressType( - own_address_type_t addressType + ble::own_address_type_t addressType ) { _ownAddressType = addressType; } @@ -443,7 +421,7 @@ public: */ ble_error_t getPeer( BLEProtocol::AddressBytes_t *address, - peer_address_type_t *addressType + ble::target_peer_address_type_t *addressType ) const { if (!address || !addressType) { return BLE_ERROR_INVALID_PARAM; @@ -460,7 +438,7 @@ public: */ void setPeer( const BLEProtocol::AddressBytes_t address, - peer_address_type_t addressType + ble::target_peer_address_type_t addressType ) { memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); _peerAddressType = addressType; @@ -650,7 +628,7 @@ public: * * @return Peer address type. */ - peer_address_type_t getPeerAddressType() const { + ble::target_peer_address_type_t getPeerAddressType() const { return _peerAddressType; }; @@ -704,8 +682,8 @@ private: uint32_t _maxInterval; /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ uint16_t _timeout; - peer_address_type_t _peerAddressType; - own_address_type_t _ownAddressType; + ble::target_peer_address_type_t _peerAddressType; + ble::own_address_type_t _ownAddressType; ble::advertising_policy_mode_t _policy; ble::phy_t _primaryPhy; ble::phy_t _secondaryPhy; diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h new file mode 100644 index 0000000000..c5eab4a744 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -0,0 +1,109 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef MBED_EXTENDED_CONNECT_PARAMETERS_H__ +#define MBED_EXTENDED_CONNECT_PARAMETERS_H__ + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +class ExtendedConnectParameters_t { + const size_t MAX_PARAM_PHYS = 3; +public: + ExtendedConnectParameters_t() : + _filterPolicy(ble::scanning_policy_mode_t::SCAN_POLICY_FILTER_ALL_ADV), + _ownAddressType(ble::own_address_type_t::PUBLIC) + { + for (int i = 0; i < MAX_PARAM_PHYS; ++i) { + _scanInterval[i] = 4; + _scanWindow[i] = 4; + _minConnectionInterval[i] = 6; + _maxConnectionInterval[i] = 6; + _slaveLatency[i] = 0; + _connectionSupervisionTimeout[i] = 0xC80; + _minimumEventLength[i] = 0; + _maximumEventLength[i] = 0xFFFF; + } + }; + + ExtendedConnectParameters_t& setScanParamteres( + uint32_t scanInterval, + uint32_t scanWindow, + ble::phy_t phy = ble::phy_t::LE_1M + ) { + _enabledPhy[phy] = true; + scanInterval = scanInterval[phy]; + scanWindow = scanWindow[phy]; + return *this; + } + + ExtendedConnectParameters_t& setConnectionParamteres( + uint16_t minConnectionInterval, + uint16_t maxConnectionInterval, + uint16_t slaveLatency, + uint16_t connectionSupervisionTimeout, + uint32_t _minimumEventLength, + uint32_t _maximumEventLength, + ble::phy_t phy = ble::phy_t::LE_1M + ) { + _enabledPhy[phy] = true; + _minConnectionInterval = minConnectionInterval[phy]; + maxConnectionInterval = maxConnectionInterval[phy]; + slaveLatency = slaveLatency[phy]; + connectionSupervisionTimeout = connectionSupervisionTimeout[phy]; + _minimumEventLength = _minimumEventLength[phy]; + _maximumEventLength = _maximumEventLength[phy]; + return *this; + } + + ExtendedConnectParameters_t& setScanParamteres( + ble::own_address_type_t ownAddress + ) { + _ownAddressType = ownAddress; + return *this; + } + + ExtendedConnectParameters_t& setScanParamteres( + ble::scanning_policy_mode_t filterPolicy + ) { + _filterPolicy = filterPolicy; + return *this; + } + +private: + ble::scanning_policy_mode_t _filterPolicy; + ble::own_address_type_t _ownAddressType; + uint32_t _scanInterval[MAX_PARAM_PHYS]; + uint32_t _scanWindow[MAX_PARAM_PHYS]; + uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; + uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; + uint16_t _slaveLatency[MAX_PARAM_PHYS]; + uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; + uint32_t _minimumEventLength[MAX_PARAM_PHYS]; + uint32_t _maximumEventLength[MAX_PARAM_PHYS]; + bool _enabledPhy[MAX_PARAM_PHYS]; +}; + +/** + * @} + * @} + */ + +#endif /* ifndef MBED_EXTENDED_CONNECT_PARAMETERS_H__ */ From d00a92d10f6102c0ec7fbfa8b4a12c86f2d33d4f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 19:16:42 +0000 Subject: [PATCH 100/361] init param to false until user changes it --- features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index c5eab4a744..3a76bb88d5 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -40,6 +40,7 @@ public: _connectionSupervisionTimeout[i] = 0xC80; _minimumEventLength[i] = 0; _maximumEventLength[i] = 0xFFFF; + _enabledPhy[i] = false; } }; From 713b5c7e10817630964e8a590882e9a564fc956c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 19:30:40 +0000 Subject: [PATCH 101/361] add ability to disable phy --- .../ble/gap/ExtendedConnectParameters.h | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 3a76bb88d5..5bd4ccfecb 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -88,6 +88,31 @@ public: return *this; } + ExtendedConnectParameters_t& togglePhy( + bool phy1M, + bool phy2M, + bool phyCoded, + ) { + _enabledPhy[ble::phy_t::LE_1M] = phy1M; + _enabledPhy[ble::phy_t::LE_2M] = phy2M; + _enabledPhy[ble::phy_t::LE_CODED] = phyCoded; + return *this; + } + + ExtendedConnectParameters_t& disablePhy( + ble::phy_t phy = ble::phy_t::LE_1M + ) { + _enabledPhy[phy] = false; + return *this; + } + + ExtendedConnectParameters_t& enablePhy( + ble::phy_t phy = ble::phy_t::LE_1M + ) { + _enabledPhy[phy] = false; + return *this; + } + private: ble::scanning_policy_mode_t _filterPolicy; ble::own_address_type_t _ownAddressType; From edb645b4923055dd4f5402e8582a016c7fe02455 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:09:25 +0000 Subject: [PATCH 102/361] handle creating contiguous arrays for the pal call --- .../ble/gap/ExtendedConnectParameters.h | 147 ++++++++++++++++-- 1 file changed, 132 insertions(+), 15 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 5bd4ccfecb..da0a81d989 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -49,9 +49,11 @@ public: uint32_t scanWindow, ble::phy_t phy = ble::phy_t::LE_1M ) { - _enabledPhy[phy] = true; - scanInterval = scanInterval[phy]; - scanWindow = scanWindow[phy]; + uint8_t phy_index = handlePhyToggle(phy, true); + + scanInterval = scanInterval[phy_index]; + scanWindow = scanWindow[phy_index]; + return *this; } @@ -64,13 +66,15 @@ public: uint32_t _maximumEventLength, ble::phy_t phy = ble::phy_t::LE_1M ) { - _enabledPhy[phy] = true; - _minConnectionInterval = minConnectionInterval[phy]; - maxConnectionInterval = maxConnectionInterval[phy]; - slaveLatency = slaveLatency[phy]; - connectionSupervisionTimeout = connectionSupervisionTimeout[phy]; - _minimumEventLength = _minimumEventLength[phy]; - _maximumEventLength = _maximumEventLength[phy]; + uint8_t phy_index = handlePhyToggle(phy, true); + + _minConnectionInterval = minConnectionInterval[phy_index]; + maxConnectionInterval = maxConnectionInterval[phy_index]; + slaveLatency = slaveLatency[phy_index]; + connectionSupervisionTimeout = connectionSupervisionTimeout[phy_index]; + _minimumEventLength = _minimumEventLength[phy_index]; + _maximumEventLength = _maximumEventLength[phy_index]; + return *this; } @@ -78,6 +82,7 @@ public: ble::own_address_type_t ownAddress ) { _ownAddressType = ownAddress; + return *this; } @@ -85,6 +90,7 @@ public: ble::scanning_policy_mode_t filterPolicy ) { _filterPolicy = filterPolicy; + return *this; } @@ -93,29 +99,139 @@ public: bool phy2M, bool phyCoded, ) { - _enabledPhy[ble::phy_t::LE_1M] = phy1M; - _enabledPhy[ble::phy_t::LE_2M] = phy2M; - _enabledPhy[ble::phy_t::LE_CODED] = phyCoded; + handlePhyToggle(ble::phy_t::LE_1M, phy1M); + handlePhyToggle(ble::phy_t::LE_2M, phy2M); + handlePhyToggle(ble::phy_t::LE_CODED, phyCoded); + return *this; } ExtendedConnectParameters_t& disablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { - _enabledPhy[phy] = false; + handlePhyToggle(phy, false); + return *this; } ExtendedConnectParameters_t& enablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { - _enabledPhy[phy] = false; + handlePhyToggle(phy, true); + return *this; } + uint32_t* getScanIntervalArray() { + return &_scanInterval[getFirstEnabledPhy()]; + } + + uint32_t* getScanWindowArray() { + return &_scanWindow[getFirstEnabledPhy()]; + } + + uint32_t* getMinConnectionIntervalArray() { + return &_minConnectionInterval[getFirstEnabledPhy()]; + } + + uint32_t* getMaxConnectionIntervalArray() { + return &_maxConnectionInterval[getFirstEnabledPhy()]; + } + + uint32_t* getSlaveLatencyArray() { + return &_slaveLatency[getFirstEnabledPhy()]; + } + + uint32_t* getConnectionSupervisionTimeoutArray() { + return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; + } + + uint32_t* getMinimumEventLengthArray() { + return &_minimumEventLength[getFirstEnabledPhy()]; + } + + uint32_t* getMaximumEventLengthArray() { + return &_maximumEventLength[getFirstEnabledPhy()]; + } + + uint8_t getNumberOfEnabledPhys() { + return (_enabledPhy[ble::phy_t::LE_1M] * 1 + + _enabledPhy[ble::phy_t::LE_2M] * 1 + + _enabledPhy[ble::phy_t::LE_CODED] * 1); + } + +private: + uint8_t getFirstEnabledPhy() { + if (_enabledPhy[ble::phy_t::LE_1M]) { + return 0; + } else if (_enabledPhy[ble::phy_t::LE_2M]) { + return 1; + } else if (_enabledPhy[ble::phy_t::LE_CODED]) { + return 2; + } + } + + /** Handle toggling PHYs on and off and return the correct index to use to set the configuration elements. + * + * @param phy Which Phy is being toggle. + * @param enable On or Off. + * @return The index to the array of settings. + */ + uint8_t handlePhyToggle(ble::phy_t phy, bool enable) { + uint8_t index = phy; + + if (_enabledPhy[phy] != enable) { + if (phy == ble::phy_t::LE_2M) { + if (_enabledPhy[ble::phy_t::LE_CODED]) { + flipCodedAnd2M(); + } + } else if (phy == ble::phy_t::LE_CODED) { + if (!_enabledPhy[ble::phy_t::LE_2M]) { + flipCodedAnd2M(); + index = ble::phy_t::LE_2M; + } + } + } + + _enabledPhy[phy] = enable; + + return index; + } + + /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ + void flipCodedAnd2M() { + uint32_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; + uint32_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; + uint16_t minConnectionInterval = _minConnectionInterval[ble::phy_t::LE_2M]; + uint16_t maxConnectionInterval = _maxConnectionInterval[ble::phy_t::LE_2M]; + uint16_t slaveLatency = _maxConnectionInterval[ble::phy_t::LE_2M]; + uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[ble::phy_t::LE_2M]; + uint32_t minimumEventLength = _minimumEventLength[ble::phy_t::LE_2M]; + uint32_t maximumEventLength = _maximumEventLength[ble::phy_t::LE_2M]; + + _scanInterval[ble::phy_t::LE_2M] = _scanInterval[ble::phy_t::LE_CODED]; + _scanWindow[ble::phy_t::LE_2M] = _scanWindow[ble::phy_t::LE_CODED]; + _minConnectionInterval[ble::phy_t::LE_2M] = _minConnectionInterval[ble::phy_t::LE_CODED]; + _maxConnectionInterval[ble::phy_t::LE_2M] = _maxConnectionInterval[ble::phy_t::LE_CODED]; + _slaveLatency[ble::phy_t::LE_2M] = _slaveLatency[ble::phy_t::LE_CODED]; + _connectionSupervisionTimeout[ble::phy_t::LE_2M] = _connectionSupervisionTimeout[ble::phy_t::LE_CODED]; + _minimumEventLength[ble::phy_t::LE_2M] = _minimumEventLength[ble::phy_t::LE_CODED]; + _maximumEventLength[ble::phy_t::LE_2M] = _maximumEventLength[ble::phy_t::LE_CODED]; + + _scanInterval[ble::phy_t::LE_CODED] = scanInterval; + _scanWindow[ble::phy_t::LE_CODED] = scanWindow; + _minConnectionInterval[ble::phy_t::LE_CODED] = minConnectionInterval; + _maxConnectionInterval[ble::phy_t::LE_CODED] = maxConnectionInterval; + _slaveLatency[ble::phy_t::LE_CODED] = slaveLatency; + _connectionSupervisionTimeout[ble::phy_t::LE_CODED] = connectionSupervisionTimeout; + _minimumEventLength[ble::phy_t::LE_CODED] = minimumEventLength; + _maximumEventLength[ble::phy_t::LE_CODED] = maximumEventLength; + } + private: ble::scanning_policy_mode_t _filterPolicy; ble::own_address_type_t _ownAddressType; + uint32_t _scanInterval[MAX_PARAM_PHYS]; uint32_t _scanWindow[MAX_PARAM_PHYS]; uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; @@ -124,6 +240,7 @@ private: uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; uint32_t _minimumEventLength[MAX_PARAM_PHYS]; uint32_t _maximumEventLength[MAX_PARAM_PHYS]; + bool _enabledPhy[MAX_PARAM_PHYS]; }; From 32d3fa9aad21761d7c49e34d5028f67de50763fb Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:32:34 +0000 Subject: [PATCH 103/361] shorten min max --- .../ble/gap/ExtendedConnectParameters.h | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index da0a81d989..f4e5c80a07 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -38,8 +38,8 @@ public: _maxConnectionInterval[i] = 6; _slaveLatency[i] = 0; _connectionSupervisionTimeout[i] = 0xC80; - _minimumEventLength[i] = 0; - _maximumEventLength[i] = 0xFFFF; + _minEventLength[i] = 0; + _maxEventLength[i] = 0xFFFF; _enabledPhy[i] = false; } }; @@ -146,12 +146,12 @@ public: return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; } - uint32_t* getMinimumEventLengthArray() { - return &_minimumEventLength[getFirstEnabledPhy()]; + uint32_t* getMinEventLengthArray() { + return &_minEventLength[getFirstEnabledPhy()]; } - uint32_t* getMaximumEventLengthArray() { - return &_maximumEventLength[getFirstEnabledPhy()]; + uint32_t* getMaxEventLengthArray() { + return &_maxEventLength[getFirstEnabledPhy()]; } uint8_t getNumberOfEnabledPhys() { @@ -160,6 +160,14 @@ public: _enabledPhy[ble::phy_t::LE_CODED] * 1); } + ble::own_address_type_t getOwnAddressType() { + return _ownAddressType; + } + + ble::scanning_policy_mode_t getFilterPolicy() { + return _filterPolicy; + } + private: uint8_t getFirstEnabledPhy() { if (_enabledPhy[ble::phy_t::LE_1M]) { @@ -206,8 +214,8 @@ private: uint16_t maxConnectionInterval = _maxConnectionInterval[ble::phy_t::LE_2M]; uint16_t slaveLatency = _maxConnectionInterval[ble::phy_t::LE_2M]; uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[ble::phy_t::LE_2M]; - uint32_t minimumEventLength = _minimumEventLength[ble::phy_t::LE_2M]; - uint32_t maximumEventLength = _maximumEventLength[ble::phy_t::LE_2M]; + uint32_t minEventLength = _minEventLength[ble::phy_t::LE_2M]; + uint32_t maxEventLength = _maxEventLength[ble::phy_t::LE_2M]; _scanInterval[ble::phy_t::LE_2M] = _scanInterval[ble::phy_t::LE_CODED]; _scanWindow[ble::phy_t::LE_2M] = _scanWindow[ble::phy_t::LE_CODED]; @@ -215,8 +223,8 @@ private: _maxConnectionInterval[ble::phy_t::LE_2M] = _maxConnectionInterval[ble::phy_t::LE_CODED]; _slaveLatency[ble::phy_t::LE_2M] = _slaveLatency[ble::phy_t::LE_CODED]; _connectionSupervisionTimeout[ble::phy_t::LE_2M] = _connectionSupervisionTimeout[ble::phy_t::LE_CODED]; - _minimumEventLength[ble::phy_t::LE_2M] = _minimumEventLength[ble::phy_t::LE_CODED]; - _maximumEventLength[ble::phy_t::LE_2M] = _maximumEventLength[ble::phy_t::LE_CODED]; + _minEventLength[ble::phy_t::LE_2M] = _minEventLength[ble::phy_t::LE_CODED]; + _maxEventLength[ble::phy_t::LE_2M] = _maxEventLength[ble::phy_t::LE_CODED]; _scanInterval[ble::phy_t::LE_CODED] = scanInterval; _scanWindow[ble::phy_t::LE_CODED] = scanWindow; @@ -224,8 +232,8 @@ private: _maxConnectionInterval[ble::phy_t::LE_CODED] = maxConnectionInterval; _slaveLatency[ble::phy_t::LE_CODED] = slaveLatency; _connectionSupervisionTimeout[ble::phy_t::LE_CODED] = connectionSupervisionTimeout; - _minimumEventLength[ble::phy_t::LE_CODED] = minimumEventLength; - _maximumEventLength[ble::phy_t::LE_CODED] = maximumEventLength; + _minEventLength[ble::phy_t::LE_CODED] = minEventLength; + _maxEventLength[ble::phy_t::LE_CODED] = maxEventLength; } private: @@ -238,8 +246,8 @@ private: uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; uint16_t _slaveLatency[MAX_PARAM_PHYS]; uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; - uint32_t _minimumEventLength[MAX_PARAM_PHYS]; - uint32_t _maximumEventLength[MAX_PARAM_PHYS]; + uint32_t _minEventLength[MAX_PARAM_PHYS]; + uint32_t _maxEventLength[MAX_PARAM_PHYS]; bool _enabledPhy[MAX_PARAM_PHYS]; }; From a2f461c38e4d9b78e9bbe5089657b0bdaf3597e0 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:32:50 +0000 Subject: [PATCH 104/361] reference instead of pointer --- features/FEATURE_BLE/ble/Gap.h | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 3be484d9f7..53d9d8b824 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1530,16 +1530,12 @@ public: */ virtual ble_error_t connect( TargetPeerAddressType_t peerAddressType, - const BLEProtocol::AddressBytes_t peerAddress, + const BLEProtocol::AddressBytes_t &peerAddress, const ExtendedConnectParameters_t &connectionParams ) { - (void)filterPolicy; - (void)ownAddressType; (void)peerAddressType; (void)peerAddress; - (void)connectionParams1M; - (void)connectionParams2M; - (void)connectionParamsCoded; + (void)connectionParams; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; From b489e0957ec51ca762d5c908a86b9bff7f2beb7b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:33:02 +0000 Subject: [PATCH 105/361] pal call --- features/FEATURE_BLE/ble/generic/GenericGap.h | 9 +++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 66aa7d7483..ca1b0bf7bf 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -231,6 +231,15 @@ public: const GapScanningParams *scanParams ); + /** + * @see Gap::connect + */ + virtual ble_error_t connect( + ble::target_peer_address_type_t peerAddressType, + const BLEProtocol::AddressBytes_t &peerAddress, + const ExtendedConnectParameters_t &connectionParams + ); + /** * @see Gap::readPhy */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3f64494b51..7da0143303 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -601,6 +601,30 @@ ble_error_t GenericGap::connect( ); } + +virtual ble_error_t connect( + ble::target_peer_address_type_t peerAddressType, + const BLEProtocol::AddressBytes_t &peerAddress, + const ExtendedConnectParameters_t &connectionParams +) { + + return _pal_gap.extended_create_connection( + (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), + (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), + (ble::peer_address_type_t)peerAddressType.value(), + peerAddress, + connectionParams.getNumberOfEnabledPhys, + connectionParams.getScanIntervalArray, + connectionParams.getScanWindowArray, + connectionParams.getMinConnectionIntervalArray, + connectionParams.getMaxConnectionIntervalArray, + connectionParams.getSlaveLatencyArray, + connectionParams.getConnectionSupervisionTimeoutArray, + connectionParams.getMinEventLengthArray, + connectionParams.getMaxEventLengthArray + ); +} + ble_error_t GenericGap::readPhy(Handle_t connection) { return _pal_gap.read_phy(connection); } From 8801ef570aae48330414765d3d9c430280fce3b8 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:44:52 +0000 Subject: [PATCH 106/361] fix types --- .../ble/gap/ExtendedConnectParameters.h | 134 +++++++++--------- 1 file changed, 70 insertions(+), 64 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index f4e5c80a07..b4c396d162 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -44,36 +44,38 @@ public: } }; + /* setters */ + ExtendedConnectParameters_t& setScanParamteres( - uint32_t scanInterval, - uint32_t scanWindow, + uint32_t scanInterval_us, + uint32_t scanWindow_us, ble::phy_t phy = ble::phy_t::LE_1M ) { uint8_t phy_index = handlePhyToggle(phy, true); - scanInterval = scanInterval[phy_index]; - scanWindow = scanWindow[phy_index]; + _scanInterval[phy_index] = scanInterval_us / 625; + _scanWindow[phy_index] = scanWindow_us / 625; return *this; } ExtendedConnectParameters_t& setConnectionParamteres( - uint16_t minConnectionInterval, - uint16_t maxConnectionInterval, + uint16_t minConnectionInterval_ms, + uint16_t maxConnectionInterval_ms, uint16_t slaveLatency, - uint16_t connectionSupervisionTimeout, - uint32_t _minimumEventLength, - uint32_t _maximumEventLength, + uint16_t connectionSupervisionTimeout_ms, + uint32_t _minEventLength_us, + uint32_t _maxEventLength_us, ble::phy_t phy = ble::phy_t::LE_1M ) { uint8_t phy_index = handlePhyToggle(phy, true); - _minConnectionInterval = minConnectionInterval[phy_index]; - maxConnectionInterval = maxConnectionInterval[phy_index]; - slaveLatency = slaveLatency[phy_index]; - connectionSupervisionTimeout = connectionSupervisionTimeout[phy_index]; - _minimumEventLength = _minimumEventLength[phy_index]; - _maximumEventLength = _maximumEventLength[phy_index]; + _minConnectionInterval[phy_index] = (((uint32_t)minConnectionInterval_ms) * 1000) / 1250; + _maxConnectionInterval[phy_index] = (((uint32_t)maxConnectionInterval_ms) * 1000) / 1250; + _slaveLatency[phy_index] = slaveLatency; + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout_ms * 10; + _minEventLength[phy_index] = _minEventLength_us / 625; + _maxEventLength[phy_index] = _maxEventLength_us / 625; return *this; } @@ -122,43 +124,7 @@ public: return *this; } - uint32_t* getScanIntervalArray() { - return &_scanInterval[getFirstEnabledPhy()]; - } - - uint32_t* getScanWindowArray() { - return &_scanWindow[getFirstEnabledPhy()]; - } - - uint32_t* getMinConnectionIntervalArray() { - return &_minConnectionInterval[getFirstEnabledPhy()]; - } - - uint32_t* getMaxConnectionIntervalArray() { - return &_maxConnectionInterval[getFirstEnabledPhy()]; - } - - uint32_t* getSlaveLatencyArray() { - return &_slaveLatency[getFirstEnabledPhy()]; - } - - uint32_t* getConnectionSupervisionTimeoutArray() { - return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; - } - - uint32_t* getMinEventLengthArray() { - return &_minEventLength[getFirstEnabledPhy()]; - } - - uint32_t* getMaxEventLengthArray() { - return &_maxEventLength[getFirstEnabledPhy()]; - } - - uint8_t getNumberOfEnabledPhys() { - return (_enabledPhy[ble::phy_t::LE_1M] * 1 + - _enabledPhy[ble::phy_t::LE_2M] * 1 + - _enabledPhy[ble::phy_t::LE_CODED] * 1); - } + /* getters */ ble::own_address_type_t getOwnAddressType() { return _ownAddressType; @@ -168,6 +134,46 @@ public: return _filterPolicy; } + /* these return pointers to arrays of settings valid only across the number of active PHYs */ + + uint16_t* getScanIntervalArray() { + return &_scanInterval[getFirstEnabledPhy()]; + } + + uint16_t* getScanWindowArray() { + return &_scanWindow[getFirstEnabledPhy()]; + } + + uint16_t* getMinConnectionIntervalArray() { + return &_minConnectionInterval[getFirstEnabledPhy()]; + } + + uint16_t* getMaxConnectionIntervalArray() { + return &_maxConnectionInterval[getFirstEnabledPhy()]; + } + + uint16_t* getSlaveLatencyArray() { + return &_slaveLatency[getFirstEnabledPhy()]; + } + + uint16_t* getConnectionSupervisionTimeoutArray() { + return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; + } + + uint16_t* getMinEventLengthArray() { + return &_minEventLength[getFirstEnabledPhy()]; + } + + uint16_t* getMaxEventLengthArray() { + return &_maxEventLength[getFirstEnabledPhy()]; + } + + uint8_t getNumberOfEnabledPhys() { + return (_enabledPhy[ble::phy_t::LE_1M] * 1 + + _enabledPhy[ble::phy_t::LE_2M] * 1 + + _enabledPhy[ble::phy_t::LE_CODED] * 1); + } + private: uint8_t getFirstEnabledPhy() { if (_enabledPhy[ble::phy_t::LE_1M]) { @@ -208,14 +214,14 @@ private: /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ void flipCodedAnd2M() { - uint32_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; - uint32_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; + uint16_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; + uint16_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; uint16_t minConnectionInterval = _minConnectionInterval[ble::phy_t::LE_2M]; uint16_t maxConnectionInterval = _maxConnectionInterval[ble::phy_t::LE_2M]; uint16_t slaveLatency = _maxConnectionInterval[ble::phy_t::LE_2M]; uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[ble::phy_t::LE_2M]; - uint32_t minEventLength = _minEventLength[ble::phy_t::LE_2M]; - uint32_t maxEventLength = _maxEventLength[ble::phy_t::LE_2M]; + uint16_t minEventLength = _minEventLength[ble::phy_t::LE_2M]; + uint16_t maxEventLength = _maxEventLength[ble::phy_t::LE_2M]; _scanInterval[ble::phy_t::LE_2M] = _scanInterval[ble::phy_t::LE_CODED]; _scanWindow[ble::phy_t::LE_2M] = _scanWindow[ble::phy_t::LE_CODED]; @@ -240,14 +246,14 @@ private: ble::scanning_policy_mode_t _filterPolicy; ble::own_address_type_t _ownAddressType; - uint32_t _scanInterval[MAX_PARAM_PHYS]; - uint32_t _scanWindow[MAX_PARAM_PHYS]; - uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; - uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; - uint16_t _slaveLatency[MAX_PARAM_PHYS]; - uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; - uint32_t _minEventLength[MAX_PARAM_PHYS]; - uint32_t _maxEventLength[MAX_PARAM_PHYS]; + uint16_t _scanInterval[MAX_PARAM_PHYS]; /* 0.625 */ + uint16_t _scanWindow[MAX_PARAM_PHYS]; /* 0.625 */ + uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 */ + uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 */ + uint16_t _slaveLatency[MAX_PARAM_PHYS]; /* 0.625 */ + uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; /* 10 */ + uint16_t _minEventLength[MAX_PARAM_PHYS]; /* 0.625 */ + uint16_t _maxEventLength[MAX_PARAM_PHYS]; /* 0.625 */ bool _enabledPhy[MAX_PARAM_PHYS]; }; From 4fe7d5ed903d9c55d8a038252daa4e90d5b0d011 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 20:51:26 +0000 Subject: [PATCH 107/361] small cleanup --- .../ble/gap/ExtendedConnectParameters.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index b4c396d162..01b53a5857 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -134,6 +134,12 @@ public: return _filterPolicy; } + uint8_t getNumberOfEnabledPhys() { + return (_enabledPhy[ble::phy_t::LE_1M] * 1 + + _enabledPhy[ble::phy_t::LE_2M] * 1 + + _enabledPhy[ble::phy_t::LE_CODED] * 1); + } + /* these return pointers to arrays of settings valid only across the number of active PHYs */ uint16_t* getScanIntervalArray() { @@ -168,12 +174,6 @@ public: return &_maxEventLength[getFirstEnabledPhy()]; } - uint8_t getNumberOfEnabledPhys() { - return (_enabledPhy[ble::phy_t::LE_1M] * 1 + - _enabledPhy[ble::phy_t::LE_2M] * 1 + - _enabledPhy[ble::phy_t::LE_CODED] * 1); - } - private: uint8_t getFirstEnabledPhy() { if (_enabledPhy[ble::phy_t::LE_1M]) { @@ -197,11 +197,11 @@ private: if (_enabledPhy[phy] != enable) { if (phy == ble::phy_t::LE_2M) { if (_enabledPhy[ble::phy_t::LE_CODED]) { - flipCodedAnd2M(); + swapCodedAnd2M(); } } else if (phy == ble::phy_t::LE_CODED) { if (!_enabledPhy[ble::phy_t::LE_2M]) { - flipCodedAnd2M(); + swapCodedAnd2M(); index = ble::phy_t::LE_2M; } } @@ -213,7 +213,7 @@ private: } /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ - void flipCodedAnd2M() { + void swapCodedAnd2M() { uint16_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; uint16_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; uint16_t minConnectionInterval = _minConnectionInterval[ble::phy_t::LE_2M]; From 952997457294fb7319f938b70b54d4e257ebca00 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 21:02:25 +0000 Subject: [PATCH 108/361] type already defined in ble types --- features/FEATURE_BLE/ble/Gap.h | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 53d9d8b824..ee0cf66d40 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -475,23 +475,6 @@ public: ADV_POLICY_FILTER_ALL_REQS = 3, }; - /** - * Scanning policy filter mode. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. - */ - enum ScanningPolicyMode_t { - /** - * The whitelist is not used for scanning operations. - */ - SCAN_POLICY_IGNORE_WHITELIST = 0, - - /** - * The whitelist is used to filter incoming advertising. - */ - SCAN_POLICY_FILTER_ALL_ADV = 1, - }; - /** * Connection initiation policy filter mode. * @@ -580,6 +563,9 @@ public: */ typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; + static const uint8_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; + static const uint8_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; + /** * Enumeration of BLE PHY */ From 6fa7a8ffce8e6a714935cc4a4b2bffe8b8434587 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 21:04:54 +0000 Subject: [PATCH 109/361] fix type --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index ee0cf66d40..f98b75bac4 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -563,8 +563,8 @@ public: */ typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; - static const uint8_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; - static const uint8_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; + static const ScanningPolicyMode_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; + static const ScanningPolicyMode_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; /** * Enumeration of BLE PHY From 5e6c0c92f6389f0f3caf43ff7f0627984ba2bc03 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 21:13:15 +0000 Subject: [PATCH 110/361] compilation errors --- .../ble/gap/ExtendedConnectParameters.h | 45 +++++++++++-------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 20 ++++----- 2 files changed, 37 insertions(+), 28 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 01b53a5857..d2a9054f8e 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -25,13 +25,13 @@ */ class ExtendedConnectParameters_t { - const size_t MAX_PARAM_PHYS = 3; + static const uint8_t MAX_PARAM_PHYS = 3; public: ExtendedConnectParameters_t() : - _filterPolicy(ble::scanning_policy_mode_t::SCAN_POLICY_FILTER_ALL_ADV), + _filterPolicy(ble::SCAN_POLICY_FILTER_ALL_ADV), _ownAddressType(ble::own_address_type_t::PUBLIC) { - for (int i = 0; i < MAX_PARAM_PHYS; ++i) { + for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { _scanInterval[i] = 4; _scanWindow[i] = 4; _minConnectionInterval[i] = 6; @@ -99,7 +99,7 @@ public: ExtendedConnectParameters_t& togglePhy( bool phy1M, bool phy2M, - bool phyCoded, + bool phyCoded ) { handlePhyToggle(ble::phy_t::LE_1M, phy1M); handlePhyToggle(ble::phy_t::LE_2M, phy2M); @@ -126,11 +126,11 @@ public: /* getters */ - ble::own_address_type_t getOwnAddressType() { + ble::own_address_type_t getOwnAddressType() const { return _ownAddressType; } - ble::scanning_policy_mode_t getFilterPolicy() { + ble::scanning_policy_mode_t getFilterPolicy() const { return _filterPolicy; } @@ -140,42 +140,51 @@ public: _enabledPhy[ble::phy_t::LE_CODED] * 1); } + ble::phy_set_t getPhySet() const { + ble::phy_set_t set( + _enabledPhy[ble::phy_t::LE_1M], + _enabledPhy[ble::phy_t::LE_2M], + _enabledPhy[ble::phy_t::LE_CODED] + ); + return set; + } + /* these return pointers to arrays of settings valid only across the number of active PHYs */ - uint16_t* getScanIntervalArray() { + const uint16_t* getScanIntervalArray() const { return &_scanInterval[getFirstEnabledPhy()]; } - uint16_t* getScanWindowArray() { + const uint16_t* getScanWindowArray() const { return &_scanWindow[getFirstEnabledPhy()]; } - uint16_t* getMinConnectionIntervalArray() { + const uint16_t* getMinConnectionIntervalArray() const { return &_minConnectionInterval[getFirstEnabledPhy()]; } - uint16_t* getMaxConnectionIntervalArray() { + const uint16_t* getMaxConnectionIntervalArray() const { return &_maxConnectionInterval[getFirstEnabledPhy()]; } - uint16_t* getSlaveLatencyArray() { + const uint16_t* getSlaveLatencyArray() const { return &_slaveLatency[getFirstEnabledPhy()]; } - uint16_t* getConnectionSupervisionTimeoutArray() { + const uint16_t* getConnectionSupervisionTimeoutArray() const { return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; } - uint16_t* getMinEventLengthArray() { + const uint16_t* getMinEventLengthArray() const { return &_minEventLength[getFirstEnabledPhy()]; } - uint16_t* getMaxEventLengthArray() { + const uint16_t* getMaxEventLengthArray() const { return &_maxEventLength[getFirstEnabledPhy()]; } private: - uint8_t getFirstEnabledPhy() { + uint8_t getFirstEnabledPhy() const { if (_enabledPhy[ble::phy_t::LE_1M]) { return 0; } else if (_enabledPhy[ble::phy_t::LE_2M]) { @@ -192,9 +201,9 @@ private: * @return The index to the array of settings. */ uint8_t handlePhyToggle(ble::phy_t phy, bool enable) { - uint8_t index = phy; + uint8_t index = phy.value(); - if (_enabledPhy[phy] != enable) { + if (_enabledPhy[phy.value()] != enable) { if (phy == ble::phy_t::LE_2M) { if (_enabledPhy[ble::phy_t::LE_CODED]) { swapCodedAnd2M(); @@ -207,7 +216,7 @@ private: } } - _enabledPhy[phy] = enable; + _enabledPhy[phy.value()] = enable; return index; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7da0143303..a30404d62c 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -602,7 +602,7 @@ ble_error_t GenericGap::connect( } -virtual ble_error_t connect( +ble_error_t GenericGap::connect( ble::target_peer_address_type_t peerAddressType, const BLEProtocol::AddressBytes_t &peerAddress, const ExtendedConnectParameters_t &connectionParams @@ -613,15 +613,15 @@ virtual ble_error_t connect( (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), (ble::peer_address_type_t)peerAddressType.value(), peerAddress, - connectionParams.getNumberOfEnabledPhys, - connectionParams.getScanIntervalArray, - connectionParams.getScanWindowArray, - connectionParams.getMinConnectionIntervalArray, - connectionParams.getMaxConnectionIntervalArray, - connectionParams.getSlaveLatencyArray, - connectionParams.getConnectionSupervisionTimeoutArray, - connectionParams.getMinEventLengthArray, - connectionParams.getMaxEventLengthArray + connectionParams.getNumberOfEnabledPhys(), + connectionParams.getScanIntervalArray(), + connectionParams.getScanWindowArray(), + connectionParams.getMinConnectionIntervalArray(), + connectionParams.getMaxConnectionIntervalArray(), + connectionParams.getSlaveLatencyArray(), + connectionParams.getConnectionSupervisionTimeoutArray(), + connectionParams.getMinEventLengthArray(), + connectionParams.getMaxEventLengthArray() ); } From bd8b7fa87f76ffd77e65d7c4e441beac580586d3 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 21:19:08 +0000 Subject: [PATCH 111/361] use set value on return --- features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index d2a9054f8e..b20e280584 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -140,13 +140,13 @@ public: _enabledPhy[ble::phy_t::LE_CODED] * 1); } - ble::phy_set_t getPhySet() const { + uint8_t getPhySet() const { ble::phy_set_t set( _enabledPhy[ble::phy_t::LE_1M], _enabledPhy[ble::phy_t::LE_2M], _enabledPhy[ble::phy_t::LE_CODED] ); - return set; + return set.value(); } /* these return pointers to arrays of settings valid only across the number of active PHYs */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index a30404d62c..5f6effa534 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -611,9 +611,9 @@ ble_error_t GenericGap::connect( return _pal_gap.extended_create_connection( (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), - (ble::peer_address_type_t)peerAddressType.value(), + (ble::peer_address_type_t::type)peerAddressType.value(), peerAddress, - connectionParams.getNumberOfEnabledPhys(), + (ble::phy_set_t)connectionParams.getPhySet(), connectionParams.getScanIntervalArray(), connectionParams.getScanWindowArray(), connectionParams.getMinConnectionIntervalArray(), From b98326150daad05d0bf090c48f70b02f62aa6f06 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 21:25:52 +0000 Subject: [PATCH 112/361] fix names --- features/FEATURE_BLE/ble/Gap.h | 2 +- .../ble/gap/ExtendedConnectParameters.h | 20 +++++++++---------- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 6 ++++-- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index f98b75bac4..6c70531c15 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1517,7 +1517,7 @@ public: virtual ble_error_t connect( TargetPeerAddressType_t peerAddressType, const BLEProtocol::AddressBytes_t &peerAddress, - const ExtendedConnectParameters_t &connectionParams + const GapExtendedConnectParameters_t &connectionParams ) { (void)peerAddressType; (void)peerAddress; diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index b20e280584..f423e6b38e 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -24,10 +24,10 @@ * @{ */ -class ExtendedConnectParameters_t { +class GapExtendedConnectParameters_t { static const uint8_t MAX_PARAM_PHYS = 3; public: - ExtendedConnectParameters_t() : + GapExtendedConnectParameters_t() : _filterPolicy(ble::SCAN_POLICY_FILTER_ALL_ADV), _ownAddressType(ble::own_address_type_t::PUBLIC) { @@ -46,7 +46,7 @@ public: /* setters */ - ExtendedConnectParameters_t& setScanParamteres( + GapExtendedConnectParameters_t& setScanParameters( uint32_t scanInterval_us, uint32_t scanWindow_us, ble::phy_t phy = ble::phy_t::LE_1M @@ -59,7 +59,7 @@ public: return *this; } - ExtendedConnectParameters_t& setConnectionParamteres( + GapExtendedConnectParameters_t& setConnectionParameters( uint16_t minConnectionInterval_ms, uint16_t maxConnectionInterval_ms, uint16_t slaveLatency, @@ -80,7 +80,7 @@ public: return *this; } - ExtendedConnectParameters_t& setScanParamteres( + GapExtendedConnectParameters_t& setScanParamteres( ble::own_address_type_t ownAddress ) { _ownAddressType = ownAddress; @@ -88,7 +88,7 @@ public: return *this; } - ExtendedConnectParameters_t& setScanParamteres( + GapExtendedConnectParameters_t& setScanParamteres( ble::scanning_policy_mode_t filterPolicy ) { _filterPolicy = filterPolicy; @@ -96,7 +96,7 @@ public: return *this; } - ExtendedConnectParameters_t& togglePhy( + GapExtendedConnectParameters_t& togglePhy( bool phy1M, bool phy2M, bool phyCoded @@ -108,7 +108,7 @@ public: return *this; } - ExtendedConnectParameters_t& disablePhy( + GapExtendedConnectParameters_t& disablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { handlePhyToggle(phy, false); @@ -116,7 +116,7 @@ public: return *this; } - ExtendedConnectParameters_t& enablePhy( + GapExtendedConnectParameters_t& enablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { handlePhyToggle(phy, true); @@ -134,7 +134,7 @@ public: return _filterPolicy; } - uint8_t getNumberOfEnabledPhys() { + uint8_t getNumberOfEnabledPhys() const { return (_enabledPhy[ble::phy_t::LE_1M] * 1 + _enabledPhy[ble::phy_t::LE_2M] * 1 + _enabledPhy[ble::phy_t::LE_CODED] * 1); diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index ca1b0bf7bf..349e915c00 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -237,7 +237,7 @@ public: virtual ble_error_t connect( ble::target_peer_address_type_t peerAddressType, const BLEProtocol::AddressBytes_t &peerAddress, - const ExtendedConnectParameters_t &connectionParams + const GapExtendedConnectParameters_t &connectionParams ); /** diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 5f6effa534..cafd6c1453 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -605,9 +605,11 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( ble::target_peer_address_type_t peerAddressType, const BLEProtocol::AddressBytes_t &peerAddress, - const ExtendedConnectParameters_t &connectionParams + const GapExtendedConnectParameters_t &connectionParams ) { - + if (!connectionParams.getNumberOfEnabledPhys()) { + return BLE_ERROR_INVALID_PARAM; + } return _pal_gap.extended_create_connection( (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), From 519f75587a9e18e11019dde1993d71567c4aec83 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 22:14:54 +0000 Subject: [PATCH 113/361] ppm conversion --- features/FEATURE_BLE/ble/pal/GapTypes.h | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 4921d16a7b..5ca29d8d8d 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -994,6 +994,43 @@ struct clock_accuracy_t : SafeEnum{ */ clock_accuracy_t(type value) : SafeEnum(value) { } + /** Get clock accuracy. + * + * @return Parts per million as a number. + */ + uint16_t getPPM() { + uint16_t ppm = 0; + + switch(value()) { + case PPM_500: + ppm = 500; + break; + case PPM_250: + ppm = 250; + break; + case PPM_150: + ppm = 150; + break; + case PPM_100: + ppm = 100; + break; + case PPM_75: + ppm = 75; + break; + case PPM_50: + ppm = 50; + break; + case PPM_30: + ppm = 30; + break; + case PPM_20: + ppm = 20; + break; + } + + return ppm; + } + explicit clock_accuracy_t(uint8_t raw_value) : SafeEnum(static_cast(raw_value)) { } }; From 62b38cfbc837e5a74dec40598eb54cc8fb08f96c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Sun, 11 Nov 2018 22:15:11 +0000 Subject: [PATCH 114/361] connection complete event --- features/FEATURE_BLE/ble/Gap.h | 26 +++++++++++++++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 20 +++++++++++--- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 6c70531c15..a9e2b71158 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1285,6 +1285,32 @@ public: (void)rxPhy; } + void onEnhancedConnectionComplete( + bool success, + Handle_t connectionHandle, + Role_t ownRole, + PeerAddressType_t peerAddressType, + const ble::address_t &peerAddress, + const ble::address_t &localResolvablePrivateAddress, + const ble::address_t &peerResolvablePrivateAddress, + uint16_t connectionInterval_us, + uint16_t connectionLatency, + uint16_t supervisionTimeout_ms, + uint16_t masterClockAccuracy_ppm + ) { + (void)success; + (void)connectionHandle; + (void)ownRole; + (void)peerAddressType; + (void)peerAddress; + (void)localResolvablePrivateAddress; + (void)peerResolvablePrivateAddress; + (void)connectionInterval_us; + (void)connectionLatency; + (void)supervisionTimeout_ms; + (void)masterClockAccuracy_ppm; + } + protected: /** * Prevent polymorphic deletion and avoid uncessery virtual destructor diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index cafd6c1453..1159f009dc 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -610,6 +610,7 @@ ble_error_t GenericGap::connect( if (!connectionParams.getNumberOfEnabledPhys()) { return BLE_ERROR_INVALID_PARAM; } + return _pal_gap.extended_create_connection( (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), @@ -2129,9 +2130,22 @@ void GenericGap::on_enhanced_connection_complete( uint16_t connection_latency, uint16_t supervision_timeout, pal::clock_accuracy_t master_clock_accuracy -) -{ - +) { + if (_eventHandler) { + _eventHandler->onEnhancedConnectionComplete( + (status==pal::hci_error_code_t::SUCCESS), + (ble::connection_handle_t)connection_handle, + (Gap::Role_t)own_role.value(), + (ble::peer_address_type_t::type)peer_address_type.value(), + peer_address, + local_resolvable_private_address, + peer_resolvable_private_address, + connection_interval * 1250, + connection_latency, + supervision_timeout * 10, + master_clock_accuracy.getPPM() + ); + } } void GenericGap::on_extended_advertising_report( From fd880d1e6b1e0a7f10119bb77fbca17d627cefc6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:15:02 +0000 Subject: [PATCH 115/361] fix swapping --- .../ble/gap/ExtendedConnectParameters.h | 32 ++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index f423e6b38e..fed927dca2 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -203,21 +203,31 @@ private: uint8_t handlePhyToggle(ble::phy_t phy, bool enable) { uint8_t index = phy.value(); - if (_enabledPhy[phy.value()] != enable) { - if (phy == ble::phy_t::LE_2M) { - if (_enabledPhy[ble::phy_t::LE_CODED]) { - swapCodedAnd2M(); - } - } else if (phy == ble::phy_t::LE_CODED) { - if (!_enabledPhy[ble::phy_t::LE_2M]) { - swapCodedAnd2M(); - index = ble::phy_t::LE_2M; - } - } + bool was_swapped = false; + bool is_swapped = false; + + if (_enabledPhy[ble::phy_t::LE_1M] && + !_enabledPhy[ble::phy_t::LE_2M] && + _enabledPhy[ble::phy_t::LE_CODED]) { + was_swapped = true; } _enabledPhy[phy.value()] = enable; + if (_enabledPhy[ble::phy_t::LE_1M] && + !_enabledPhy[ble::phy_t::LE_2M] && + _enabledPhy[ble::phy_t::LE_CODED]) { + is_swapped = true; + } + + if (was_swapped != is_swapped) { + swapCodedAnd2M(); + } + + if (is_swapped && phy == ble::phy_t::LE_CODED) { + index -= 1; + } + return index; } From 565f1e01312e2dbaa6cf0b02e90c23dd646fc8f6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:20:41 +0000 Subject: [PATCH 116/361] fix first element of array selection --- .../ble/gap/ExtendedConnectParameters.h | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index fed927dca2..784ea4129f 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -190,7 +190,11 @@ private: } else if (_enabledPhy[ble::phy_t::LE_2M]) { return 1; } else if (_enabledPhy[ble::phy_t::LE_CODED]) { - return 2; + if (isSwapped()) { + return 1; + } else { + return 2; + } } } @@ -206,17 +210,13 @@ private: bool was_swapped = false; bool is_swapped = false; - if (_enabledPhy[ble::phy_t::LE_1M] && - !_enabledPhy[ble::phy_t::LE_2M] && - _enabledPhy[ble::phy_t::LE_CODED]) { + if (isSwapped()) { was_swapped = true; } _enabledPhy[phy.value()] = enable; - if (_enabledPhy[ble::phy_t::LE_1M] && - !_enabledPhy[ble::phy_t::LE_2M] && - _enabledPhy[ble::phy_t::LE_CODED]) { + if (isSwapped()) { is_swapped = true; } @@ -231,6 +231,12 @@ private: return index; } + bool isSwapped() const { + return (_enabledPhy[ble::phy_t::LE_1M] && + !_enabledPhy[ble::phy_t::LE_2M] && + _enabledPhy[ble::phy_t::LE_CODED]); + } + /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ void swapCodedAnd2M() { uint16_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; From 87887cc9dd40d8386ed3c2871ab2ae1fd838454b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:22:16 +0000 Subject: [PATCH 117/361] rename phy to index --- .../ble/gap/ExtendedConnectParameters.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 784ea4129f..e853f41489 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -152,39 +152,39 @@ public: /* these return pointers to arrays of settings valid only across the number of active PHYs */ const uint16_t* getScanIntervalArray() const { - return &_scanInterval[getFirstEnabledPhy()]; + return &_scanInterval[getFirstEnabledIndex()]; } const uint16_t* getScanWindowArray() const { - return &_scanWindow[getFirstEnabledPhy()]; + return &_scanWindow[getFirstEnabledIndex()]; } const uint16_t* getMinConnectionIntervalArray() const { - return &_minConnectionInterval[getFirstEnabledPhy()]; + return &_minConnectionInterval[getFirstEnabledIndex()]; } const uint16_t* getMaxConnectionIntervalArray() const { - return &_maxConnectionInterval[getFirstEnabledPhy()]; + return &_maxConnectionInterval[getFirstEnabledIndex()]; } const uint16_t* getSlaveLatencyArray() const { - return &_slaveLatency[getFirstEnabledPhy()]; + return &_slaveLatency[getFirstEnabledIndex()]; } const uint16_t* getConnectionSupervisionTimeoutArray() const { - return &_connectionSupervisionTimeout[getFirstEnabledPhy()]; + return &_connectionSupervisionTimeout[getFirstEnabledIndex()]; } const uint16_t* getMinEventLengthArray() const { - return &_minEventLength[getFirstEnabledPhy()]; + return &_minEventLength[getFirstEnabledIndex()]; } const uint16_t* getMaxEventLengthArray() const { - return &_maxEventLength[getFirstEnabledPhy()]; + return &_maxEventLength[getFirstEnabledIndex()]; } private: - uint8_t getFirstEnabledPhy() const { + uint8_t getFirstEnabledIndex() const { if (_enabledPhy[ble::phy_t::LE_1M]) { return 0; } else if (_enabledPhy[ble::phy_t::LE_2M]) { From 32c303d7f38bfb5f976a5e0c27257d250f0fc7eb Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:23:30 +0000 Subject: [PATCH 118/361] missing return --- features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index e853f41489..66b8f4619f 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -196,6 +196,7 @@ private: return 2; } } + return 0; } /** Handle toggling PHYs on and off and return the correct index to use to set the configuration elements. From 02d9b35bad7cd4c0bfb3456dfb50310e97833573 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:31:46 +0000 Subject: [PATCH 119/361] assert added --- features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 66b8f4619f..2b13762b91 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -17,6 +17,9 @@ #ifndef MBED_EXTENDED_CONNECT_PARAMETERS_H__ #define MBED_EXTENDED_CONNECT_PARAMETERS_H__ +#include "ble/BLETypes.h" +#include "mbed_assert.h" + /** * @addtogroup ble * @{ @@ -196,6 +199,9 @@ private: return 2; } } + /* this should never happen, it means you were trying to start a connection with a blank set + * of paramters - you need to enabled at least one phy */ + MBED_ASSERT("Trying to use connection parameters without any PHY defined."); return 0; } From a3820c89c50d0b83d6ee654f34093ae22dc09e08 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 08:32:02 +0000 Subject: [PATCH 120/361] removed impossible case --- features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 2b13762b91..810491390d 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -193,11 +193,7 @@ private: } else if (_enabledPhy[ble::phy_t::LE_2M]) { return 1; } else if (_enabledPhy[ble::phy_t::LE_CODED]) { - if (isSwapped()) { - return 1; - } else { - return 2; - } + return 2; } /* this should never happen, it means you were trying to start a connection with a blank set * of paramters - you need to enabled at least one phy */ From 216dd6dcc76b20f76b80c7145ffab31bede0428f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 09:11:17 +0000 Subject: [PATCH 121/361] we need clamping while we wait for c++17 --- features/FEATURE_BLE/ble/BLETypes.h | 10 ++++++++++ .../ble/gap/AdvertisingParameters.h | 16 ++++------------ .../ble/gap/ExtendedConnectParameters.h | 19 +++++++++++-------- 3 files changed, 25 insertions(+), 20 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index bbe3dc2ad9..c445340e20 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -32,6 +32,16 @@ namespace ble { +/* replace with std::clamp when it arrives */ +template +void clamp(T& value, const R& min, const R& max) { + if (value > max) { + value = max; + } else if (value < min) { + value = min; + } +} + /** * Opaque reference to a connection. * diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 5c0a563fa5..95f3229a6e 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -22,14 +22,6 @@ #include "blecommon.h" #include "SafeEnum.h" -/* TODO: std::clamp */ -#define CLAMP(value, min, max) \ - if (value > max) { \ - value = max; \ - } else if (value < min) { \ - value = min; \ - } - /** * @addtogroup ble * @{ @@ -140,11 +132,11 @@ public: _maxInterval = 0; } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { /* Min interval is slightly larger than in other modes. */ - CLAMP(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); - CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + ble::clamp(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); + ble::clamp(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); } else { - CLAMP(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); - CLAMP(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + ble::clamp(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + ble::clamp(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); } /* Timeout checks. */ diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 810491390d..085cd1a581 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -59,6 +59,9 @@ public: _scanInterval[phy_index] = scanInterval_us / 625; _scanWindow[phy_index] = scanWindow_us / 625; + ble::clamp(_scanInterval[phy_index], 0x0004, 0xFFFF); + ble::clamp(_scanWindow[phy_index], 0x0006, 0x0C80); + return *this; } @@ -274,14 +277,14 @@ private: ble::scanning_policy_mode_t _filterPolicy; ble::own_address_type_t _ownAddressType; - uint16_t _scanInterval[MAX_PARAM_PHYS]; /* 0.625 */ - uint16_t _scanWindow[MAX_PARAM_PHYS]; /* 0.625 */ - uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 */ - uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 */ - uint16_t _slaveLatency[MAX_PARAM_PHYS]; /* 0.625 */ - uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; /* 10 */ - uint16_t _minEventLength[MAX_PARAM_PHYS]; /* 0.625 */ - uint16_t _maxEventLength[MAX_PARAM_PHYS]; /* 0.625 */ + uint16_t _scanInterval[MAX_PARAM_PHYS]; /* 0.625 ms */ + uint16_t _scanWindow[MAX_PARAM_PHYS]; /* 0.625 ms */ + uint16_t _minConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 ms */ + uint16_t _maxConnectionInterval[MAX_PARAM_PHYS]; /* 1.25 ms */ + uint16_t _slaveLatency[MAX_PARAM_PHYS]; /* events */ + uint16_t _connectionSupervisionTimeout[MAX_PARAM_PHYS]; /* 10 ms */ + uint16_t _minEventLength[MAX_PARAM_PHYS]; /* 0.625 ms */ + uint16_t _maxEventLength[MAX_PARAM_PHYS]; /* 0.625 ms */ bool _enabledPhy[MAX_PARAM_PHYS]; }; From c0f4b864ca95a6bea4e55cbb8f4ea6ff525225c7 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 09:33:23 +0000 Subject: [PATCH 122/361] clamp values --- .../ble/gap/ExtendedConnectParameters.h | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 085cd1a581..ab0275b863 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -60,7 +60,7 @@ public: _scanWindow[phy_index] = scanWindow_us / 625; ble::clamp(_scanInterval[phy_index], 0x0004, 0xFFFF); - ble::clamp(_scanWindow[phy_index], 0x0006, 0x0C80); + ble::clamp(_scanWindow[phy_index], 0x0004, 0xFFFF); return *this; } @@ -79,9 +79,25 @@ public: _minConnectionInterval[phy_index] = (((uint32_t)minConnectionInterval_ms) * 1000) / 1250; _maxConnectionInterval[phy_index] = (((uint32_t)maxConnectionInterval_ms) * 1000) / 1250; _slaveLatency[phy_index] = slaveLatency; - _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout_ms * 10; - _minEventLength[phy_index] = _minEventLength_us / 625; - _maxEventLength[phy_index] = _maxEventLength_us / 625; + + ble::clamp(_minConnectionInterval[phy_index], 0x0006, 0x0C80); + ble::clamp(_maxConnectionInterval[phy_index], 0x0006, 0x0C80); + ble::clamp(_slaveLatency[phy_index], 0x0000, 0x01F3); + + /* avoid overlfow */ + uint32_t connectionSupervisionTimeout_10ms = connectionSupervisionTimeout_ms * 10; + ble::clamp(connectionSupervisionTimeout_10ms, 0x000A, 0x0C80); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout_10ms; + + /* avoid overflows and truncation */ + _minEventLength_us = _minEventLength_us / 625; + _maxEventLength_us = _maxEventLength_us / 625; + + ble::clamp(_minEventLength_us, 0x0000, 0xFFFF); + ble::clamp(_maxEventLength_us, 0x0000, 0xFFFF); + + _minEventLength[phy_index] = _minEventLength_us; + _maxEventLength[phy_index] = _maxEventLength_us; return *this; } From 365a6c8c4d2dc45823abd8ab8a87309898952947 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 14:01:56 +0000 Subject: [PATCH 123/361] set random address --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 89 ++++++++++++++----- 3 files changed, 69 insertions(+), 26 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index a9e2b71158..e4d5828703 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1840,7 +1840,7 @@ public: */ virtual ble_error_t startAdvertising( AdvHandle_t handle, - uint32_t maxDuration = 0, + uint16_t maxDuration = 0, uint8_t maxEvents = 0 ) { diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 349e915c00..98e6485265 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -106,7 +106,7 @@ public: ble_error_t startAdvertising( AdvHandle_t handle, - uint32_t maxDuration, + uint16_t maxDuration, uint8_t maxEvents ); @@ -506,6 +506,8 @@ private: void update_random_address(); + bool getUnresolvableRandomAddress(ble::address_t& address); + void on_address_rotation_timeout(); virtual void use_deprecated_scan_api() const; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 1159f009dc..99b924a055 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1550,15 +1550,50 @@ void GenericGap::update_random_address() return; } - ble::address_t address; + if (is_extended_advertising_available()) { + for (uint8_t i = 0; i < MAX_ADVERTISING_SETS; ++i) { + if (_existing_sets.get(i)) { + ble::address_t address; + if (!getUnresolvableRandomAddress(address)) { + return; + } + + /* ignore the error, if it fails to cycle because it's connectable */ + _pal_gap.set_advertising_set_random_address( + (AdvHandle_t)i, + address + ); + } + } + } else { + ble::address_t address; + + if (!getUnresolvableRandomAddress(address)) { + return; + } + + ble_error_t err = _pal_gap.set_random_address( + address + ); + + if (err) { + return; + } + + _address_type = LegacyAddressType::RANDOM_PRIVATE_NON_RESOLVABLE; + _address = address; + } +} + +bool GenericGap::getUnresolvableRandomAddress(ble::address_t& address) { do { byte_array_t<8> random_data; ble_error_t ret = _pal_sm.get_random_data(random_data); if (ret != BLE_ERROR_NONE) { // Abort - return; + return false; } // Build a non-resolvable private address as specified in the Core 4.2 spec, Vol 6, Part B, 1.3.2.2 @@ -1579,15 +1614,7 @@ void GenericGap::update_random_address() break; } while(true); - ble_error_t err = _pal_gap.set_random_address( - address - ); - if (err) { - return; - } - - _address_type = LegacyAddressType::RANDOM_PRIVATE_NON_RESOLVABLE; - _address = address; + return true; } void GenericGap::on_address_rotation_timeout() @@ -1863,10 +1890,11 @@ ble_error_t GenericGap::setAdvertisingData( ble_error_t GenericGap::startAdvertising( AdvHandle_t handle, - uint32_t maxDuration, + uint16_t maxDuration, uint8_t maxEvents -) -{ +) { + ble_error_t error = BLE_ERROR_NONE; + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -1880,9 +1908,9 @@ ble_error_t GenericGap::startAdvertising( return BLE_ERROR_INVALID_PARAM; } - ble_error_t err = _pal_gap.advertising_enable(true); - if (err) { - return err; + error = _pal_gap.advertising_enable(true); + if (error) { + return error; } _advertising_timeout.detach(); @@ -1893,24 +1921,37 @@ ble_error_t GenericGap::startAdvertising( ); } } else { - /* round up */ - uint16_t duration_10ms = maxDuration ? (maxDuration - 1) / 10 + 1 : 0 ; - ble_error_t err = _pal_gap.extended_advertising_enable( + ble::address_t random_address; + + if (!getUnresolvableRandomAddress(random_address)) { + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + error = _pal_gap.set_advertising_set_random_address( + handle, + random_address + ); + + if (error) { + return error; + } + + error = _pal_gap.extended_advertising_enable( /* enable */ true, /* number of advertising sets */ 1, &handle, - &duration_10ms, + &maxDuration, &maxEvents ); - if (err) { - return err; + if (error) { + return error; } } _active_sets.set(handle); - return BLE_ERROR_NONE; + return error; } ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { From 2cdff44f2a4f21cfe7af3ade10eb5c5026b4e37a Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 14:14:11 +0000 Subject: [PATCH 124/361] cancel connection --- features/FEATURE_BLE/ble/Gap.h | 17 ++++++++++++----- features/FEATURE_BLE/ble/generic/GenericGap.h | 5 +++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 5 +++++ 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index e4d5828703..1e79ae4923 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1530,11 +1530,7 @@ public: * Once the connection is established, a ConnectionCallbackParams_t event is * emitted to handlers that have been registered with onConnection(). * - * @param[in] peerAddr MAC address of the peer. It must be in LSB format. - * @param[in] peerAddrType Address type of the peer. It is usually obtained - * from advertising frames. - * @param[in] connectionParams Connection parameters to use. - * @param[in] scanParams Scan parameters used to find the peer. + * FIXME * * @return BLE_ERROR_NONE if connection establishment procedure is started * successfully. The connectionCallChain (if set) is invoked upon @@ -1553,6 +1549,17 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** Cancel the connection attempt. This is not guaranteed to succeed. As a result + * onConnectionComplete in the event handler will be called. Check the success parameter + * to see if the connection was created. + * + * @return BLE_ERROR_NONE if the connection attempt has been requested to be cancelled. + */ + virtual ble_error_t cancelConnect() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; + } + /** * Initiate a connection to a peer. * diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 98e6485265..3aedfca6d4 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -240,6 +240,11 @@ public: const GapExtendedConnectParameters_t &connectionParams ); + /** + * @see Gap::cancelConnect + */ + virtual ble_error_t cancelConnect(); + /** * @see Gap::readPhy */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 99b924a055..ed4229e937 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -628,6 +628,11 @@ ble_error_t GenericGap::connect( ); } +ble_error_t GenericGap::cancelConnect() +{ + return _pal_gap.cancel_connection_creation(); +} + ble_error_t GenericGap::readPhy(Handle_t connection) { return _pal_gap.read_phy(connection); } From 8cc580d986fcc498265502a51e69e862684ee3b9 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 14:15:42 +0000 Subject: [PATCH 125/361] only one connection event needed --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 1e79ae4923..8604037d7c 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1285,7 +1285,7 @@ public: (void)rxPhy; } - void onEnhancedConnectionComplete( + void onConnectionComplete( bool success, Handle_t connectionHandle, Role_t ownRole, @@ -1313,7 +1313,7 @@ public: protected: /** - * Prevent polymorphic deletion and avoid uncessery virtual destructor + * Prevent polymorphic deletion and avoid unnecessary virtual destructor * as the Gap class will never delete the instance it contains. */ ~EventHandler() { } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index ed4229e937..7b6c584dd0 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2178,7 +2178,7 @@ void GenericGap::on_enhanced_connection_complete( pal::clock_accuracy_t master_clock_accuracy ) { if (_eventHandler) { - _eventHandler->onEnhancedConnectionComplete( + _eventHandler->onConnectionComplete( (status==pal::hci_error_code_t::SUCCESS), (ble::connection_handle_t)connection_handle, (Gap::Role_t)own_role.value(), From 68b5aad2ce95105bdf84065e552a6dfec7db7fd1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 15:08:23 +0000 Subject: [PATCH 126/361] ppm case --- features/FEATURE_BLE/ble/pal/GapTypes.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 5ca29d8d8d..b769ca2edf 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -998,7 +998,7 @@ struct clock_accuracy_t : SafeEnum{ * * @return Parts per million as a number. */ - uint16_t getPPM() { + uint16_t getPpm() { uint16_t ppm = 0; switch(value()) { diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7b6c584dd0..5aa29b0ea6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2189,7 +2189,7 @@ void GenericGap::on_enhanced_connection_complete( connection_interval * 1250, connection_latency, supervision_timeout * 10, - master_clock_accuracy.getPPM() + master_clock_accuracy.getPpm() ); } } From 9b77f9dcba105f50c34ecffc67a259285f959595 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 15:08:47 +0000 Subject: [PATCH 127/361] default values and func names --- .../FEATURE_BLE/ble/gap/ExtendedConnectParameters.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index ab0275b863..54764f912e 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -31,7 +31,7 @@ class GapExtendedConnectParameters_t { static const uint8_t MAX_PARAM_PHYS = 3; public: GapExtendedConnectParameters_t() : - _filterPolicy(ble::SCAN_POLICY_FILTER_ALL_ADV), + _filterPolicy(ble::SCAN_POLICY_IGNORE_WHITELIST), _ownAddressType(ble::own_address_type_t::PUBLIC) { for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { @@ -70,9 +70,9 @@ public: uint16_t maxConnectionInterval_ms, uint16_t slaveLatency, uint16_t connectionSupervisionTimeout_ms, - uint32_t _minEventLength_us, - uint32_t _maxEventLength_us, - ble::phy_t phy = ble::phy_t::LE_1M + ble::phy_t phy = ble::phy_t::LE_1M, + uint32_t _minEventLength_us = 0, + uint32_t _maxEventLength_us = 0xFFFF ) { uint8_t phy_index = handlePhyToggle(phy, true); @@ -102,7 +102,7 @@ public: return *this; } - GapExtendedConnectParameters_t& setScanParamteres( + GapExtendedConnectParameters_t& setOwnAddressType( ble::own_address_type_t ownAddress ) { _ownAddressType = ownAddress; @@ -110,7 +110,7 @@ public: return *this; } - GapExtendedConnectParameters_t& setScanParamteres( + GapExtendedConnectParameters_t& setFilterPolicy( ble::scanning_policy_mode_t filterPolicy ) { _filterPolicy = filterPolicy; From 8733d52da9f4a4a6b3d38649ce08610f4973f20f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 15:19:27 +0000 Subject: [PATCH 128/361] event types fixed --- features/FEATURE_BLE/ble/Gap.h | 89 ++++++++----------- .../ble/gap/ExtendedConnectParameters.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 14 +-- 4 files changed, 49 insertions(+), 58 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8604037d7c..13c5daf30c 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1183,6 +1183,21 @@ public: (void) connected; } + struct AdvertisingReportEvent_t { + AdvertisingEventType_t type; + PeerAddressType_t peerAddressType; + ble::address_t const &peerAddress; + Phy_t primaryPhy; + Phy_t secondaryPhy; + uint8_t SID; + int8_t txPower; + int8_t rssi; + int16_t periodicInterval; + PeerAddressType_t directAddressType; + const ble::address_t &directAddress; + mbed::Span advertisingData; + }; + /** * FIXME * @param type @@ -1199,31 +1214,29 @@ public: * @param advertisingData */ void onAdvertisingReport( - AdvertisingEventType_t type, - PeerAddressType_t peerAddressType, - BLEProtocol::AddressBytes_t const &peerAddress, - Phy_t primaryPhy, - Phy_t secondaryPhy, - uint8_t SID, - int8_t txPower, - int8_t rssi, - int16_t periodicInterval, - PeerAddressType_t directAddressType, - BLEProtocol::AddressBytes_t directAddress, - mbed::Span advertisingData + const AdvertisingReportEvent_t &event ) { - (void) type; - (void) peerAddressType; - (void) peerAddress; - (void) primaryPhy; - (void) secondaryPhy; - (void) SID; - (void) txPower; - (void) rssi; - (void) periodicInterval; - (void) directAddressType; - (void) directAddress; - (void) advertisingData; + (void) event; + } + + struct ConnectionCompleteEvent_t { + bool success; + Handle_t connectionHandle; + Role_t ownRole; + PeerAddressType_t peerAddressType; + const ble::address_t &peerAddress; + const ble::address_t &localResolvablePrivateAddress; + const ble::address_t &peerResolvablePrivateAddress; + uint16_t connectionInterval_us; + uint16_t connectionLatency; + uint16_t supervisionTimeout_ms; + uint16_t masterClockAccuracy_ppm; + }; + + void onConnectionComplete( + const ConnectionCompleteEvent_t &event + ) { + (void)event; } /** @@ -1285,32 +1298,6 @@ public: (void)rxPhy; } - void onConnectionComplete( - bool success, - Handle_t connectionHandle, - Role_t ownRole, - PeerAddressType_t peerAddressType, - const ble::address_t &peerAddress, - const ble::address_t &localResolvablePrivateAddress, - const ble::address_t &peerResolvablePrivateAddress, - uint16_t connectionInterval_us, - uint16_t connectionLatency, - uint16_t supervisionTimeout_ms, - uint16_t masterClockAccuracy_ppm - ) { - (void)success; - (void)connectionHandle; - (void)ownRole; - (void)peerAddressType; - (void)peerAddress; - (void)localResolvablePrivateAddress; - (void)peerResolvablePrivateAddress; - (void)connectionInterval_us; - (void)connectionLatency; - (void)supervisionTimeout_ms; - (void)masterClockAccuracy_ppm; - } - protected: /** * Prevent polymorphic deletion and avoid unnecessary virtual destructor @@ -1538,7 +1525,7 @@ public: */ virtual ble_error_t connect( TargetPeerAddressType_t peerAddressType, - const BLEProtocol::AddressBytes_t &peerAddress, + const ble::address_t &peerAddress, const GapExtendedConnectParameters_t &connectionParams ) { (void)peerAddressType; diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index 54764f912e..d839431610 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -38,7 +38,7 @@ public: _scanInterval[i] = 4; _scanWindow[i] = 4; _minConnectionInterval[i] = 6; - _maxConnectionInterval[i] = 6; + _maxConnectionInterval[i] = 0xC80; _slaveLatency[i] = 0; _connectionSupervisionTimeout[i] = 0xC80; _minEventLength[i] = 0; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 3aedfca6d4..df1f877032 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -236,7 +236,7 @@ public: */ virtual ble_error_t connect( ble::target_peer_address_type_t peerAddressType, - const BLEProtocol::AddressBytes_t &peerAddress, + const ble::address_t &peerAddress, const GapExtendedConnectParameters_t &connectionParams ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 5aa29b0ea6..c09eeae1b8 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -604,7 +604,7 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( ble::target_peer_address_type_t peerAddressType, - const BLEProtocol::AddressBytes_t &peerAddress, + const ble::address_t &peerAddress, const GapExtendedConnectParameters_t &connectionParams ) { if (!connectionParams.getNumberOfEnabledPhys()) { @@ -2178,7 +2178,7 @@ void GenericGap::on_enhanced_connection_complete( pal::clock_accuracy_t master_clock_accuracy ) { if (_eventHandler) { - _eventHandler->onConnectionComplete( + Gap::EventHandler::ConnectionCompleteEvent_t event = { (status==pal::hci_error_code_t::SUCCESS), (ble::connection_handle_t)connection_handle, (Gap::Role_t)own_role.value(), @@ -2190,7 +2190,9 @@ void GenericGap::on_enhanced_connection_complete( connection_latency, supervision_timeout * 10, master_clock_accuracy.getPpm() - ); + }; + + _eventHandler->onConnectionComplete(event); } } @@ -2211,7 +2213,7 @@ void GenericGap::on_extended_advertising_report( ) { if (_eventHandler) { - _eventHandler->onAdvertisingReport( + Gap::EventHandler::AdvertisingReportEvent_t event = { event_type, (PeerAddressType_t::type)(address_type? address_type->value() : connection_peer_address_type_t::PUBLIC_ADDRESS), (BLEProtocol::AddressBytes_t&)address, @@ -2224,7 +2226,9 @@ void GenericGap::on_extended_advertising_report( (PeerAddressType_t::type)direct_address_type.value(), (BLEProtocol::AddressBytes_t&)direct_address, mbed::make_Span(data, data_length) - ); + }; + + _eventHandler->onAdvertisingReport(event); } } From 00da0e571a92a8b6f4c4c886303082509affe661 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 15:52:57 +0000 Subject: [PATCH 129/361] fix review comments --- features/FEATURE_BLE/ble/pal/GapTypes.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 36 +++++++++---------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index b769ca2edf..b8262e2fc5 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -998,7 +998,7 @@ struct clock_accuracy_t : SafeEnum{ * * @return Parts per million as a number. */ - uint16_t getPpm() { + uint16_t get_ppm() { uint16_t ppm = 0; switch(value()) { diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index c09eeae1b8..b10e212eba 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1571,24 +1571,24 @@ void GenericGap::update_random_address() ); } } - } else { - ble::address_t address; - - if (!getUnresolvableRandomAddress(address)) { - return; - } - - ble_error_t err = _pal_gap.set_random_address( - address - ); - - if (err) { - return; - } - - _address_type = LegacyAddressType::RANDOM_PRIVATE_NON_RESOLVABLE; - _address = address; } + + ble::address_t address; + + if (!getUnresolvableRandomAddress(address)) { + return; + } + + ble_error_t err = _pal_gap.set_random_address( + address + ); + + if (err) { + return; + } + + _address_type = LegacyAddressType::RANDOM_PRIVATE_NON_RESOLVABLE; + _address = address; } bool GenericGap::getUnresolvableRandomAddress(ble::address_t& address) { @@ -2189,7 +2189,7 @@ void GenericGap::on_enhanced_connection_complete( connection_interval * 1250, connection_latency, supervision_timeout * 10, - master_clock_accuracy.getPpm() + master_clock_accuracy.get_ppm() }; _eventHandler->onConnectionComplete(event); From b6c7bd7960884356682731f6eb723d6ecf252bbb Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 12 Nov 2018 16:48:16 +0000 Subject: [PATCH 130/361] Merge pull request #1 from paul-szczepanek-arm/vincent connections --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b10e212eba..504dabcbec 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1632,6 +1632,10 @@ void GenericGap::set_connection_event_handler(pal::ConnectionEventMonitor::Event _connection_event_handler = connection_event_handler; } +const uint8_t GenericGap::MAX_ADVERTISING_SETS; + +const size_t GenericGap::MAX_HCI_DATA_LENGTH; + uint8_t GenericGap::getMaxAdvertisingSetNumber() { uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); From 74c2def5ef972f66a171e8af68ed954635e6749c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 10:26:14 +0000 Subject: [PATCH 131/361] BLE: Fix mutability in ble::advertising_event_t --- features/FEATURE_BLE/ble/BLETypes.h | 105 ---------------------------- 1 file changed, 105 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index c445340e20..b826aa420a 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -224,36 +224,6 @@ struct advertising_event_t { */ explicit advertising_event_t(uint8_t value) : value(value) { } - /** - * FIXME - * @param legacy_type - */ - advertising_event_t(advertising_type_t legacy_type) - { - switch (legacy_type) { - case ADV_CONNECTABLE_UNDIRECTED: - value = 0x23; - break; - case ADV_CONNECTABLE_DIRECTED: - value = 0x25; - break; - case ADV_SCANNABLE_UNDIRECTED: - value = 0x22; - break; - case ADV_NON_CONNECTABLE_UNDIRECTED: - value = 0x20; - break; - case ADV_CONNECTABLE_DIRECTED_LOW_DUTY: - value = 0x2D; - break; - } - } - - /** - * FIXME - */ - advertising_event_t() : value(0) { } - /** * FIXME * @return @@ -263,21 +233,6 @@ struct advertising_event_t { return static_cast(value & (1 << 0)); } - /** - * FIXME - * @param v - * @return - */ - advertising_event_t& connectable(bool v) - { - if (v) { - value |= (1 << 0); - } else { - value &= ~(1 << 0); - } - return *this; - } - /** * FIXME * @return @@ -287,21 +242,6 @@ struct advertising_event_t { return static_cast(value & (1 << 1)); } - /** - * FIXME - * @param v - * @return - */ - advertising_event_t& scannable_advertising(bool v) - { - if (v) { - value |= (1 << 1); - } else { - value &= ~(1 << 1); - } - return *this; - } - /** * FIXME * @return @@ -311,21 +251,6 @@ struct advertising_event_t { return static_cast(value & (1 << 2)); } - /** - * FIXME - * @param v - * @return - */ - advertising_event_t& directed_advertising(bool v) - { - if (v) { - value |= (1 << 2); - } else { - value &= ~(1 << 2); - } - return *this; - } - /** * FIXME * @return @@ -335,21 +260,6 @@ struct advertising_event_t { return static_cast(value & (1 << 3)); } - /** - * FIXME - * @param v - * @return - */ - advertising_event_t& scan_response(bool v) - { - if (v) { - value |= (1 << 3); - } else { - value &= ~(1 << 3); - } - return *this; - } - /** * FIXME * @return @@ -359,21 +269,6 @@ struct advertising_event_t { return static_cast(value & (1 << 4)); } - /** - * FIXME - * @param v - * @return - */ - advertising_event_t& legacy_advertising(bool v) - { - if (v) { - value |= (1 << 4); - } else { - value &= ~(1 << 4); - } - return *this; - } - /** * FIXME * @return From 194e2cb4f83d8094710f5cad275c332e41a678d6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 10:34:40 +0000 Subject: [PATCH 132/361] BLE: Move common type from pal to ble namespace. --- features/FEATURE_BLE/ble/BLETypes.h | 118 +++++++++++++++++ features/FEATURE_BLE/ble/generic/GenericGap.h | 4 +- features/FEATURE_BLE/ble/pal/GapTypes.h | 124 +----------------- features/FEATURE_BLE/ble/pal/PalGap.h | 8 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 +- 5 files changed, 130 insertions(+), 128 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index b826aa420a..88177f95fc 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -337,6 +337,25 @@ private: uint8_t value; }; +/** + * Identify an advertising SID. Range: [0x00, 0x0F] + */ +typedef uint8_t advertising_sid_t; + +// Range -127 <= N <= +20 +// Special value: 127 +// - RSSI not available. +typedef int8_t rssi_t; + +/** + * Describe the advertising power. + * + * Value comprised between -127 and +126 are considered power values in dBm while + * the special value 127 can be used as a wildcard to indicates that the host + * has no preference or if the power information is not available. + */ +typedef int8_t advertising_power_t; + /** * Advertising policy filter modes. * @@ -888,6 +907,13 @@ struct target_peer_address_type_t : ble::SafeEnum { /** struct scoped enum wrapped by the class */ enum type { + /** + * No phy selected. + * + * @note This value can be used to indicate the absence of phy + */ + NONE = 0, + /** * 1Mbit/s LE. * @@ -1064,6 +1090,98 @@ struct coded_symbol_per_bit_t :SafeEnum { SafeEnum(value) { } }; +/** + * Accuracy of the master clock. + */ +struct clock_accuracy_t : SafeEnum{ + enum type { + /** + * 500 PPM + */ + PPM_500 = 0x00, + + /** + * 250 PPM + */ + PPM_250 = 0x01, + + /** + * 150 PPM + */ + PPM_150 = 0x02, + + /** + * 100 PPM + */ + PPM_100 = 0x03, + + /** + * 75 PPM + */ + PPM_75 = 0x04, + + /** + * 50 PPM + */ + PPM_50 = 0x05, + + /** + * 30 PPM + */ + PPM_30 = 0x06, + + /** + * 20 PPM + */ + PPM_20 = 0x07 + }; + + /** Get clock accuracy. + * + * @return Parts per million as a number. + */ + uint16_t get_ppm() { + uint16_t ppm = 0; + + switch(value()) { + case PPM_500: + ppm = 500; + break; + case PPM_250: + ppm = 250; + break; + case PPM_150: + ppm = 150; + break; + case PPM_100: + ppm = 100; + break; + case PPM_75: + ppm = 75; + break; + case PPM_50: + ppm = 50; + break; + case PPM_30: + ppm = 30; + break; + case PPM_20: + ppm = 20; + break; + } + + return ppm; + } + + /** + * Construct a new clock_accuracy_t value. + */ + clock_accuracy_t(type value) : SafeEnum(value) { } + + explicit clock_accuracy_t(uint8_t raw_value) : + SafeEnum(static_cast(raw_value)) { } +}; + } // namespace ble /** diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index df1f877032..429160c6a0 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -555,7 +555,7 @@ private: const ble::address_t &address, phy_t primary_phy, const phy_t *secondary_phy, - pal::advertising_sid_t advertising_sid, + advertising_sid_t advertising_sid, pal::advertising_power_t tx_power, pal::rssi_t rssi, uint16_t periodic_advertising_interval, @@ -568,7 +568,7 @@ private: virtual void on_periodic_advertising_sync_established( pal::hci_error_code_t error, pal::sync_handle_t sync_handle, - pal::advertising_sid_t advertising_sid, + advertising_sid_t advertising_sid, pal::connection_peer_address_type_t advertiser_address_type, const ble::address_t &advertiser_address, uint16_t periodic_advertising_interval, diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index b8262e2fc5..4979434034 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -754,7 +754,7 @@ typedef uint16_t periodic_advertising_interval_t; // Range -127 <= N <= +20 // Special value: 127 // - RSSI not available. -typedef int8_t rssi_t; +typedef ble::rssi_t rssi_t; /** * Description of an advertising fragment. @@ -831,35 +831,9 @@ struct duplicates_filter_t : SafeEnum{ /** * Identify a periodic advertising sync. */ -typedef uint16_t sync_handle_t; +typedef ble::periodic_sync_handle_t sync_handle_t; -/** - * Identify an advertising SID. Range: [0x00, 0x0F] - */ -typedef uint8_t advertising_sid_t; - -struct advertising_data_status_t : SafeEnum{ - enum type { - COMPLETE = 0x00, - INCOMPLETE_MORE_DATA = 0x01, - INCOMPLETE_DATA_TRUNCATED = 0x02 - }; - - /** - * Construct a new advertising_data_status_t value. - */ - advertising_data_status_t(type value) : - SafeEnum(value) { } - - /** - * Explicit constructor from a raw value. - */ - explicit advertising_data_status_t(uint8_t value) : - SafeEnum( - static_cast(value) - ) - { } -}; +typedef ble::advertising_data_status_t advertising_data_status_t; struct extended_advertising_report_event_type_t { extended_advertising_report_event_type_t(uint8_t value) : value(value) { } @@ -943,97 +917,7 @@ struct direct_address_type_t : SafeEnum { explicit direct_address_type_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; -/** - * Accuracy of the master clock. - */ -struct clock_accuracy_t : SafeEnum{ - enum type { - /** - * 500 PPM - */ - PPM_500 = 0x00, - - /** - * 250 PPM - */ - PPM_250 = 0x01, - - /** - * 150 PPM - */ - PPM_150 = 0x02, - - /** - * 100 PPM - */ - PPM_100 = 0x03, - - /** - * 75 PPM - */ - PPM_75 = 0x04, - - /** - * 50 PPM - */ - PPM_50 = 0x05, - - /** - * 30 PPM - */ - PPM_30 = 0x06, - - /** - * 20 PPM - */ - PPM_20 = 0x07 - }; - - /** - * Construct a new clock_accuracy_t value. - */ - clock_accuracy_t(type value) : SafeEnum(value) { } - - /** Get clock accuracy. - * - * @return Parts per million as a number. - */ - uint16_t get_ppm() { - uint16_t ppm = 0; - - switch(value()) { - case PPM_500: - ppm = 500; - break; - case PPM_250: - ppm = 250; - break; - case PPM_150: - ppm = 150; - break; - case PPM_100: - ppm = 100; - break; - case PPM_75: - ppm = 75; - break; - case PPM_50: - ppm = 50; - break; - case PPM_30: - ppm = 30; - break; - case PPM_20: - ppm = 20; - break; - } - - return ppm; - } - - explicit clock_accuracy_t(uint8_t raw_value) : - SafeEnum(static_cast(raw_value)) { } -}; +typedef ble::clock_accuracy_t clock_accuracy_t; } // namespace pal } // namespace ble diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index ac160d66dc..ab807c5909 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -185,13 +185,13 @@ struct Gap { * report event. */ virtual void on_periodic_advertising_sync_established( - hci_error_code_t error, - sync_handle_t sync_handle, + pal::hci_error_code_t error, + pal::sync_handle_t sync_handle, advertising_sid_t advertising_sid, connection_peer_address_type_t advertiser_address_type, - const address_t &advertiser_address, + const ble::address_t &advertiser_address, uint16_t periodic_advertising_interval, - clock_accuracy_t clock_accuracy + pal::clock_accuracy_t clock_accuracy ) = 0; /** diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 504dabcbec..0d58fca1b2 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2206,7 +2206,7 @@ void GenericGap::on_extended_advertising_report( const ble::address_t &address, phy_t primary_phy, const phy_t *secondary_phy, - pal::advertising_sid_t advertising_sid, + advertising_sid_t advertising_sid, pal::advertising_power_t tx_power, pal::rssi_t rssi, uint16_t periodic_advertising_interval, @@ -2239,7 +2239,7 @@ void GenericGap::on_extended_advertising_report( void GenericGap::on_periodic_advertising_sync_established( pal::hci_error_code_t error, pal::sync_handle_t sync_handle, - pal::advertising_sid_t advertising_sid, + advertising_sid_t advertising_sid, connection_peer_address_type_t advertiser_address_type, const ble::address_t &advertiser_address, uint16_t periodic_advertising_interval, From 6a63948a7dc027608ab66e64cbcd1b122660b500 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 10:35:47 +0000 Subject: [PATCH 133/361] BLE: Add phy in sync exstablished event. --- features/FEATURE_BLE/ble/generic/GenericGap.h | 1 + features/FEATURE_BLE/ble/pal/PalGap.h | 1 + features/FEATURE_BLE/source/generic/GenericGap.cpp | 1 + .../FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp | 1 + 4 files changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 429160c6a0..4fa3e56f3e 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -571,6 +571,7 @@ private: advertising_sid_t advertising_sid, pal::connection_peer_address_type_t advertiser_address_type, const ble::address_t &advertiser_address, + phy_t advertiser_phy, uint16_t periodic_advertising_interval, pal::clock_accuracy_t clock_accuracy ); diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index ab807c5909..6a0d103049 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -190,6 +190,7 @@ struct Gap { advertising_sid_t advertising_sid, connection_peer_address_type_t advertiser_address_type, const ble::address_t &advertiser_address, + phy_t advertiser_phy, uint16_t periodic_advertising_interval, pal::clock_accuracy_t clock_accuracy ) = 0; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0d58fca1b2..40b194ad6f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2242,6 +2242,7 @@ void GenericGap::on_periodic_advertising_sync_established( advertising_sid_t advertising_sid, connection_peer_address_type_t advertiser_address_type, const ble::address_t &advertiser_address, + phy_t advertiser_phy, uint16_t periodic_advertising_interval, pal::clock_accuracy_t clock_accuracy ) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index 782aa16b43..b27c81f581 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -445,6 +445,7 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->advSid, connection_peer_address_type_t(evt->advAddrType), evt->advAddr, + phy_t(evt->advPhy), evt->perAdvInterval, clock_accuracy_t(evt->clockAccuracy) ); From f136b0cb00e9b47a03fd00f7e33b90983ba092e0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 10:37:44 +0000 Subject: [PATCH 134/361] BLE: Rework Gap event handler. Every user facing event handler accept a single parameter type; event that contains all the event fields. That strategy allows us to extend the type later if required while we do not disrupt existing code. --- features/FEATURE_BLE/ble/Gap.h | 475 ++++++++++++++++-- .../FEATURE_BLE/source/generic/GenericGap.cpp | 100 +++- 2 files changed, 495 insertions(+), 80 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 13c5daf30c..9ba0525cf0 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1148,50 +1148,104 @@ public: * Definition of the general handler of Gap related events. */ struct EventHandler { - /** - * FIXME - * @param advHandle - * @param peerAddressType - * @param peerAddress - */ - virtual void onScanRequest( - AdvHandle_t advHandle, - PeerAddressType_t peerAddressType, - const BLEProtocol::AddressBytes_t &peerAddress - ) { - (void) advHandle; - (void) peerAddressType; - (void) peerAddress; - } - /** - * FIXME - * @param advHandle - * @param connection - * @param completed_events - * @param connected - */ - virtual void onAdvertisingEnd( - AdvHandle_t advHandle, - Handle_t connection, - uint8_t completed_events, - bool connected - ) { - (void) advHandle; - (void) connection; - (void) completed_events; - (void) connected; - } + struct AdvertisingReportEvent { + AdvertisingReportEvent( + const AdvertisingEventType_t &type, + const PeerAddressType_t &peerAddressType, + const ble::address_t &peerAddress, + const Phy_t &primaryPhy, + const Phy_t &secondaryPhy, + ble::advertising_sid_t SID, + ble::advertising_power_t txPower, + ble::rssi_t rssi, + int16_t periodicInterval, + const PeerAddressType_t &directAddressType, + const ble::address_t &directAddress, + const mbed::Span &advertisingData + ) : + type(type), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + primaryPhy(primaryPhy), + secondaryPhy(secondaryPhy), + SID(SID), + txPower(txPower), + rssi(rssi), + periodicInterval(periodicInterval), + directAddressType(directAddressType), + directAddress(directAddress), + advertisingData(advertisingData) { } - struct AdvertisingReportEvent_t { + const AdvertisingEventType_t &getType() const + { + return type; + } + + const PeerAddressType_t &getPeerAddressType() const + { + return peerAddressType; + } + + const ble::address_t &getPeerAddress() const + { + return peerAddress; + } + + const Phy_t &getPrimaryPhy() const + { + return primaryPhy; + } + + const Phy_t &getSecondaryPhy() const + { + return secondaryPhy; + } + + ble::advertising_sid_t getSID() const + { + return SID; + } + + ble::advertising_power_t getTxPower() const + { + return txPower; + } + + ble::rssi_t getRssi() const + { + return rssi; + } + + int16_t getPeriodicInterval() const + { + return periodicInterval; + } + + const PeerAddressType_t &getDirectAddressType() const + { + return directAddressType; + } + + const ble::address_t &getDirectAddress() const + { + return directAddress; + } + + const mbed::Span &getAdvertisingData() const + { + return advertisingData; + } + + private: AdvertisingEventType_t type; PeerAddressType_t peerAddressType; - ble::address_t const &peerAddress; + const ble::address_t &peerAddress; Phy_t primaryPhy; Phy_t secondaryPhy; - uint8_t SID; - int8_t txPower; - int8_t rssi; + ble::advertising_sid_t SID; + ble::advertising_power_t txPower; + ble::rssi_t rssi; int16_t periodicInterval; PeerAddressType_t directAddressType; const ble::address_t &directAddress; @@ -1200,26 +1254,93 @@ public: /** * FIXME - * @param type - * @param peerAddressType - * @param peerAddress - * @param primaryPhy - * @param secondaryPhy - * @param SID - * @param txPower - * @param rssi - * @param periodicInterval - * @param directAddressType - * @param directAddress - * @param advertisingData */ - void onAdvertisingReport( - const AdvertisingReportEvent_t &event - ) { + virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { (void) event; } - struct ConnectionCompleteEvent_t { + struct ConnectionCompleteEvent { + ConnectionCompleteEvent( + bool success, + Handle_t connectionHandle, + Role_t ownRole, + const PeerAddressType_t &peerAddressType, + const ble::address_t &peerAddress, + const ble::address_t &localResolvablePrivateAddress, + const ble::address_t &peerResolvablePrivateAddress, + uint16_t connectionInterval_us, + uint16_t connectionLatency, + uint16_t supervisionTimeout_ms, + uint16_t masterClockAccuracy_ppm + ) : + success(success), + connectionHandle(connectionHandle), + ownRole(ownRole), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + localResolvablePrivateAddress(localResolvablePrivateAddress), + peerResolvablePrivateAddress(peerResolvablePrivateAddress), + connectionInterval_us(connectionInterval_us), + connectionLatency(connectionLatency), + supervisionTimeout_ms(supervisionTimeout_ms), + masterClockAccuracy_ppm(masterClockAccuracy_ppm) { } + + bool isSuccess() const + { + return success; + } + + Handle_t getConnectionHandle() const + { + return connectionHandle; + } + + Role_t getOwnRole() const + { + return ownRole; + } + + const PeerAddressType_t &getPeerAddressType() const + { + return peerAddressType; + } + + const ble::address_t &getPeerAddress() const + { + return peerAddress; + } + + const ble::address_t &getLocalResolvablePrivateAddress() const + { + return localResolvablePrivateAddress; + } + + const ble::address_t &getPeerResolvablePrivateAddress() const + { + return peerResolvablePrivateAddress; + } + + uint16_t getConnectionInterval_us() const + { + return connectionInterval_us; + } + + uint16_t getConnectionLatency() const + { + return connectionLatency; + } + + uint16_t getSupervisionTimeout_ms() const + { + return supervisionTimeout_ms; + } + + uint16_t getMasterClockAccuracy_ppm() const + { + return masterClockAccuracy_ppm; + } + + private: bool success; Handle_t connectionHandle; Role_t ownRole; @@ -1234,11 +1355,255 @@ public: }; void onConnectionComplete( - const ConnectionCompleteEvent_t &event + const ConnectionCompleteEvent &event ) { (void)event; } + + struct PeriodicAdvertisingSyncEstablishedEvent { + PeriodicAdvertisingSyncEstablishedEvent( + ble_error_t status, + ble::periodic_sync_handle_t syncHandle, + ble::advertising_sid_t sid, + const PeerAddressType_t &peerAddressType, + const ble::address_t &peerAddress, + const Phy_t &peerPhy, + uint16_t advertisingInterval, + const ble::clock_accuracy_t &peerClockAccuracy + ) : + status(status), + syncHandle(syncHandle), + sid(sid), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + peerPhy(peerPhy), + advertisingInterval(advertisingInterval), + peerClockAccuracy(peerClockAccuracy) { } + + ble_error_t getStatus() const + { + return status; + } + + ble::periodic_sync_handle_t getSyncHandle() const + { + return syncHandle; + } + + ble::advertising_sid_t getSid() const + { + return sid; + } + + const PeerAddressType_t &getPeerAddressType() const + { + return peerAddressType; + } + + const ble::address_t &getPeerAddress() const + { + return peerAddress; + } + + const Phy_t &getPeerPhy() const + { + return peerPhy; + } + + uint16_t getAdvertisingInterval() const + { + return advertisingInterval; + } + + const ble::clock_accuracy_t &getPeerClockAccuracy() const + { + return peerClockAccuracy; + } + + private: + ble_error_t status; + ble::periodic_sync_handle_t syncHandle; + ble::advertising_sid_t sid; + PeerAddressType_t peerAddressType; + const ble::address_t& peerAddress; + Phy_t peerPhy; + uint16_t advertisingInterval; + ble::clock_accuracy_t peerClockAccuracy; + }; + + virtual void onPeriodicAdvertisingSyncEstablished( + const PeriodicAdvertisingSyncEstablishedEvent &event + ) + { + (void) event; + } + + struct PeriodicAdvertisingReportEvent { + PeriodicAdvertisingReportEvent( + ble::periodic_sync_handle_t syncHandle, + ble::advertising_power_t txPower, + ble::rssi_t rssi, + const ble::advertising_data_status_t &dataStatus, + const mbed::Span &payload + ) : + syncHandle(syncHandle), + txPower(txPower), + rssi(rssi), + dataStatus(dataStatus), + payload(payload) { } + + ble::periodic_sync_handle_t getSyncHandle() const + { + return syncHandle; + } + + ble::advertising_power_t getTxPower() const + { + return txPower; + } + + ble::rssi_t getRssi() const + { + return rssi; + } + + const ble::advertising_data_status_t &getDataStatus() const + { + return dataStatus; + } + + const mbed::Span &getPayload() const + { + return payload; + } + + private: + ble::periodic_sync_handle_t syncHandle; + ble::advertising_power_t txPower; + ble::rssi_t rssi; + ble::advertising_data_status_t dataStatus; + mbed::Span payload; + }; + + virtual void onPeriodicAdvertisingReportEvent( + const PeriodicAdvertisingReportEvent & event + ) + { + (void) event; + } + + struct PeriodicAdvertisingSyncLoss { + PeriodicAdvertisingSyncLoss(ble::periodic_sync_handle_t syncHandle) : + syncHandle(syncHandle) { } + + ble::periodic_sync_handle_t getSyncHandle() const + { + return syncHandle; + } + + private: + ble::periodic_sync_handle_t syncHandle; + }; + + virtual void onPeriodicAdvertisingSyncLoss( + const PeriodicAdvertisingSyncLoss &event + ) + { + (void) event; + } + + struct ScanTimeoutEvent { }; + + virtual void onScanTimeout(const ScanTimeoutEvent &) { } + + struct AdvertisingEndEvent_t { + AdvertisingEndEvent_t( + AdvHandle_t advHandle, + Handle_t connection, + uint8_t completed_events, + bool connected + ) : + advHandle(advHandle), + connection(connection), + completed_events(completed_events), + connected(connected) { } + + AdvHandle_t getAdvHandle() const + { + return advHandle; + } + + Handle_t getConnection() const + { + return connection; + } + + uint8_t getCompleted_events() const + { + return completed_events; + } + + bool isConnected() const + { + return connected; + } + + private: + AdvHandle_t advHandle; + Handle_t connection; + uint8_t completed_events; + bool connected; + }; + + /** + * FIXME + */ + virtual void onAdvertisingEnd(const AdvertisingEndEvent_t& event) { + (void) event; + } + + /** + * FIXME + */ + struct ScanRequestEvent_t { + ScanRequestEvent_t( + AdvHandle_t advHandle, + const PeerAddressType_t &peerAddressType, + const ble::address_t &peerAddress + ) : + advHandle(advHandle), + peerAddressType(peerAddressType), + peerAddress(peerAddress) { } + + AdvHandle_t getAdvHandle() const + { + return advHandle; + } + + const PeerAddressType_t &getPeerAddressType() const + { + return peerAddressType; + } + + const ble::address_t &getPeerAddress() const + { + return peerAddress; + } + + private: + AdvHandle_t advHandle; + PeerAddressType_t peerAddressType; + const ble::address_t &peerAddress; + }; + + /** + * FIXME + */ + virtual void onScanRequest(const ScanRequestEvent_t& event) { + (void) event; + } + /** * Function invoked when the current transmitter and receiver PHY have * been read for a given connection. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 40b194ad6f..1e47cad045 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1218,7 +1218,11 @@ void GenericGap::processDisconnectionEvent( void GenericGap::on_scan_timeout() { - _event_queue.post(mbed::callback(this, &GenericGap::process_scan_timeout)); + if (!_eventHandler) { + return; + } + + _eventHandler->onScanTimeout(::Gap::EventHandler::ScanTimeoutEvent()); } void GenericGap::process_scan_timeout() @@ -1864,6 +1868,7 @@ ble_error_t GenericGap::setAdvertisingData( &pal::Gap::set_extended_scan_response_data : &pal::Gap::set_extended_advertising_data; + // FIXME: Handle the case where the payload size is 0 for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { // select the operation based on the index op_t op(op_t::INTERMEDIATE_FRAGMENT); @@ -2181,8 +2186,12 @@ void GenericGap::on_enhanced_connection_complete( uint16_t supervision_timeout, pal::clock_accuracy_t master_clock_accuracy ) { - if (_eventHandler) { - Gap::EventHandler::ConnectionCompleteEvent_t event = { + if (!_eventHandler) { + return; + } + + _eventHandler->onConnectionComplete( + Gap::EventHandler::ConnectionCompleteEvent( (status==pal::hci_error_code_t::SUCCESS), (ble::connection_handle_t)connection_handle, (Gap::Role_t)own_role.value(), @@ -2194,10 +2203,8 @@ void GenericGap::on_enhanced_connection_complete( connection_latency, supervision_timeout * 10, master_clock_accuracy.get_ppm() - }; - - _eventHandler->onConnectionComplete(event); - } + ) + ); } void GenericGap::on_extended_advertising_report( @@ -2216,13 +2223,17 @@ void GenericGap::on_extended_advertising_report( const uint8_t *data ) { - if (_eventHandler) { - Gap::EventHandler::AdvertisingReportEvent_t event = { + if (!_eventHandler) { + return; + } + + _eventHandler->onAdvertisingReport( + ::Gap::EventHandler::AdvertisingReportEvent( event_type, - (PeerAddressType_t::type)(address_type? address_type->value() : connection_peer_address_type_t::PUBLIC_ADDRESS), + (PeerAddressType_t::type)(address_type ? address_type->value() : PeerAddressType_t::ANONYMOUS), (BLEProtocol::AddressBytes_t&)address, primary_phy, - secondary_phy? *secondary_phy : phy_t::LE_1M, + secondary_phy? *secondary_phy : phy_t::NONE, advertising_sid, tx_power, rssi, @@ -2230,10 +2241,8 @@ void GenericGap::on_extended_advertising_report( (PeerAddressType_t::type)direct_address_type.value(), (BLEProtocol::AddressBytes_t&)direct_address, mbed::make_Span(data, data_length) - }; - - _eventHandler->onAdvertisingReport(event); - } + ) + ); } void GenericGap::on_periodic_advertising_sync_established( @@ -2247,6 +2256,22 @@ void GenericGap::on_periodic_advertising_sync_established( pal::clock_accuracy_t clock_accuracy ) { + if (!_eventHandler) { + return; + } + + _eventHandler->onPeriodicAdvertisingSyncEstablished( + ::Gap::EventHandler::PeriodicAdvertisingSyncEstablishedEvent( + (error == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, + sync_handle, + advertising_sid, + static_cast(advertiser_address_type.value()), + advertiser_address, + advertiser_phy, + periodic_advertising_interval, + clock_accuracy + ) + ); } @@ -2259,12 +2284,30 @@ void GenericGap::on_periodic_advertising_report( const uint8_t *data ) { + if (!_eventHandler) { + return; + } + _eventHandler->onPeriodicAdvertisingReportEvent( + ::Gap::EventHandler::PeriodicAdvertisingReportEvent( + sync_handle, + tx_power, + rssi, + data_status, + mbed::make_const_Span(data, data_length) + ) + ); } void GenericGap::on_periodic_advertising_sync_loss(pal::sync_handle_t sync_handle) { + if (!_eventHandler) { + return; + } + _eventHandler->onPeriodicAdvertisingSyncLoss( + ::Gap::EventHandler::PeriodicAdvertisingSyncLoss(sync_handle) + ); } void GenericGap::on_advertising_set_terminated( @@ -2276,14 +2319,18 @@ void GenericGap::on_advertising_set_terminated( { _active_sets.clear(advertising_handle); - if (_eventHandler) { - _eventHandler->onAdvertisingEnd( + if (!_eventHandler) { + return; + } + + _eventHandler->onAdvertisingEnd( + ::Gap::EventHandler::AdvertisingEndEvent_t( advertising_handle, connection_handle, number_of_completed_extended_advertising_events, status == pal::hci_error_code_t::SUCCESS - ); - } + ) + ); } void GenericGap::on_scan_request_received( @@ -2292,14 +2339,17 @@ void GenericGap::on_scan_request_received( const ble::address_t &address ) { - if (_eventHandler) { - _eventHandler->onScanRequest( - advertising_handle, - (ble::peer_address_type_t::type)scanner_address_type.value(), - (const BLEProtocol::AddressBytes_t&)address - ); + if (!_eventHandler) { + return; } + _eventHandler->onScanRequest( + ::Gap::EventHandler::ScanRequestEvent_t( + advertising_handle, + (ble::peer_address_type_t::type) scanner_address_type.value(), + address + ) + ); } ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) From e04fd876f52ab843379bc1b3a7cdfba5f704282a Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 16:47:08 +0000 Subject: [PATCH 135/361] units --- features/FEATURE_BLE/ble/BLETypes.h | 31 +++++++++++++++++++++++++++++ features/FEATURE_BLE/ble/Gap.h | 12 +++++++++++ 2 files changed, 43 insertions(+) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 88177f95fc..e2e15c270f 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -42,6 +42,37 @@ void clamp(T& value, const R& min, const R& max) { } } +template +class unit_t { +public: + unit_t() : _value(0) { } + + unit_t(LayoutType value) : _value(value) { } + + void clamp() { + clamp(_value, min, max); + } + + LayoutType value() const { + return _value; + } + +private: + LayoutType _value; +}; + +typedef unit_t unit_adv_interval_t; +typedef unit_t unit_adv_duration_t; +typedef unit_t unit_scan_interval_t; +typedef unit_t unit_scan_window_t; +typedef unit_t unit_conn_interval_t; +typedef unit_t unit_slave_latency_t; +typedef unit_t unit_supervision_timeout_t; +typedef unit_t unit_conn_event_length_t; +typedef unit_t unit_sync_timeout_t; +typedef unit_t unit_ms_t; +typedef unit_t unit_us_t; + /** * Opaque reference to a connection. * diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9ba0525cf0..2f37676d87 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -528,6 +528,18 @@ public: unsigned connected : 1; }; + typedef ble::unit_adv_interval_t UnitAdvInterval_t; + typedef ble::unit_adv_duration_t UnitAdvDuration_t; + typedef ble::unit_scan_interval_t UnitScanInterval_t; + typedef ble::unit_scan_window_t UnitScanWindow_t; + typedef ble::unit_conn_interval_t UnitConnInterval_t; + typedef ble::unit_slave_latency_t UnitSlaveLatency_t; + typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t; + typedef ble::unit_conn_event_length_t UnitConnEventLength_t; + typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; + typedef ble::unit_ms_t UnitMs_t; + typedef ble::unit_us_t UnitUs_t; + /** * Opaque value type representing a connection handle. * From 8e18e191fb6646224e33374209cde645bef6d937 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 17:04:55 +0000 Subject: [PATCH 136/361] new units --- features/FEATURE_BLE/ble/BLETypes.h | 1 + features/FEATURE_BLE/ble/Gap.h | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index e2e15c270f..6750653324 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -70,6 +70,7 @@ typedef unit_t unit_slave_latency_t; typedef unit_t unit_supervision_timeout_t; typedef unit_t unit_conn_event_length_t; typedef unit_t unit_sync_timeout_t; +typedef unit_t unit_periodic_interval_t; typedef unit_t unit_ms_t; typedef unit_t unit_us_t; diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 2f37676d87..13dd486176 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -537,6 +537,7 @@ public: typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t; typedef ble::unit_conn_event_length_t UnitConnEventLength_t; typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; + typedef ble::unit_periodic_interval_t UnitPeriodicInterval_t; typedef ble::unit_ms_t UnitMs_t; typedef ble::unit_us_t UnitUs_t; @@ -2211,7 +2212,7 @@ public: */ virtual ble_error_t startAdvertising( AdvHandle_t handle, - uint16_t maxDuration = 0, + UnitAdvDuration_t maxDuration = 0, uint8_t maxEvents = 0 ) { @@ -2251,8 +2252,8 @@ public: */ virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - uint32_t periodicAdvertisingIntervalMinMs, - uint32_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower = true ) { (void) handle; From 7b4439567d95aa84de3238710f320d6b178db928 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 17:41:04 +0000 Subject: [PATCH 137/361] comparison operator --- features/FEATURE_BLE/ble/BLETypes.h | 9 ++++-- features/FEATURE_BLE/ble/generic/GenericGap.h | 6 ++-- .../FEATURE_BLE/source/generic/GenericGap.cpp | 29 ++++++------------- 3 files changed, 19 insertions(+), 25 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 6750653324..d5917ba908 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -53,10 +53,14 @@ public: clamp(_value, min, max); } - LayoutType value() const { + const LayoutType& value() const { return _value; } + bool operator>(unit_t const& other) const { + return _value > other._value; + } + private: LayoutType _value; }; @@ -66,7 +70,6 @@ typedef unit_t unit_adv_duration_t; typedef unit_t unit_scan_interval_t; typedef unit_t unit_scan_window_t; typedef unit_t unit_conn_interval_t; -typedef unit_t unit_slave_latency_t; typedef unit_t unit_supervision_timeout_t; typedef unit_t unit_conn_event_length_t; typedef unit_t unit_sync_timeout_t; @@ -74,6 +77,8 @@ typedef unit_t unit_periodic_interval_t; typedef unit_t unit_ms_t; typedef unit_t unit_us_t; +typedef unit_t unit_slave_latency_t; + /** * Opaque reference to a connection. * diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 4fa3e56f3e..2a01a17655 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -106,7 +106,7 @@ public: ble_error_t startAdvertising( AdvHandle_t handle, - uint16_t maxDuration, + UnitAdvDuration_t maxDuration, uint8_t maxEvents ); @@ -116,8 +116,8 @@ public: virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - uint32_t periodicAdvertisingIntervalMinMs, - uint32_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 1e47cad045..0b874676ac 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1904,7 +1904,7 @@ ble_error_t GenericGap::setAdvertisingData( ble_error_t GenericGap::startAdvertising( AdvHandle_t handle, - uint16_t maxDuration, + UnitAdvDuration_t maxDuration, uint8_t maxEvents ) { ble_error_t error = BLE_ERROR_NONE; @@ -1928,10 +1928,10 @@ ble_error_t GenericGap::startAdvertising( } _advertising_timeout.detach(); - if (maxDuration) { + if (maxDuration.value()) { _advertising_timeout.attach_us( mbed::callback(this, &GenericGap::on_advertising_timeout), - maxDuration + maxDuration.value() ); } } else { @@ -1954,7 +1954,7 @@ ble_error_t GenericGap::startAdvertising( /* enable */ true, /* number of advertising sets */ 1, &handle, - &maxDuration, + &maxDuration.value(), &maxEvents ); @@ -2009,23 +2009,12 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { ble_error_t GenericGap::setPeriodicAdvertisingParameters( Gap::AdvHandle_t handle, - uint32_t periodicAdvertisingIntervalMinMs, - uint32_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, bool advertiseTxPower ) { - uint32_t interval_min = (periodicAdvertisingIntervalMinMs * 100) / 125; - uint32_t interval_max = (periodicAdvertisingIntervalMaxMs * 100) / 125; - - if (interval_min < 6 || interval_min > 0xFFFF) { - return BLE_ERROR_INVALID_PARAM; - } - - if (interval_max < 6 || interval_max > 0xFFFF) { - return BLE_ERROR_INVALID_PARAM; - } - - if (interval_min > interval_max) { + if (periodicAdvertisingIntervalMinMs > periodicAdvertisingIntervalMaxMs) { return BLE_ERROR_INVALID_PARAM; } @@ -2043,8 +2032,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( return _pal_gap.set_periodic_advertising_parameters( handle, - interval_min, - interval_max, + periodicAdvertisingIntervalMinMs.value(), + periodicAdvertisingIntervalMaxMs.value(), advertiseTxPower ); } From 57e4cdd732fa2dd9e3d740fa5111a64528ae2844 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 12 Nov 2018 18:46:41 +0000 Subject: [PATCH 138/361] new units --- features/FEATURE_BLE/ble/BLETypes.h | 14 ++++- features/FEATURE_BLE/ble/Gap.h | 24 +++---- .../ble/gap/ExtendedConnectParameters.h | 51 ++++++--------- features/FEATURE_BLE/ble/generic/GenericGap.h | 17 ++--- .../FEATURE_BLE/source/generic/GenericGap.cpp | 62 +++++++------------ 5 files changed, 77 insertions(+), 91 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index d5917ba908..93bc637d26 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -42,7 +42,7 @@ void clamp(T& value, const R& min, const R& max) { } } -template +template class unit_t { public: unit_t() : _value(0) { } @@ -50,23 +50,33 @@ public: unit_t(LayoutType value) : _value(value) { } void clamp() { - clamp(_value, min, max); + clamp(_value, value_min, value_max); } const LayoutType& value() const { return _value; } + uint32_t microseconds() const { + return _value * in_microseconds; + } + bool operator>(unit_t const& other) const { return _value > other._value; } + bool operator=(unit_t const& other) { + return _value = other._value; + } + private: LayoutType _value; }; typedef unit_t unit_adv_interval_t; typedef unit_t unit_adv_duration_t; +typedef unit_t unit_scan_duration_t; +typedef unit_t unit_scan_period_t; typedef unit_t unit_scan_interval_t; typedef unit_t unit_scan_window_t; typedef unit_t unit_conn_interval_t; diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 13dd486176..7e34fd8959 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -530,6 +530,8 @@ public: typedef ble::unit_adv_interval_t UnitAdvInterval_t; typedef ble::unit_adv_duration_t UnitAdvDuration_t; + typedef ble::unit_scan_duration_t UnitScanDuration_t; + typedef ble::unit_scan_period_t UnitScanPeriod_t; typedef ble::unit_scan_interval_t UnitScanInterval_t; typedef ble::unit_scan_window_t UnitScanWindow_t; typedef ble::unit_conn_interval_t UnitConnInterval_t; @@ -1259,7 +1261,7 @@ public: ble::advertising_sid_t SID; ble::advertising_power_t txPower; ble::rssi_t rssi; - int16_t periodicInterval; + UnitPeriodicInterval_t periodicInterval; PeerAddressType_t directAddressType; const ble::address_t &directAddress; mbed::Span advertisingData; @@ -1361,10 +1363,10 @@ public: const ble::address_t &peerAddress; const ble::address_t &localResolvablePrivateAddress; const ble::address_t &peerResolvablePrivateAddress; - uint16_t connectionInterval_us; - uint16_t connectionLatency; - uint16_t supervisionTimeout_ms; - uint16_t masterClockAccuracy_ppm; + UnitConnInterval_t connectionInterval; + UnitConnInterval_t connectionLatency; + UnitSupervisionTimeout_t supervisionTimeout; + uint16_t masterClockAccuracy /* parts per million */; }; void onConnectionComplete( @@ -2340,8 +2342,8 @@ public: */ virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, - uint16_t duration = 0, - uint16_t period = 0 + UnitScanDuration_t duration = 0, + UnitScanPeriod_t period = 0 ) { use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -2361,8 +2363,8 @@ public: PeerAddressType_t peerAddressType, Address_t peerAddress, uint8_t sid, - uint16_t maxPacketSkip, - uint32_t timeoutMs + UnitSlaveLatency_t maxPacketSkip, + UnitSyncTimeout_t timeout ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; @@ -2375,8 +2377,8 @@ public: * @return */ virtual ble_error_t createSync( - uint16_t maxPacketSkip, - uint32_t timeoutMs + UnitSlaveLatency_t maxPacketSkip, + UnitSyncTimeout_t timeout ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index d839431610..a78fcf143f 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -50,54 +50,41 @@ public: /* setters */ GapExtendedConnectParameters_t& setScanParameters( - uint32_t scanInterval_us, - uint32_t scanWindow_us, + ble::unit_scan_interval_t scanInterval, + ble::unit_scan_window_t scanWindow, ble::phy_t phy = ble::phy_t::LE_1M ) { uint8_t phy_index = handlePhyToggle(phy, true); - _scanInterval[phy_index] = scanInterval_us / 625; - _scanWindow[phy_index] = scanWindow_us / 625; - - ble::clamp(_scanInterval[phy_index], 0x0004, 0xFFFF); - ble::clamp(_scanWindow[phy_index], 0x0004, 0xFFFF); + _scanInterval[phy_index] = scanInterval.value(); + _scanWindow[phy_index] = scanWindow.value(); return *this; } GapExtendedConnectParameters_t& setConnectionParameters( - uint16_t minConnectionInterval_ms, - uint16_t maxConnectionInterval_ms, - uint16_t slaveLatency, - uint16_t connectionSupervisionTimeout_ms, + ble::unit_conn_interval_t minConnectionInterval, + ble::unit_conn_interval_t maxConnectionInterval, + ble::unit_slave_latency_t slaveLatency, + ble::unit_supervision_timeout_t connectionSupervisionTimeout, ble::phy_t phy = ble::phy_t::LE_1M, - uint32_t _minEventLength_us = 0, - uint32_t _maxEventLength_us = 0xFFFF + ble::unit_conn_event_length_t minEventLength = 0, + ble::unit_conn_event_length_t maxEventLength = 0xFFFF ) { uint8_t phy_index = handlePhyToggle(phy, true); - _minConnectionInterval[phy_index] = (((uint32_t)minConnectionInterval_ms) * 1000) / 1250; - _maxConnectionInterval[phy_index] = (((uint32_t)maxConnectionInterval_ms) * 1000) / 1250; - _slaveLatency[phy_index] = slaveLatency; - - ble::clamp(_minConnectionInterval[phy_index], 0x0006, 0x0C80); - ble::clamp(_maxConnectionInterval[phy_index], 0x0006, 0x0C80); - ble::clamp(_slaveLatency[phy_index], 0x0000, 0x01F3); - - /* avoid overlfow */ - uint32_t connectionSupervisionTimeout_10ms = connectionSupervisionTimeout_ms * 10; - ble::clamp(connectionSupervisionTimeout_10ms, 0x000A, 0x0C80); - _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout_10ms; + _minConnectionInterval[phy_index] = minConnectionInterval.value(); + _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); + _slaveLatency[phy_index] = slaveLatency.value(); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); /* avoid overflows and truncation */ - _minEventLength_us = _minEventLength_us / 625; - _maxEventLength_us = _maxEventLength_us / 625; + if (minEventLength > maxEventLength) { + minEventLength = maxEventLength; + } - ble::clamp(_minEventLength_us, 0x0000, 0xFFFF); - ble::clamp(_maxEventLength_us, 0x0000, 0xFFFF); - - _minEventLength[phy_index] = _minEventLength_us; - _maxEventLength[phy_index] = _maxEventLength_us; + _minEventLength[phy_index] = minEventLength.value(); + _maxEventLength[phy_index] = maxEventLength.value(); return *this; } diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 2a01a17655..a549fd1286 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -116,8 +116,8 @@ public: virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, - UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMin, + UnitPeriodicInterval_t periodicAdvertisingIntervalMax, bool advertiseTxPower ); @@ -136,19 +136,22 @@ public: virtual ble_error_t startScan( scanning_filter_duplicates_t filtering, - uint16_t duration_ms, - uint16_t period_ms + UnitScanDuration_t duration, + UnitScanPeriod_t period ); virtual ble_error_t createSync( PeerAddressType_t peerAddressType, uint8_t *peerAddress, uint8_t sid, - uint16_t maxPacketSkip, - uint32_t timeoutMs + Gap::UnitSlaveLatency_t maxPacketSkip, + Gap::UnitSyncTimeout_t timeout ); - virtual ble_error_t createSync(uint16_t maxPacketSkip, uint32_t timeoutMs); + virtual ble_error_t createSync( + Gap::UnitSlaveLatency_t maxPacketSkip, + Gap::UnitSyncTimeout_t timeout + ); virtual ble_error_t cancelCreateSync(); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0b874676ac..281b6cf6b6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1931,7 +1931,7 @@ ble_error_t GenericGap::startAdvertising( if (maxDuration.value()) { _advertising_timeout.attach_us( mbed::callback(this, &GenericGap::on_advertising_timeout), - maxDuration.value() + maxDuration.microseconds() ); } } else { @@ -2009,12 +2009,12 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { ble_error_t GenericGap::setPeriodicAdvertisingParameters( Gap::AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, - UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMin, + UnitPeriodicInterval_t periodicAdvertisingIntervalMax, bool advertiseTxPower ) { - if (periodicAdvertisingIntervalMinMs > periodicAdvertisingIntervalMaxMs) { + if (periodicAdvertisingIntervalMin > periodicAdvertisingIntervalMax) { return BLE_ERROR_INVALID_PARAM; } @@ -2032,8 +2032,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( return _pal_gap.set_periodic_advertising_parameters( handle, - periodicAdvertisingIntervalMinMs.value(), - periodicAdvertisingIntervalMaxMs.value(), + periodicAdvertisingIntervalMin.value(), + periodicAdvertisingIntervalMax.value(), advertiseTxPower ); } @@ -2388,8 +2388,8 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) ble_error_t GenericGap::startScan( scanning_filter_duplicates_t filtering, - uint16_t duration, - uint16_t period + UnitScanDuration_t duration, + UnitScanPeriod_t period ) { use_non_deprecated_scan_api(); @@ -2399,11 +2399,11 @@ ble_error_t GenericGap::startScan( return _pal_gap.extended_scan_enable( /* enable */true, (pal::duplicates_filter_t::type) filtering, - duration, - period + duration.value(), + period.value() ); } else { - if (period != 0) { + if (period.value() != 0) { return BLE_ERROR_INVALID_PARAM; } @@ -2417,10 +2417,10 @@ ble_error_t GenericGap::startScan( } _scan_timeout.detach(); - if (duration) { + if (duration.value()) { _scan_timeout.attach_us( mbed::callback(this, &GenericGap::on_scan_timeout), - duration * 10 /* ms */ * 1000 /* us */ + duration.microseconds() ); } @@ -2432,8 +2432,8 @@ ble_error_t GenericGap::createSync( Gap::PeerAddressType_t peerAddressType, uint8_t *peerAddress, uint8_t sid, - uint16_t maxPacketSkip, - uint32_t timeoutMs + UnitSlaveLatency_t maxPacketSkip, + UnitSyncTimeout_t timeout ) { if (is_extended_advertising_available() == false) { @@ -2450,47 +2450,31 @@ ble_error_t GenericGap::createSync( return BLE_ERROR_INVALID_PARAM; } - if (maxPacketSkip > 0x1F3) { - return BLE_ERROR_INVALID_PARAM; - } - - uint32_t timeout = timeoutMs / 10; - if (timeout < 0x000A || timeout > 0x4000) { - return BLE_ERROR_INVALID_PARAM; - } - return _pal_gap.periodic_advertising_create_sync( /* use advertiser list */ false, sid, (peer_address_type_t::type) peerAddressType.value(), peerAddress, - maxPacketSkip, - timeout + maxPacketSkip.value(), + timeout.value() ); } -ble_error_t GenericGap::createSync(uint16_t maxPacketSkip, uint32_t timeoutMs) -{ +ble_error_t GenericGap::createSync( + UnitSlaveLatency_t maxPacketSkip, + UnitSyncTimeout_t timeout +) { if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } - if (maxPacketSkip > 0x1F3) { - return BLE_ERROR_INVALID_PARAM; - } - - uint32_t timeout = timeoutMs / 10; - if (timeout < 0x000A || timeout > 0x4000) { - return BLE_ERROR_INVALID_PARAM; - } - return _pal_gap.periodic_advertising_create_sync( /* use advertiser list */ true, /* sid - not used */ 0x00, /* N/A */ peer_address_type_t::PUBLIC, /* N/A */ ble::address_t(), - maxPacketSkip, - timeout + maxPacketSkip.value(), + timeout.value() ); } From d01b4a53ee21466454b8c9f1524e70767f19536a Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 10:28:21 +0000 Subject: [PATCH 139/361] docs --- features/FEATURE_BLE/ble/Gap.h | 102 ++++++++++++++++++--------------- 1 file changed, 55 insertions(+), 47 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 7e34fd8959..2d7ae41d2a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1134,35 +1134,26 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; - /** - * FIXME - */ + /** Advertising handle used to identify advertising sets. */ typedef ble::advertising_handle_t AdvHandle_t; - /** - * FIXME - */ + /** Advertising handle used to identify periodic advertising sets. */ typedef ble::periodic_sync_handle_t PeriodicSyncHandle_t; - /** - * FIXME - */ + /** Type of advertisement scanned. */ typedef ble::advertising_event_t AdvertisingEventType_t; - /** - * FIXME - */ + /** Special advertising set handle used for the legacy advertising set. */ static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; - /** - * FIXME - */ + /** Special advertising set handle used as return or parameter to signify an invalid handle. */ static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; /** * Definition of the general handler of Gap related events. */ struct EventHandler { +<<<<<<< HEAD struct AdvertisingReportEvent { AdvertisingReportEvent( @@ -1253,24 +1244,28 @@ public: } private: - AdvertisingEventType_t type; - PeerAddressType_t peerAddressType; - const ble::address_t &peerAddress; - Phy_t primaryPhy; - Phy_t secondaryPhy; - ble::advertising_sid_t SID; - ble::advertising_power_t txPower; - ble::rssi_t rssi; - UnitPeriodicInterval_t periodicInterval; - PeerAddressType_t directAddressType; - const ble::address_t &directAddress; - mbed::Span advertisingData; + AdvertisingEventType_t type; /**< Type of advertising used. */ + PeerAddressType_t peerAddressType; /**< Peer address type of advertiser. */ + ble::address_t const &peerAddress; /**< Peer address of advertiser. */ + Phy_t primaryPhy; /**< PHY used on the primary channels. */ + Phy_t secondaryPhy; /**< PHY used on secondary channels. */ + ble::advertising_sid_t SID; /**< Set identification number. */ + ble::advertising_power_t txPower; /**< Transmission power reported by the packet. */ + ble::rssi_t rssi; /**< Measured signal strength. */ + UnitPeriodicInterval_t periodicInterval; /**< Interval of periodic advertising. */ + PeerAddressType_t directAddressType;/**< Directed advertising target address type. */ + const ble::address_t &directAddress; /**< Directed advertising target address. */ + mbed::Span advertisingData; /**< Advertising payload. */ }; - /** - * FIXME + /** Called when scanning reads an advertising packet during passive scan or receives + * a scan response during an active scan. + * + * @param event Advertising report @see AdvertisingReportEvent_t for details. */ - virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { + void onAdvertisingReport( + const AdvertisingReportEvent_t &event + ) { (void) event; } @@ -1356,17 +1351,17 @@ public: } private: - bool success; - Handle_t connectionHandle; - Role_t ownRole; - PeerAddressType_t peerAddressType; - const ble::address_t &peerAddress; - const ble::address_t &localResolvablePrivateAddress; - const ble::address_t &peerResolvablePrivateAddress; - UnitConnInterval_t connectionInterval; - UnitConnInterval_t connectionLatency; - UnitSupervisionTimeout_t supervisionTimeout; - uint16_t masterClockAccuracy /* parts per million */; + bool success; /**< True if connection succeeded. */ + Handle_t connectionHandle; /**< Connection handle if successful. */ + Role_t ownRole; /**< Role of the local device. */ + PeerAddressType_t peerAddressType; /**< Peer address type. */ + const ble::address_t &peerAddress; /**< Peer address. */ + const ble::address_t &localResolvablePrivateAddress; /**< Local address type if privacy enabled. */ + const ble::address_t &peerResolvablePrivateAddress; /**< Peer address type if privacy enabled. */ + UnitConnInterval_t connectionInterval; /**< Connection interval. */ + UnitSlaveLatency_t connectionLatency; /**< Connection latency in events. */ + UnitSupervisionTimeout_t supervisionTimeout; /**< Supervision timeout. */ + uint16_t masterClockAccuracy; /**< Peer clock accuracy in parts per million. */ }; void onConnectionComplete( @@ -1533,6 +1528,13 @@ public: virtual void onScanTimeout(const ScanTimeoutEvent &) { } struct AdvertisingEndEvent_t { + /** + * + * @param advHandle Advertising set handle. + * @param connection Connection handle. + * @param completed_events Number of events created during before advertising end. + * @param connected True if connection has been established. + */ AdvertisingEndEvent_t( AdvHandle_t advHandle, Handle_t connection, @@ -1571,10 +1573,13 @@ public: bool connected; }; - /** - * FIXME + /** Called when advertising ends. + * + * @param event Advertising end event: @see AdvertisingEndEvent_t for details. */ - virtual void onAdvertisingEnd(const AdvertisingEndEvent_t& event) { + virtual void onAdvertisingEnd( + const AdvertisingEndEvent_t& event + ) { (void) event; } @@ -1612,10 +1617,13 @@ public: const ble::address_t &peerAddress; }; - /** - * FIXME + /** Called when a scanning device request a scan response. + * + * @param event Scan request event: @see ScanRequestEvent_t for details. */ - virtual void onScanRequest(const ScanRequestEvent_t& event) { + virtual void onScanRequest( + const ScanRequestEvent_t& event + ) { (void) event; } From cfde4ed019202bf5f63ab4a73a5f28fa2022240b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 11:18:33 +0000 Subject: [PATCH 140/361] disallow removing the legacy handle --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 281b6cf6b6..59e3d70d00 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1688,6 +1688,10 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } + if (handle == LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } From bb8892a956ad96ccde22a8d3b103b83d2c731176 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 11:18:39 +0000 Subject: [PATCH 141/361] more docs --- features/FEATURE_BLE/ble/Gap.h | 159 ++++++++++++++++++--------------- 1 file changed, 86 insertions(+), 73 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 2d7ae41d2a..48d045a547 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1364,6 +1364,10 @@ public: uint16_t masterClockAccuracy; /**< Peer clock accuracy in parts per million. */ }; + /** Called when connection attempt ends. + * + * @param event Connection event @see ConnectionCompleteEvent_t for details. + */ void onConnectionComplete( const ConnectionCompleteEvent &event ) { @@ -2113,29 +2117,34 @@ public: /* advertising */ - /** - * FIXME - * @return + /** Return currently available number of supported advertising sets. + * This may change at runtime. + * + * @return Number of advertising sets that may be created at the same time. */ virtual uint8_t getMaxAdvertisingSetNumber() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 1; } - /** - * FIXME - * @return + /** Return maximum advertising data length supported. + * + * @return Maximum advertising data length supported. */ virtual uint8_t getMaxAdvertisingDataLength() { /* Requesting action from porter(s): override this API if this capability is supported. */ return 0x1F; } - /** - * FIXME - * @param handle - * @param parameters - * @return + /** Create an advertising set and apply the passed in parameters. The handle returned + * by this function must be used for all other calls that accept an advertising handle. + * When done with advertising, remove from the system using destroyAdvertisingSet(). + * + * @note The exception is the LEGACY_ADVERTISING_HANDLE which may be used at any time. + * + * @param[out] handle Advertising handle returned, valid only if function returned success. + * @param parameters Advertising parameters for the newly created set. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createAdvertisingSet( AdvHandle_t *handle, @@ -2147,10 +2156,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Remove the advertising set (resets its set parameters). The advertising set must not + * be active. + * + * @note LEGACY_ADVERTISING_HANDLE may not be destroyed. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { (void) handle; @@ -2158,11 +2170,11 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @param params - * @return + /** Set advertising parameters of an existing set. + * + * @param handle Advertising set handle. + * @param params New advertising parameters. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingParams( AdvHandle_t handle, @@ -2174,12 +2186,12 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @param payload - * @param minimiseFragmentation - * @return + /** Set new advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingPayload( AdvHandle_t handle, @@ -2193,12 +2205,12 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @param response - * @param minimiseFragmentation - * @return + /** Set new advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param response Advertising scan response. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingScanResponse( AdvHandle_t handle, @@ -2213,12 +2225,12 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @param maxDuration - * @param maxEvents - * @return + /** Start advertising using the given advertising set. + * + * @param handle Advertising set handle. + * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. + * @param maxEvents Max number of events produced during advertising - 0 means no limit. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startAdvertising( AdvHandle_t handle, @@ -2232,10 +2244,10 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Stop advertising given advertising set. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t stopAdvertising(AdvHandle_t handle) { (void) handle; @@ -2243,42 +2255,42 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Check if advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if advertising is active on this set. */ virtual bool isAdvertisingActive(AdvHandle_t handle) { return false; } - /** - * FIXME - * @param handle - * @param periodicAdvertisingIntervalMinMs - * @param periodicAdvertisingIntervalMaxMs + /** Set periodic advertising parameters for a given advertising set. + * + * @param handle Advertising set handle. + * @param periodicAdvertisingIntervalMin + * @param periodicAdvertisingIntervalMax * @param advertiseTxPower - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMinMs, - UnitPeriodicInterval_t periodicAdvertisingIntervalMaxMs, + UnitPeriodicInterval_t periodicAdvertisingIntervalMin, + UnitPeriodicInterval_t periodicAdvertisingIntervalMax, bool advertiseTxPower = true ) { (void) handle; - (void) periodicAdvertisingIntervalMinMs; - (void) periodicAdvertisingIntervalMaxMs; + (void) periodicAdvertisingIntervalMin; + (void) periodicAdvertisingIntervalMax; (void) advertiseTxPower; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @param payload - * @return + /** Set new periodic advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setPeriodicAdvertisingPayload( AdvHandle_t handle, @@ -2290,10 +2302,11 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Start periodic advertising for a given set. Periodic advertising will not start until + * normal advertising is running but will continue to run after normal advertising has stopped. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle) { @@ -2302,10 +2315,10 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Stop periodic advertising for a given set. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle) { @@ -2314,10 +2327,10 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param handle - * @return + /** Check if periodic advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if periodic advertising is active on this set. */ virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle) { From 4f769df9760b2586361d934917d074864be5afc7 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 11:40:51 +0000 Subject: [PATCH 142/361] merge fail --- features/FEATURE_BLE/ble/Gap.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 48d045a547..bed9ce5d3c 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1153,8 +1153,6 @@ public: * Definition of the general handler of Gap related events. */ struct EventHandler { -<<<<<<< HEAD - struct AdvertisingReportEvent { AdvertisingReportEvent( const AdvertisingEventType_t &type, From 642602c9254c44fb2020cfd8b01a9e6acef4d8f7 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 11:48:10 +0000 Subject: [PATCH 143/361] merge cleanup --- features/FEATURE_BLE/ble/Gap.h | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index bed9ce5d3c..9af23cb782 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1163,7 +1163,7 @@ public: ble::advertising_sid_t SID, ble::advertising_power_t txPower, ble::rssi_t rssi, - int16_t periodicInterval, + UnitPeriodicInterval_t periodicInterval, const PeerAddressType_t &directAddressType, const ble::address_t &directAddress, const mbed::Span &advertisingData @@ -1221,7 +1221,7 @@ public: return rssi; } - int16_t getPeriodicInterval() const + UnitPeriodicInterval_t getPeriodicInterval() const { return periodicInterval; } @@ -1262,7 +1262,7 @@ public: * @param event Advertising report @see AdvertisingReportEvent_t for details. */ void onAdvertisingReport( - const AdvertisingReportEvent_t &event + const AdvertisingReportEvent &event ) { (void) event; } @@ -1276,10 +1276,10 @@ public: const ble::address_t &peerAddress, const ble::address_t &localResolvablePrivateAddress, const ble::address_t &peerResolvablePrivateAddress, - uint16_t connectionInterval_us, - uint16_t connectionLatency, - uint16_t supervisionTimeout_ms, - uint16_t masterClockAccuracy_ppm + UnitConnInterval_t connectionInterval, + UnitSlaveLatency_t connectionLatency, + UnitSupervisionTimeout_t supervisionTimeout, + uint16_t masterClockAccuracy ) : success(success), connectionHandle(connectionHandle), @@ -1288,10 +1288,10 @@ public: peerAddress(peerAddress), localResolvablePrivateAddress(localResolvablePrivateAddress), peerResolvablePrivateAddress(peerResolvablePrivateAddress), - connectionInterval_us(connectionInterval_us), + connectionInterval(connectionInterval), connectionLatency(connectionLatency), - supervisionTimeout_ms(supervisionTimeout_ms), - masterClockAccuracy_ppm(masterClockAccuracy_ppm) { } + supervisionTimeout(supervisionTimeout), + masterClockAccuracy(masterClockAccuracy) { } bool isSuccess() const { @@ -1328,24 +1328,24 @@ public: return peerResolvablePrivateAddress; } - uint16_t getConnectionInterval_us() const + UnitConnInterval_t getConnectionInterval() const { - return connectionInterval_us; + return connectionInterval; } - uint16_t getConnectionLatency() const + UnitSlaveLatency_t getConnectionLatency() const { return connectionLatency; } - uint16_t getSupervisionTimeout_ms() const + UnitSupervisionTimeout_t getSupervisionTimeout() const { - return supervisionTimeout_ms; + return supervisionTimeout; } - uint16_t getMasterClockAccuracy_ppm() const + uint16_t getMasterClockAccuracy() const { - return masterClockAccuracy_ppm; + return masterClockAccuracy; } private: From 9fc577d6e6b05ee15d5a86f2a46112f1f946ad83 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 12:34:36 +0000 Subject: [PATCH 144/361] docs --- features/FEATURE_BLE/ble/BLETypes.h | 5 +-- features/FEATURE_BLE/ble/Gap.h | 69 ++++++++++++++--------------- 2 files changed, 36 insertions(+), 38 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 93bc637d26..df7159e842 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -389,9 +389,8 @@ private: */ typedef uint8_t advertising_sid_t; -// Range -127 <= N <= +20 -// Special value: 127 -// - RSSI not available. +/** Received signal strength. Range <-127, 20>. + * @note Special value 127 means RSSI is not available. */ typedef int8_t rssi_t; /** diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9af23cb782..3fb55ab8c1 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1500,8 +1500,7 @@ public: virtual void onPeriodicAdvertisingReportEvent( const PeriodicAdvertisingReportEvent & event - ) - { + ) { (void) event; } @@ -1520,8 +1519,7 @@ public: virtual void onPeriodicAdvertisingSyncLoss( const PeriodicAdvertisingSyncLoss &event - ) - { + ) { (void) event; } @@ -1529,6 +1527,8 @@ public: virtual void onScanTimeout(const ScanTimeoutEvent &) { } + /** Event produced when advertising ends + */ struct AdvertisingEndEvent_t { /** * @@ -1585,8 +1585,7 @@ public: (void) event; } - /** - * FIXME + /** Event produced when a peer requests a scan response from the advertiser. */ struct ScanRequestEvent_t { ScanRequestEvent_t( @@ -1904,10 +1903,12 @@ public: /** * Initiate a connection to a peer. * - * Once the connection is established, a ConnectionCallbackParams_t event is - * emitted to handlers that have been registered with onConnection(). + * Once the connection is established an onConnectionComplete in the event handler + * will be called. * - * FIXME + * @param peerAddressType + * @param peerAddress + * @param connectionParams * * @return BLE_ERROR_NONE if connection establishment procedure is started * successfully. The connectionCallChain (if set) is invoked upon @@ -2020,10 +2021,10 @@ public: * Set the preferred PHYs to use in a connection. * * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no - * preferred PHYs are set and the default value of the subsytem is used. + * preferred PHYs are set and the default value of the subsystem is used. * * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no - * preferred PHYs are set and the default value of the subsytem is used. + * preferred PHYs are set and the default value of the subsystem is used. * * @return BLE_ERROR_NONE if the preferences have been set or an appropriate * error code. @@ -2339,10 +2340,10 @@ public: /* scanning */ - /** - * FIXME - * @param params - * @return + /** Set new scan parameters + * + * @param params Scan paramters + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setScanParameters( const GapScanParameters& params @@ -2357,7 +2358,7 @@ public: * @param filtering * @param duration * @param period - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, @@ -2376,7 +2377,7 @@ public: * @param sid * @param maxPacketSkip * @param timeoutMs - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createSync( PeerAddressType_t peerAddressType, @@ -2393,7 +2394,7 @@ public: * FIXME * @param maxPacketSkip * @param timeoutMs - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createSync( UnitSlaveLatency_t maxPacketSkip, @@ -2405,7 +2406,7 @@ public: /** * FIXME - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t cancelCreateSync() { @@ -2427,7 +2428,7 @@ public: * @param peerAddressType * @param peerAddress * @param sid - * @return + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( PeerAddressType_t peerAddressType, @@ -2439,11 +2440,10 @@ public: } /** - * FIXME - * @param peerAddressType - * @param peerAddress - * @param sid - * @return + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( PeerAddressType_t peerAddressType, @@ -2454,18 +2454,17 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @return + /** Remove all devices from periodic advertiser list. + * + * @return BLE_ERROR_NONE on success. */ virtual ble_error_t clearPeriodicAdvertiserList() { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @return + /** Get number of devices that can be added to the periodic advertiser list. + * @return Number of devices that can be added to the periodic advertiser list. */ virtual uint8_t getMaxPeriodicAdvertiserListSize() { /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -2476,13 +2475,13 @@ protected: /* Override the following in the underlying adaptation layer to provide the * functionality of scanning. */ - /** - * FIXME + /** Can only be called if use_non_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. */ virtual void use_deprecated_scan_api() const { } - /** - * FIXME + /** Can only be called if use_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. */ virtual void use_non_deprecated_scan_api() const { } From 360336c89c3cdb93d3ad0862cce8e2c2f71b0c67 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 13:34:43 +0000 Subject: [PATCH 145/361] docs --- features/FEATURE_BLE/ble/Gap.h | 76 ++++++++++++++++++++-------------- 1 file changed, 46 insertions(+), 30 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 3fb55ab8c1..5c3e579605 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -2340,9 +2340,9 @@ public: /* scanning */ - /** Set new scan parameters + /** Set new scan parameters. * - * @param params Scan paramters + * @param params Scan parameters, @see GapScanParameters for details. * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setScanParameters( @@ -2353,11 +2353,17 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; }; - /** - * FIXME - * @param filtering - * @param duration - * @param period + /** Start scanning. + * + * @param filtering Filtering policy. + * @param duration How long to scan for. Special value 0 means scan forever. + * @param period How long to scan for in single period. If the period is 0 and duration + * is nonzero the scan will last for single duration. + * + * @note When the duration and period parameters are non-zero scanning will last for + * the duration within the period. After the scan period has expired a new scan period + * will begin and scanning. This will repeat until stopScan() is called. + * * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startScan( @@ -2370,13 +2376,16 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; }; - /** - * FIXME - * @param peerAddressType - * @param peerAddress - * @param sid - * @param maxPacketSkip - * @param timeoutMs + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receptions. If this time is + * exceeded, synchronisation is lost. * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createSync( @@ -2390,10 +2399,13 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param maxPacketSkip - * @param timeoutMs + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. Use periodic advertising sync list to determine who to sync with. + * + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receives. + * If this time is exceeded, synchronisation is lost. * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createSync( @@ -2404,8 +2416,8 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME + /** Cancel sync attempt. + * * @return BLE_ERROR_NONE on success. */ virtual ble_error_t cancelCreateSync() @@ -2414,20 +2426,23 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME + /** Stop reception of the periodic advertising identified by the handle. + * + * @param handle Periodic advertising synchronisation handle. + * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle) - { + virtual ble_error_t terminateSync( + PeriodicSyncHandle_t handle + ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * FIXME - * @param peerAddressType - * @param peerAddress - * @param sid + /** Add device to the periodic advertiser list. Cannot be called when sync is ongoing. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. * @return BLE_ERROR_NONE on success. */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( @@ -2439,7 +2454,8 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** + /** Remove device from the periodic advertiser list. Cannot be called when sync is ongoing. + * * @param peerAddressType Peer address type. * @param peerAddress Peer address. * @param sid Advertiser set identifier. From 8fe07b47be837270a5d2389b723d151c7b256736 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 13:38:57 +0000 Subject: [PATCH 146/361] docs --- features/FEATURE_BLE/ble/Gap.h | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 5c3e579605..7374ad00d2 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -2204,7 +2204,8 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** Set new advertising payload for a given advertising set. + /** Set new advertising scan response for a given advertising set. This will be sent to + * device who perform active scanning. * * @param handle Advertising set handle. * @param response Advertising scan response. @@ -2243,7 +2244,8 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** Stop advertising given advertising set. + /** Stop advertising given advertising set. This is separate from periodic advertising + * which will not be affected. * * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. @@ -2266,9 +2268,9 @@ public: /** Set periodic advertising parameters for a given advertising set. * * @param handle Advertising set handle. - * @param periodicAdvertisingIntervalMin - * @param periodicAdvertisingIntervalMax - * @param advertiseTxPower + * @param periodicAdvertisingIntervalMin Minimum interval for periodic advertising. + * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. + * @param advertiseTxPower Include transmission power in the advertisements. * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setPeriodicAdvertisingParameters( @@ -2527,7 +2529,7 @@ public: * Generic Access Service. * * A connected peer may read the characteristic exposing these parameters - * and request an update of the connection parameters to accomodate the + * and request an update of the connection parameters to accommodate the * local device. * * @param[in] params Value of the preferred connection parameters. From fa3869cf82bc131c6b7832b54e6ee54a99b7fec0 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 13:41:35 +0000 Subject: [PATCH 147/361] docs --- features/FEATURE_BLE/ble/BLETypes.h | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index df7159e842..9988b9ef8c 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -454,18 +454,10 @@ enum scanning_policy_mode_t { * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. */ enum scanning_filter_duplicates_t { - /** - * FIXME - */ - SCAN_FILTER_DUPLICATES_DISABLED = 0, - /** - * FIXME - */ - SCAN_FILTER_DUPLICATES_ENABLED = 1, - /** - * FIXME - */ - SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 + SCAN_FILTER_DUPLICATES_DISABLED = 0, /**< Do not remove duplicate reports. */ + SCAN_FILTER_DUPLICATES_ENABLED = 1, /**< Remove duplicate reports. */ + SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 /**< Remove reports which are duplicate + within a single period. */ }; /** From 9604c0187a645c32c85b84e92ed354fddb2e4297 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 13:54:31 +0000 Subject: [PATCH 148/361] BLE: Introduce Duration and Bounded classes. --- features/FEATURE_BLE/ble/BLETypes.h | 149 ++++++++++++++---- .../ble/gap/ExtendedConnectParameters.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 8 +- 3 files changed, 120 insertions(+), 39 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 9988b9ef8c..fa30d55bb4 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -42,52 +42,133 @@ void clamp(T& value, const R& min, const R& max) { } } -template -class unit_t { -public: - unit_t() : _value(0) { } +template +struct Duration { + Duration() : d(1) { } - unit_t(LayoutType value) : _value(value) { } + Duration(Representation v) : d(v) { } - void clamp() { - clamp(_value, value_min, value_max); + Representation value() const { + return d; } - const LayoutType& value() const { - return _value; + const Representation* operator&() const { + return &d; } - uint32_t microseconds() const { - return _value * in_microseconds; - } - - bool operator>(unit_t const& other) const { - return _value > other._value; - } - - bool operator=(unit_t const& other) { - return _value = other._value; + uint32_t value_us() const { + return d * Us; } private: - LayoutType _value; + Representation d; }; -typedef unit_t unit_adv_interval_t; -typedef unit_t unit_adv_duration_t; -typedef unit_t unit_scan_duration_t; -typedef unit_t unit_scan_period_t; -typedef unit_t unit_scan_interval_t; -typedef unit_t unit_scan_window_t; -typedef unit_t unit_conn_interval_t; -typedef unit_t unit_supervision_timeout_t; -typedef unit_t unit_conn_event_length_t; -typedef unit_t unit_sync_timeout_t; -typedef unit_t unit_periodic_interval_t; -typedef unit_t unit_ms_t; -typedef unit_t unit_us_t; +template +bool operator<(Duration lhs, Duration rhs) { + return lhs.value() < rhs.value(); +} -typedef unit_t unit_slave_latency_t; +template +bool operator<=(Duration lhs, Duration rhs) { + return lhs.value_us() < rhs.value_us(); +} + +template +bool operator==(Duration lhs, Duration rhs) { + return lhs.value_us() == rhs.value_us(); +} + +template +bool operator!=(Duration lhs, Duration rhs) { + return lhs.value_us() != rhs.value_us(); +} + +template +bool operator>=(Duration lhs, Duration rhs) { + return lhs.value_us() >= rhs.value_us(); +} + +template +bool operator>(Duration lhs, Duration rhs) { + return lhs.value_us() > rhs.value_us(); +} + +template +struct Bounded { + Bounded(T v) : _value(v) { + if (v < Min) { + _value = v; + } else if (v > Max) { + _value = v; + } + } + + T value() const { + return _value; + } + + static const T min = Min; + static const T max = Max; + +private: + T _value; +}; + +template +struct Bounded, Min, Max> { + Bounded(LayoutType v) : _value(v) { + if (v < Min) { + _value = Min; + } else if (v > Max) { + _value = Max; + } + } + + Bounded(Duration v) : _value(v) { + if (v.value() < Min) { + _value = Min; + } else if (v.value() > Max) { + _value = Max; + } + } + + LayoutType value() const { + return _value.value(); + } + + uint32_t value_us() const { + return _value.value_us(); + } + + const LayoutType* operator&() const { + return &_value; + } + + static const LayoutType min = Min; + static const LayoutType max = Max; + +private: + Duration _value; +}; + + +typedef Bounded, 0x20, 0xFFFFFF> unit_adv_interval_t; +typedef Bounded, 0x01, 0xFFFF> unit_adv_duration_t; +typedef Bounded, 0x01, 0xFFFF> unit_scan_duration_t; +typedef Bounded, 0x01, 0xFFFF> unit_scan_period_t; +typedef Bounded, 0x04, 0xFFFF> unit_scan_interval_t; +typedef Bounded, 0x04, 0xFFFF> unit_scan_window_t; +typedef Bounded, 0x06, 0x0C80> unit_conn_interval_t; +typedef Bounded, 0x0A, 0x0C80> unit_supervision_timeout_t; +typedef Bounded, 0, 0xFFFF> unit_conn_event_length_t; +typedef Bounded, 0x0A, 0x4000> unit_sync_timeout_t; +typedef Bounded, 0x06, 0xFFFF> unit_periodic_interval_t; + +typedef Bounded, 0, 0xFFFFFFFF> unit_ms_t; +typedef Bounded, 0, 0xFFFFFFFF> unit_us_t; + +typedef Bounded unit_slave_latency_t; /** * Opaque reference to a connection. diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index a78fcf143f..d8c73032c2 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -79,7 +79,7 @@ public: _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); /* avoid overflows and truncation */ - if (minEventLength > maxEventLength) { + if (minEventLength.value() > maxEventLength.value()) { minEventLength = maxEventLength; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 59e3d70d00..e22a82fae2 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1935,7 +1935,7 @@ ble_error_t GenericGap::startAdvertising( if (maxDuration.value()) { _advertising_timeout.attach_us( mbed::callback(this, &GenericGap::on_advertising_timeout), - maxDuration.microseconds() + maxDuration.value_us() ); } } else { @@ -1958,7 +1958,7 @@ ble_error_t GenericGap::startAdvertising( /* enable */ true, /* number of advertising sets */ 1, &handle, - &maxDuration.value(), + &maxDuration, &maxEvents ); @@ -2018,7 +2018,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( bool advertiseTxPower ) { - if (periodicAdvertisingIntervalMin > periodicAdvertisingIntervalMax) { + if (periodicAdvertisingIntervalMin.value() > periodicAdvertisingIntervalMax.value()) { return BLE_ERROR_INVALID_PARAM; } @@ -2424,7 +2424,7 @@ ble_error_t GenericGap::startScan( if (duration.value()) { _scan_timeout.attach_us( mbed::callback(this, &GenericGap::on_scan_timeout), - duration.microseconds() + duration.value_us() ); } From ff9b380c44e6ee41ea5740dd05b7cabbdde182f1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:39:05 +0000 Subject: [PATCH 149/361] BLE: Use secure types in GapScanParameters. --- features/FEATURE_BLE/ble/GapScanParameters.h | 48 +++++++++++++++----- 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapScanParameters.h b/features/FEATURE_BLE/ble/GapScanParameters.h index ae83d56b79..c875629958 100644 --- a/features/FEATURE_BLE/ble/GapScanParameters.h +++ b/features/FEATURE_BLE/ble/GapScanParameters.h @@ -31,6 +31,9 @@ class GapScanParameters { public: + typedef ble::unit_scan_window_t scan_window_t; + typedef ble::unit_scan_interval_t scan_interval_t; + enum own_address_type_t { PUBLIC_ADDRESS = 0x00, RANDOM_ADDRESS = 0x01, @@ -39,15 +42,34 @@ public: }; struct phy_configuration_t { - uint16_t interval; - uint16_t window; + phy_configuration_t( + scan_window_t scan_interval, + scan_interval_t scan_window, + bool active_scanning + ) : interval(scan_interval), + window(scan_window), + active_scanning(active_scanning) + { + if (window.value() > interval.value()) { + interval = window; + } + } + + scan_window_t interval; + scan_interval_t window; bool active_scanning; }; GapScanParameters() : own_address_type(PUBLIC_ADDRESS), - phy_1m_configuration(/* TODO */), - phy_coded_configuration(/* TODO */) + scanning_filter_policy(ble::SCAN_POLICY_IGNORE_WHITELIST), + phys(ble::phy_set_t::PHY_SET_1M), + phy_1m_configuration( + scan_interval_t::min(), scan_window_t::min(), true + ), + phy_coded_configuration( + scan_interval_t::min(), scan_window_t::min(), true + ) { } GapScanParameters& set_own_address_type(own_address_type_t address) @@ -85,14 +107,15 @@ public: } GapScanParameters& set_1m_phy_configuration( - uint16_t interval, - uint16_t window, + scan_interval_t interval, + scan_window_t window, bool active_scanning ) { phys.set_1m(true); - phy_configuration_t new_conf = { interval, window, active_scanning }; - phy_1m_configuration = new_conf; + phy_1m_configuration = phy_configuration_t( + interval, window, active_scanning + ); return *this; } @@ -102,14 +125,15 @@ public: } GapScanParameters& set_coded_phy_configuration( - uint16_t interval, - uint16_t window, + scan_interval_t interval, + scan_window_t window, bool active_scanning ) { phys.set_coded(true); - phy_configuration_t new_conf = { interval, window, active_scanning }; - phy_coded_configuration = new_conf; + phy_coded_configuration = phy_configuration_t( + interval, window, active_scanning + ); return *this; } From 09d22a329c1b5c9406ff58fb16e44b3285e5e256 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:40:16 +0000 Subject: [PATCH 150/361] BLE: Address special case when advertising payload size is 0. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index e22a82fae2..fca2d63c5a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1872,8 +1872,10 @@ ble_error_t GenericGap::setAdvertisingData( &pal::Gap::set_extended_scan_response_data : &pal::Gap::set_extended_advertising_data; - // FIXME: Handle the case where the payload size is 0 - for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { + for (size_t i = 0, end = payload.size(); + (i < end) || (i == 0 && end == 0); + i += MAX_HCI_DATA_LENGTH) + { // select the operation based on the index op_t op(op_t::INTERMEDIATE_FRAGMENT); if (end < MAX_HCI_DATA_LENGTH) { @@ -2065,7 +2067,10 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( typedef pal::advertising_fragment_description_t op_t; - for (size_t i = 0, end = payload.size(); i < end; i += MAX_HCI_DATA_LENGTH) { + for (size_t i = 0, end = payload.size(); + (i < end) || (i == 0 && end == 0); + i += MAX_HCI_DATA_LENGTH + ) { // select the operation based on the index op_t op(op_t::INTERMEDIATE_FRAGMENT); if (end < MAX_HCI_DATA_LENGTH) { From 6fccb11006c794337af345e1c42231ca1d8147ea Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:41:14 +0000 Subject: [PATCH 151/361] BLE: Deal with random address rotation where appropriate. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index fca2d63c5a..093d2d1cdf 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1740,8 +1740,6 @@ ble_error_t GenericGap::setAdvertisingParams( params.getChannel39() ); - // FIXME: check min and max adv value ??? or truncate ??? - return _pal_gap.set_advertising_parameters( params.getMinIntervalInADVUnits(), params.getMaxIntervalInADVUnits(), @@ -1993,7 +1991,6 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { return err; } _advertising_timeout.detach(); - // FIXME: Handle random address rotation of this advertising set } return _pal_gap.extended_advertising_enable( @@ -2117,7 +2114,6 @@ ble_error_t GenericGap::startPeriodicAdvertising(Gap::AdvHandle_t handle) } if (_active_sets.get(handle) == false) { - // FIXME: should we start periodic advertising behind the user's back ? return BLE_ERROR_INVALID_STATE; } @@ -2354,9 +2350,6 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) { use_non_deprecated_scan_api(); - // FIXME: validate parameters - // FIXME: deal with random address rotation - if (is_extended_advertising_available()) { bool active_scanning[] = { params.get_1m_configuration().active_scanning, @@ -2402,7 +2395,11 @@ ble_error_t GenericGap::startScan( ) { use_non_deprecated_scan_api(); - // FIXME: deal with random address rotation + + if(_privacy_enabled && _central_privacy_configuration.use_non_resolvable_random_address) + { + set_random_address_rotation(true); + } if (is_extended_advertising_available()) { return _pal_gap.extended_scan_enable( From 3e884a382efea38d0ee4761c6e6ea64e8f5b4a94 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:41:46 +0000 Subject: [PATCH 152/361] BLE: Initialisation of legacy advertising set. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 093d2d1cdf..28a073f009 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -432,7 +432,12 @@ GenericGap::GenericGap( _pal_gap.set_event_handler(this); - // FIXME: lazy initialization of the legacy advertising set + if (is_extended_advertising_available()) { + setExtendedAdvertisingParameters( + LEGACY_ADVERTISING_HANDLE, + GapAdvertisingParameters() + ); + } } GenericGap::~GenericGap() From 5ad50a20f804723f7c5df7f881e39d1da680c3a3 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:42:24 +0000 Subject: [PATCH 153/361] BLE: Add PHY precondition check in setScanParameters. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 28a073f009..50c83a59c8 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2380,6 +2380,10 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) scan_window ); } else { + if (params.get_scanning_phys().get_coded()) { + return BLE_ERROR_INVALID_PARAM; + } + GapScanParameters::phy_configuration_t legacy_configuration = params.get_1m_configuration(); From 4de9a613c8fd7318d1fb9d5acfb786134f6a5350 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 23:45:01 +0000 Subject: [PATCH 154/361] BLE: Add strict Duration type * Construction from representation type is explicit * Conversion between unit is only allowed if there is no precision loss * Range is built inside the type * More operators! * min and max values exposed as part of the interface --- features/FEATURE_BLE/ble/BLETypes.h | 252 ++++++++++++------ features/FEATURE_BLE/ble/Gap.h | 6 +- .../ble/gap/ExtendedConnectParameters.h | 4 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 24 +- 4 files changed, 190 insertions(+), 96 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index fa30d55bb4..148b35f21d 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -20,6 +20,7 @@ #include #include #include +#include "platform/mbed_assert.h" #include "ble/SafeEnum.h" #include "ble/ArrayView.h" @@ -42,56 +43,187 @@ void clamp(T& value, const R& min, const R& max) { } } -template +template +struct Range { + enum { + MIN = Min, + MAX = Max + }; +}; + +template +struct DefaultRange; + +template<> +struct DefaultRange { + typedef Range<0, 0xFF> type; +}; + +template<> +struct DefaultRange { + typedef Range<0, 0xFFFF> type; +}; + +template<> +struct DefaultRange { + typedef Range<0, 0xFFFFFFFF> type; +}; + + +template::type > struct Duration { - Duration() : d(1) { } + Duration() : duration() { } - Duration(Representation v) : d(v) { } + explicit Duration(Rep v) : duration(clamp(v)) { } - Representation value() const { - return d; + template + Duration(Duration other) : + duration(clamp(other.value() * (OtherTB / TB))) + { + MBED_STATIC_ASSERT(OtherTB >= TB && (OtherTB % TB) == 0, "Incompatible units"); } - const Representation* operator&() const { - return &d; + Rep value() { + return duration; } - uint32_t value_us() const { - return d * Us; + enum { + TIME_BASE = TB, + MIN = Range::MIN, + MAX = Range::MAX + }; + + static Duration min() + { + return Duration(MIN); + } + + static Duration max() + { + return Duration(MAX); + } + + const Rep* storage() const + { + return &duration; } private: - Representation d; + static Rep clamp(Rep in) { + if (in < MIN) { + return MIN; + } else if (in > MAX) { + return MAX; + } else { + return in; + } + } + + Rep duration; }; -template -bool operator<(Duration lhs, Duration rhs) { +typedef Duration microsecond_t; +typedef Duration millisecond_t; +typedef Duration second_t; + +template +DurationOut durationCast(Duration duration) { + return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); +} + +// ADDITION OPERATOR +template +microsecond_t operator+(Duration lhs, Duration rhs) { + return microsecond_t((lhs.value() * lhs.TIME_BASE) + (rhs.value() * rhs.TIME_BASE)); +} + +template +Duration operator+(Duration lhs, Duration rhs) { + return Duration(lhs.value() + rhs.value()); +} + +// MULTIPLICATION OPERATOR + +template +Duration operator*(Duration lhs, uint32_t rhs) { + return Duration(lhs.value() * rhs); +} + +template +Duration operator*(uint32_t lhs, Duration rhs) { + return Duration(lhs * rhs.value()); +} + +// LESS THAN + +template +bool operator<(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE < rhs.value() * rhs.TIME_BASE; +} + +template +bool operator<(Duration lhs, Duration rhs) { return lhs.value() < rhs.value(); } -template -bool operator<=(Duration lhs, Duration rhs) { - return lhs.value_us() < rhs.value_us(); +// LESS OR EQUAL TO + +template +bool operator<=(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; } -template -bool operator==(Duration lhs, Duration rhs) { - return lhs.value_us() == rhs.value_us(); +template +bool operator<=(Duration lhs, Duration rhs) { + return lhs.value() <= rhs.value(); } -template -bool operator!=(Duration lhs, Duration rhs) { - return lhs.value_us() != rhs.value_us(); +// EQUAL + +template +bool operator==(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; } -template -bool operator>=(Duration lhs, Duration rhs) { - return lhs.value_us() >= rhs.value_us(); +template +bool operator==(Duration lhs, Duration rhs) { + return lhs.value() == rhs.value(); } -template -bool operator>(Duration lhs, Duration rhs) { - return lhs.value_us() > rhs.value_us(); +// NOT EQUAL + +template +bool operator!=(Duration lhs, Duration rhs) { + return !(lhs == rhs); +} + +template +bool operator!=(Duration lhs, Duration rhs) { + return !(lhs == rhs); +} + +// GREATER OR EQUAL + +template +bool operator>=(Duration lhs, Duration rhs) { + return rhs <= lhs; +} + +template +bool operator>=(Duration lhs, Duration rhs) { + return rhs <= lhs; +} + +// GREATER THAN + +template +bool operator>(Duration lhs, Duration rhs) { + return rhs < lhs; +} + +template +bool operator>(Duration lhs, Duration rhs) { + return rhs < lhs; } template @@ -115,60 +247,22 @@ private: T _value; }; -template -struct Bounded, Min, Max> { - Bounded(LayoutType v) : _value(v) { - if (v < Min) { - _value = Min; - } else if (v > Max) { - _value = Max; - } - } +typedef Duration > unit_adv_interval_t; +typedef Duration > unit_adv_duration_t; +typedef Duration > unit_scan_duration_t; +typedef Duration > unit_scan_period_t; +typedef Duration > unit_scan_interval_t; +typedef Duration > unit_scan_window_t; +typedef Duration > unit_conn_interval_t; +typedef Duration > unit_supervision_timeout_t; +typedef Duration > unit_conn_event_length_t; +typedef Duration > unit_sync_timeout_t; +typedef Duration > unit_periodic_interval_t; - Bounded(Duration v) : _value(v) { - if (v.value() < Min) { - _value = Min; - } else if (v.value() > Max) { - _value = Max; - } - } +typedef Duration unit_ms_t; +typedef Duration unit_us_t; - LayoutType value() const { - return _value.value(); - } - - uint32_t value_us() const { - return _value.value_us(); - } - - const LayoutType* operator&() const { - return &_value; - } - - static const LayoutType min = Min; - static const LayoutType max = Max; - -private: - Duration _value; -}; - - -typedef Bounded, 0x20, 0xFFFFFF> unit_adv_interval_t; -typedef Bounded, 0x01, 0xFFFF> unit_adv_duration_t; -typedef Bounded, 0x01, 0xFFFF> unit_scan_duration_t; -typedef Bounded, 0x01, 0xFFFF> unit_scan_period_t; -typedef Bounded, 0x04, 0xFFFF> unit_scan_interval_t; -typedef Bounded, 0x04, 0xFFFF> unit_scan_window_t; -typedef Bounded, 0x06, 0x0C80> unit_conn_interval_t; -typedef Bounded, 0x0A, 0x0C80> unit_supervision_timeout_t; -typedef Bounded, 0, 0xFFFF> unit_conn_event_length_t; -typedef Bounded, 0x0A, 0x4000> unit_sync_timeout_t; -typedef Bounded, 0x06, 0xFFFF> unit_periodic_interval_t; - -typedef Bounded, 0, 0xFFFFFFFF> unit_ms_t; -typedef Bounded, 0, 0xFFFFFFFF> unit_us_t; - -typedef Bounded unit_slave_latency_t; +typedef Bounded unit_slave_latency_t; /** * Opaque reference to a connection. diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 7374ad00d2..e2f5c4469c 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -2234,7 +2234,7 @@ public: */ virtual ble_error_t startAdvertising( AdvHandle_t handle, - UnitAdvDuration_t maxDuration = 0, + UnitAdvDuration_t maxDuration = UnitAdvDuration_t(0), uint8_t maxEvents = 0 ) { @@ -2370,8 +2370,8 @@ public: */ virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, - UnitScanDuration_t duration = 0, - UnitScanPeriod_t period = 0 + UnitScanDuration_t duration = UnitScanDuration_t(0), + UnitScanPeriod_t period = UnitScanPeriod_t(0) ) { use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h index d8c73032c2..a9efba186a 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h @@ -68,8 +68,8 @@ public: ble::unit_slave_latency_t slaveLatency, ble::unit_supervision_timeout_t connectionSupervisionTimeout, ble::phy_t phy = ble::phy_t::LE_1M, - ble::unit_conn_event_length_t minEventLength = 0, - ble::unit_conn_event_length_t maxEventLength = 0xFFFF + ble::unit_conn_event_length_t minEventLength = ble::unit_conn_event_length_t(0), + ble::unit_conn_event_length_t maxEventLength = ble::unit_conn_event_length_t(0xFFFF) ) { uint8_t phy_index = handlePhyToggle(phy, true); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 50c83a59c8..9d8aaf5c9a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1940,7 +1940,7 @@ ble_error_t GenericGap::startAdvertising( if (maxDuration.value()) { _advertising_timeout.attach_us( mbed::callback(this, &GenericGap::on_advertising_timeout), - maxDuration.value_us() + durationCast(maxDuration).value() ); } } else { @@ -1963,7 +1963,7 @@ ble_error_t GenericGap::startAdvertising( /* enable */ true, /* number of advertising sets */ 1, &handle, - &maxDuration, + maxDuration.storage(), &maxEvents ); @@ -2198,9 +2198,9 @@ void GenericGap::on_enhanced_connection_complete( peer_address, local_resolvable_private_address, peer_resolvable_private_address, - connection_interval * 1250, + UnitConnInterval_t(connection_interval), connection_latency, - supervision_timeout * 10, + UnitSupervisionTimeout_t(supervision_timeout), master_clock_accuracy.get_ppm() ) ); @@ -2236,7 +2236,7 @@ void GenericGap::on_extended_advertising_report( advertising_sid, tx_power, rssi, - periodic_advertising_interval, + UnitPeriodicInterval_t(periodic_advertising_interval), (PeerAddressType_t::type)direct_address_type.value(), (BLEProtocol::AddressBytes_t&)direct_address, mbed::make_Span(data, data_length) @@ -2362,13 +2362,13 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) }; uint16_t scan_interval[] = { - params.get_1m_configuration().interval, - params.get_coded_configuration().interval + params.get_1m_configuration().interval.value(), + params.get_coded_configuration().interval.value() }; uint16_t scan_window[] = { - params.get_1m_configuration().window, - params.get_coded_configuration().window + params.get_1m_configuration().window.value(), + params.get_coded_configuration().window.value() }; return _pal_gap.set_extended_scan_parameters( @@ -2389,8 +2389,8 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) return _pal_gap.set_scan_parameters( legacy_configuration.active_scanning, - legacy_configuration.interval, - legacy_configuration.window, + legacy_configuration.interval.value(), + legacy_configuration.window.value(), (pal::own_address_type_t::type) params.get_own_address_type(), (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy() ); @@ -2435,7 +2435,7 @@ ble_error_t GenericGap::startScan( if (duration.value()) { _scan_timeout.attach_us( mbed::callback(this, &GenericGap::on_scan_timeout), - duration.value_us() + microsecond_t(duration).value() ); } From da22df74bc8cbba4b5e31e27603a2074a9a4838e Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 14:54:40 +0000 Subject: [PATCH 155/361] docs and synchronise connection result with other events --- features/FEATURE_BLE/ble/Gap.h | 92 +++++++++++++------ .../FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 2 files changed, 65 insertions(+), 29 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index e2f5c4469c..dfd08bd620 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -528,6 +528,7 @@ public: unsigned connected : 1; }; + /* Time units. */ typedef ble::unit_adv_interval_t UnitAdvInterval_t; typedef ble::unit_adv_duration_t UnitAdvDuration_t; typedef ble::unit_scan_duration_t UnitScanDuration_t; @@ -535,7 +536,6 @@ public: typedef ble::unit_scan_interval_t UnitScanInterval_t; typedef ble::unit_scan_window_t UnitScanWindow_t; typedef ble::unit_conn_interval_t UnitConnInterval_t; - typedef ble::unit_slave_latency_t UnitSlaveLatency_t; typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t; typedef ble::unit_conn_event_length_t UnitConnEventLength_t; typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; @@ -543,6 +543,9 @@ public: typedef ble::unit_ms_t UnitMs_t; typedef ble::unit_us_t UnitUs_t; + /** Measured in number of events. */ + typedef ble::unit_slave_latency_t UnitSlaveLatency_t; + /** * Opaque value type representing a connection handle. * @@ -1153,7 +1156,26 @@ public: * Definition of the general handler of Gap related events. */ struct EventHandler { + + /** Event generated when when an advertising packet is seen during passive scanning + * or a scan response is received during active scanning. + */ struct AdvertisingReportEvent { + /** Create a advertising report event. + * + * @param type Type of advertising used. + * @param peerAddressType Peer address type of advertiser. + * @param peerAddress Peer address of advertiser. + * @param primaryPhy PHY used on the primary channels. + * @param secondaryPhy PHY used on secondary channels. + * @param SID Set identification number. + * @param txPower Transmission power reported by the packet. + * @param rssi Measured signal strength. + * @param periodicInterval Interval of periodic advertising. + * @param directAddressType Directed advertising target address type. + * @param directAddress Directed advertising target address. + * @param advertisingData Advertising payload. + */ AdvertisingReportEvent( const AdvertisingEventType_t &type, const PeerAddressType_t &peerAddressType, @@ -1242,18 +1264,18 @@ public: } private: - AdvertisingEventType_t type; /**< Type of advertising used. */ - PeerAddressType_t peerAddressType; /**< Peer address type of advertiser. */ - ble::address_t const &peerAddress; /**< Peer address of advertiser. */ - Phy_t primaryPhy; /**< PHY used on the primary channels. */ - Phy_t secondaryPhy; /**< PHY used on secondary channels. */ - ble::advertising_sid_t SID; /**< Set identification number. */ - ble::advertising_power_t txPower; /**< Transmission power reported by the packet. */ - ble::rssi_t rssi; /**< Measured signal strength. */ - UnitPeriodicInterval_t periodicInterval; /**< Interval of periodic advertising. */ - PeerAddressType_t directAddressType;/**< Directed advertising target address type. */ - const ble::address_t &directAddress; /**< Directed advertising target address. */ - mbed::Span advertisingData; /**< Advertising payload. */ + AdvertisingEventType_t type; + PeerAddressType_t peerAddressType; + ble::address_t const &peerAddress; + Phy_t primaryPhy; + Phy_t secondaryPhy; + ble::advertising_sid_t SID; + ble::advertising_power_t txPower; + ble::rssi_t rssi; + UnitPeriodicInterval_t periodicInterval; + PeerAddressType_t directAddressType; + const ble::address_t &directAddress; + mbed::Span advertisingData; }; /** Called when scanning reads an advertising packet during passive scan or receives @@ -1268,8 +1290,22 @@ public: } struct ConnectionCompleteEvent { + /** Create a connection complete event. + * + * @param success BLE_ERROR_NONE if connection succeeded. + * @param connectionHandle Connection handle if successful. + * @param ownRole Role of the local device. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param localResolvablePrivateAddress Local address type if privacy enabled. + * @param peerResolvablePrivateAddress Peer address type if privacy enabled. + * @param connectionInterval Connection interval. + * @param connectionLatency Connection latency in events. + * @param supervisionTimeout Supervision timeout. + * @param masterClockAccuracy Peer clock accuracy in parts per million. + */ ConnectionCompleteEvent( - bool success, + ble_error_t status, Handle_t connectionHandle, Role_t ownRole, const PeerAddressType_t &peerAddressType, @@ -1281,7 +1317,7 @@ public: UnitSupervisionTimeout_t supervisionTimeout, uint16_t masterClockAccuracy ) : - success(success), + status(status), connectionHandle(connectionHandle), ownRole(ownRole), peerAddressType(peerAddressType), @@ -1293,9 +1329,9 @@ public: supervisionTimeout(supervisionTimeout), masterClockAccuracy(masterClockAccuracy) { } - bool isSuccess() const + ble_error_t getStatus() const { - return success; + return status; } Handle_t getConnectionHandle() const @@ -1349,17 +1385,17 @@ public: } private: - bool success; /**< True if connection succeeded. */ - Handle_t connectionHandle; /**< Connection handle if successful. */ - Role_t ownRole; /**< Role of the local device. */ - PeerAddressType_t peerAddressType; /**< Peer address type. */ - const ble::address_t &peerAddress; /**< Peer address. */ - const ble::address_t &localResolvablePrivateAddress; /**< Local address type if privacy enabled. */ - const ble::address_t &peerResolvablePrivateAddress; /**< Peer address type if privacy enabled. */ - UnitConnInterval_t connectionInterval; /**< Connection interval. */ - UnitSlaveLatency_t connectionLatency; /**< Connection latency in events. */ - UnitSupervisionTimeout_t supervisionTimeout; /**< Supervision timeout. */ - uint16_t masterClockAccuracy; /**< Peer clock accuracy in parts per million. */ + ble_error_t status; + Handle_t connectionHandle; + Role_t ownRole; + PeerAddressType_t peerAddressType; + const ble::address_t &peerAddress; + const ble::address_t &localResolvablePrivateAddress; + const ble::address_t &peerResolvablePrivateAddress; + UnitConnInterval_t connectionInterval; + UnitSlaveLatency_t connectionLatency; + UnitSupervisionTimeout_t supervisionTimeout; + uint16_t masterClockAccuracy; }; /** Called when connection attempt ends. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9d8aaf5c9a..b7b28de718 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2191,7 +2191,7 @@ void GenericGap::on_enhanced_connection_complete( _eventHandler->onConnectionComplete( Gap::EventHandler::ConnectionCompleteEvent( - (status==pal::hci_error_code_t::SUCCESS), + (status == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, (ble::connection_handle_t)connection_handle, (Gap::Role_t)own_role.value(), (ble::peer_address_type_t::type)peer_address_type.value(), From e9177fa2331fa7805a5aa3ef1945791bf1345ab1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 15:45:25 +0000 Subject: [PATCH 156/361] docs --- features/FEATURE_BLE/ble/Gap.h | 49 ++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index dfd08bd620..cfd1ad758d 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1289,6 +1289,8 @@ public: (void) event; } + /** Event generated when attempts to connect end (successfully or not). + */ struct ConnectionCompleteEvent { /** Create a connection complete event. * @@ -1408,8 +1410,20 @@ public: (void)event; } - + /** Event generated when we first receive a periodic advertisement. + */ struct PeriodicAdvertisingSyncEstablishedEvent { + /** Create advertising sync event. + * + * @param success BLE_ERROR_NONE if connection succeeded. + * @param syncHandle Advertising sync handle. + * @param sid Advertising set identifier. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param peerPhy Phy used for advertisements. + * @param advertisingInterval Periodic advertising interval. + * @param masterClockAccuracy Peer clock accuracy in parts per million. + */ PeriodicAdvertisingSyncEstablishedEvent( ble_error_t status, ble::periodic_sync_handle_t syncHandle, @@ -1480,19 +1494,32 @@ public: ble::clock_accuracy_t peerClockAccuracy; }; + /** Called when first advertising packet in periodic advertising is received. + * + * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. + */ virtual void onPeriodicAdvertisingSyncEstablished( const PeriodicAdvertisingSyncEstablishedEvent &event - ) - { + ) { (void) event; } + /** Event generated when periodic advertising packet is received. + */ struct PeriodicAdvertisingReportEvent { + /** Create periodic advertising report event. + * + * @param syncHandle Periodic advertising sync handle + * @param txPower TX power. + * @param rssi Received signal strength. + * @param dataStatus Status to indicate the completeness of the payload. + * @param payload Periodic advertisement payload. + */ PeriodicAdvertisingReportEvent( ble::periodic_sync_handle_t syncHandle, ble::advertising_power_t txPower, ble::rssi_t rssi, - const ble::advertising_data_status_t &dataStatus, + ble::advertising_data_status_t dataStatus, const mbed::Span &payload ) : syncHandle(syncHandle), @@ -1534,14 +1561,26 @@ public: mbed::Span payload; }; + /** Called when a periodic advertising packet is received. + * + * @param event Periodic advertisement event. + */ virtual void onPeriodicAdvertisingReportEvent( const PeriodicAdvertisingReportEvent & event ) { (void) event; } + /** Event generated when periodic advertising sync is lost. + */ struct PeriodicAdvertisingSyncLoss { - PeriodicAdvertisingSyncLoss(ble::periodic_sync_handle_t syncHandle) : + /** Create periodic advertising sync loss event. + * + * @param syncHandle Periodic advertising sync handle. + */ + PeriodicAdvertisingSyncLoss( + ble::periodic_sync_handle_t syncHandle + ) : syncHandle(syncHandle) { } ble::periodic_sync_handle_t getSyncHandle() const From 472e9ff9973c5e986b0dc9bf264c9141b8a6a471 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 16:50:38 +0000 Subject: [PATCH 157/361] Update mbed-os/features/FEATURE_BLE/ble/Gap.h Co-Authored-By: paul-szczepanek-arm --- features/FEATURE_BLE/ble/Gap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index cfd1ad758d..8d74a9cbd8 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1157,7 +1157,7 @@ public: */ struct EventHandler { - /** Event generated when when an advertising packet is seen during passive scanning + /** Event generated when an advertising packet is seen during passive scanning * or a scan response is received during active scanning. */ struct AdvertisingReportEvent { From 6eee528b793939e9959b9972a6aae9f9ba5e93ce Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 13 Nov 2018 16:50:53 +0000 Subject: [PATCH 158/361] Update mbed-os/features/FEATURE_BLE/ble/Gap.h Co-Authored-By: paul-szczepanek-arm --- features/FEATURE_BLE/ble/Gap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8d74a9cbd8..ff51b6bf3b 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1289,7 +1289,7 @@ public: (void) event; } - /** Event generated when attempts to connect end (successfully or not). + /** Event generated when a connection initiation end (successfully or not). */ struct ConnectionCompleteEvent { /** Create a connection complete event. From 0f4ac44bc5beaf6ac6e25916016f851b662e63fd Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 18:01:32 +0000 Subject: [PATCH 159/361] docs --- features/FEATURE_BLE/ble/BLETypes.h | 107 +++++++------------- features/FEATURE_BLE/ble/Gap.h | 148 ++++++++++++++-------------- 2 files changed, 111 insertions(+), 144 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 148b35f21d..ddad511be2 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -407,17 +407,13 @@ enum advertising_type_t { ADV_CONNECTABLE_DIRECTED_LOW_DUTY }; -/** - * FIXME +/** Used to indicate if the packet is complete and if it's truncated. */ struct advertising_data_status_t : SafeEnum{ - /** - * FIXME - */ enum type { - COMPLETE = 0x00, - INCOMPLETE_MORE_DATA = 0x01, - INCOMPLETE_DATA_TRUNCATED = 0x02 + COMPLETE = 0x00, /**< Advertising payload complete. */ + INCOMPLETE_MORE_DATA = 0x01, /**< Partial advertising payload, more to come. */ + INCOMPLETE_DATA_TRUNCATED = 0x02 /**< Advertising payload incomplete and no more is comoing. */ }; /** @@ -436,123 +432,94 @@ struct advertising_data_status_t : SafeEnum(value & (1 << 0)); } - /** - * FIXME - * @return + /** Is advertising scannable. + * + * @return True if scannable */ bool scannable_advertising() const { return static_cast(value & (1 << 1)); } - /** - * FIXME - * @return + /** Is advertising directed. + * + * @return True if directed. */ bool directed_advertising() const { return static_cast(value & (1 << 2)); } - /** - * FIXME - * @return + /** Is this a scan response. + * + * @return True if scan response. */ bool scan_response() const { return static_cast(value & (1 << 3)); } - /** - * FIXME - * @return + /** Is this legacy advertising. + * + * @return True if legacy. */ bool legacy_advertising() const { return static_cast(value & (1 << 4)); } - /** - * FIXME - * @return + /** Payload completeness status. + * + * @return @see advertising_data_status_t for details. */ advertising_data_status_t data_status() const { return static_cast((value >> 5) & 0x03); } - /** - * FIXME - * @return + /** Is payload complete. + * + * @return True if payload is coplete. */ bool complete() const { - return data_status() == advertising_data_status_t::COMPLETE; + return data_status().value() == advertising_data_status_t::COMPLETE; } - /** - * FIXME - * @return + /** Is there more data coming. + * + * @return True if more data coming. */ bool more_data_to_come() const { - return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; + return data_status().value() == advertising_data_status_t::INCOMPLETE_MORE_DATA; } - /** - * FIXME - * @return + /** Is the payload truncated. + * + * @return True if no more data coming. */ bool truncated() const { - return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; - } - - /** - * FIXME - * @param lhs - * @param rhs - * @return - */ - friend bool operator==( - const advertising_event_t &lhs, - const advertising_event_t &rhs - ) - { - return lhs.value == rhs.value; - } - - /** - * FIXME - * @param lhs - * @param rhs - * @return - */ - friend bool operator!=( - const advertising_event_t &lhs, - const advertising_event_t &rhs - ) - { - return !(rhs == lhs); + return data_status().value() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; } private: diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index ff51b6bf3b..d97f40701d 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1203,63 +1203,63 @@ public: directAddress(directAddress), advertisingData(advertisingData) { } - const AdvertisingEventType_t &getType() const - { + /** Get event type. */ + const AdvertisingEventType_t &getType() const { return type; } - const PeerAddressType_t &getPeerAddressType() const - { + /** Get peer address type. */ + const PeerAddressType_t &getPeerAddressType() const { return peerAddressType; } - const ble::address_t &getPeerAddress() const - { + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { return peerAddress; } - const Phy_t &getPrimaryPhy() const - { + /** Get primary PHY. */ + const Phy_t &getPrimaryPhy() const { return primaryPhy; } - const Phy_t &getSecondaryPhy() const - { + /** Get secondary PHY. */ + const Phy_t &getSecondaryPhy() const { return secondaryPhy; } - ble::advertising_sid_t getSID() const - { + /** Get advertising set identifier. */ + ble::advertising_sid_t getSID() const { return SID; } - ble::advertising_power_t getTxPower() const - { + /** Get TX power. */ + ble::advertising_power_t getTxPower() const { return txPower; } - ble::rssi_t getRssi() const - { + /** Get received signal strength. */ + ble::rssi_t getRssi() const { return rssi; } - UnitPeriodicInterval_t getPeriodicInterval() const - { + /** Get interval. */ + UnitPeriodicInterval_t getPeriodicInterval() const { return periodicInterval; } - const PeerAddressType_t &getDirectAddressType() const - { + /** Get target address type in directed advertising. */ + const PeerAddressType_t &getDirectAddressType() const { return directAddressType; } - const ble::address_t &getDirectAddress() const - { + /** Get target address in directed advertising. */ + const ble::address_t &getDirectAddress() const { return directAddress; } - const mbed::Span &getAdvertisingData() const - { + /** Get payload. */ + const mbed::Span &getAdvertisingData() const { return advertisingData; } @@ -1331,58 +1331,58 @@ public: supervisionTimeout(supervisionTimeout), masterClockAccuracy(masterClockAccuracy) { } - ble_error_t getStatus() const - { + /** Get connection complete event status. */ + ble_error_t getStatus() const { return status; } - Handle_t getConnectionHandle() const - { + /** Get connection handle (valid only when successful). */ + Handle_t getConnectionHandle() const { return connectionHandle; } - Role_t getOwnRole() const - { + /** Get own role. */ + Role_t getOwnRole() const { return ownRole; } - const PeerAddressType_t &getPeerAddressType() const - { + /** Get peer address type. */ + const PeerAddressType_t &getPeerAddressType() const { return peerAddressType; } - const ble::address_t &getPeerAddress() const - { + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { return peerAddress; } - const ble::address_t &getLocalResolvablePrivateAddress() const - { + /** Get get local resolvable random address if privacy is used. */ + const ble::address_t &getLocalResolvablePrivateAddress() const { return localResolvablePrivateAddress; } - const ble::address_t &getPeerResolvablePrivateAddress() const - { + /** Get peer resolvable private address if privacy is used. */ + const ble::address_t &getPeerResolvablePrivateAddress() const { return peerResolvablePrivateAddress; } - UnitConnInterval_t getConnectionInterval() const - { + /** Get connection interval. */ + UnitConnInterval_t getConnectionInterval() const { return connectionInterval; } - UnitSlaveLatency_t getConnectionLatency() const - { + /** Get connection latency. */ + UnitSlaveLatency_t getConnectionLatency() const { return connectionLatency; } - UnitSupervisionTimeout_t getSupervisionTimeout() const - { + /** Get supervision timeout. */ + UnitSupervisionTimeout_t getSupervisionTimeout() const { return supervisionTimeout; } - uint16_t getMasterClockAccuracy() const - { + /** Get clock accuracy in parts per million. */ + uint16_t getMasterClockAccuracy() const { return masterClockAccuracy; } @@ -1415,12 +1415,12 @@ public: struct PeriodicAdvertisingSyncEstablishedEvent { /** Create advertising sync event. * - * @param success BLE_ERROR_NONE if connection succeeded. + * @param success BLE_ERROR_NONE if synchronisation was achieved. * @param syncHandle Advertising sync handle. * @param sid Advertising set identifier. * @param peerAddressType Peer address type. * @param peerAddress Peer address. - * @param peerPhy Phy used for advertisements. + * @param peerPhy PHY used for advertisements. * @param advertisingInterval Periodic advertising interval. * @param masterClockAccuracy Peer clock accuracy in parts per million. */ @@ -1443,43 +1443,43 @@ public: advertisingInterval(advertisingInterval), peerClockAccuracy(peerClockAccuracy) { } - ble_error_t getStatus() const - { + /** Get sync establishment status. */ + ble_error_t getStatus() const { return status; } - ble::periodic_sync_handle_t getSyncHandle() const - { + /** Get periodic advertising sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { return syncHandle; } - ble::advertising_sid_t getSid() const - { + /** Get advertising set identifier. */ + ble::advertising_sid_t getSid() const { return sid; } - const PeerAddressType_t &getPeerAddressType() const - { + /** Get peer address type. */ + const PeerAddressType_t &getPeerAddressType() const { return peerAddressType; } - const ble::address_t &getPeerAddress() const - { + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { return peerAddress; } - const Phy_t &getPeerPhy() const - { + /** Get PHY used. */ + const Phy_t &getPeerPhy() const { return peerPhy; } - uint16_t getAdvertisingInterval() const - { + /** Get interval. */ + uint16_t getAdvertisingInterval() const { return advertisingInterval; } - const ble::clock_accuracy_t &getPeerClockAccuracy() const - { + /** Get clock accuracy in parts per million. */ + const ble::clock_accuracy_t &getPeerClockAccuracy() const { return peerClockAccuracy; } @@ -1528,28 +1528,28 @@ public: dataStatus(dataStatus), payload(payload) { } - ble::periodic_sync_handle_t getSyncHandle() const - { + /** Get periodic advertising sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { return syncHandle; } - ble::advertising_power_t getTxPower() const - { + /** Get TX power as reported by the advertising packet. */ + ble::advertising_power_t getTxPower() const { return txPower; } - ble::rssi_t getRssi() const - { + /** Get received signal strength. */ + ble::rssi_t getRssi() const { return rssi; } - const ble::advertising_data_status_t &getDataStatus() const - { + /** Get data completeness status. */ + const ble::advertising_data_status_t &getDataStatus() const { return dataStatus; } - const mbed::Span &getPayload() const - { + /** Get payload. */ + const mbed::Span &getPayload() const { return payload; } From f7310a07e95824103134bf9ebbf1a02a18b01f43 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 18:15:04 +0000 Subject: [PATCH 160/361] docs --- features/FEATURE_BLE/ble/Gap.h | 72 +++++++++++++++++++--------------- 1 file changed, 41 insertions(+), 31 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index d97f40701d..57fe891b94 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -529,19 +529,19 @@ public: }; /* Time units. */ - typedef ble::unit_adv_interval_t UnitAdvInterval_t; - typedef ble::unit_adv_duration_t UnitAdvDuration_t; - typedef ble::unit_scan_duration_t UnitScanDuration_t; - typedef ble::unit_scan_period_t UnitScanPeriod_t; - typedef ble::unit_scan_interval_t UnitScanInterval_t; - typedef ble::unit_scan_window_t UnitScanWindow_t; - typedef ble::unit_conn_interval_t UnitConnInterval_t; - typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t; - typedef ble::unit_conn_event_length_t UnitConnEventLength_t; - typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; - typedef ble::unit_periodic_interval_t UnitPeriodicInterval_t; - typedef ble::unit_ms_t UnitMs_t; - typedef ble::unit_us_t UnitUs_t; + typedef ble::unit_adv_interval_t UnitAdvInterval_t; /**< 625us */ + typedef ble::unit_adv_duration_t UnitAdvDuration_t; /**< 10ms */ + typedef ble::unit_scan_duration_t UnitScanDuration_t; /**< 10ms */ + typedef ble::unit_scan_period_t UnitScanPeriod_t; /**< 1.28ms */ + typedef ble::unit_scan_interval_t UnitScanInterval_t; /**< 625us */ + typedef ble::unit_scan_window_t UnitScanWindow_t; /**< 625us */ + typedef ble::unit_conn_interval_t UnitConnInterval_t; /**< 1.25ms */ + typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t;/**< 10ms */ + typedef ble::unit_conn_event_length_t UnitConnEventLength_t; /**< 625us */ + typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; /**< 10ms */ + typedef ble::unit_periodic_interval_t UnitPeriodicInterval_t; /**< 1.25ms */ + typedef ble::unit_ms_t UnitMs_t; /**< Milliseconds */ + typedef ble::unit_us_t UnitUs_t; /**< Microseconds */ /** Measured in number of events. */ typedef ble::unit_slave_latency_t UnitSlaveLatency_t; @@ -1583,8 +1583,8 @@ public: ) : syncHandle(syncHandle) { } - ble::periodic_sync_handle_t getSyncHandle() const - { + /** Get periodic sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { return syncHandle; } @@ -1598,14 +1598,18 @@ public: (void) event; } + /** Event generated when scan times out. + */ struct ScanTimeoutEvent { }; + /** Called when scan times out. + */ virtual void onScanTimeout(const ScanTimeoutEvent &) { } - /** Event produced when advertising ends + /** Event produced when advertising ends. */ struct AdvertisingEndEvent_t { - /** + /** Create advertising end event. * * @param advHandle Advertising set handle. * @param connection Connection handle. @@ -1623,23 +1627,23 @@ public: completed_events(completed_events), connected(connected) { } - AdvHandle_t getAdvHandle() const - { + /** Get advertising handle. */ + AdvHandle_t getAdvHandle() const { return advHandle; } - Handle_t getConnection() const - { + /** Get connection handle (valid only if connected successfully). */ + Handle_t getConnection() const { return connection; } - uint8_t getCompleted_events() const - { + /** Get how many events advertising created. */ + uint8_t getCompleted_events() const { return completed_events; } - bool isConnected() const - { + /** Has the advertising ended with a connection. */ + bool isConnected() const { return connected; } @@ -1663,6 +1667,12 @@ public: /** Event produced when a peer requests a scan response from the advertiser. */ struct ScanRequestEvent_t { + /** Create scan request event. + * + * @param advHandle Advertising handle. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + */ ScanRequestEvent_t( AdvHandle_t advHandle, const PeerAddressType_t &peerAddressType, @@ -1672,18 +1682,18 @@ public: peerAddressType(peerAddressType), peerAddress(peerAddress) { } - AdvHandle_t getAdvHandle() const - { + /** Get advertising handle. */ + AdvHandle_t getAdvHandle() const { return advHandle; } - const PeerAddressType_t &getPeerAddressType() const - { + /** Get peer address type. */ + const PeerAddressType_t &getPeerAddressType() const { return peerAddressType; } - const ble::address_t &getPeerAddress() const - { + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { return peerAddress; } From cf69013bb6ad2c1b6bd4dfd02320fa67e0f2d354 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 13 Nov 2018 18:32:28 +0000 Subject: [PATCH 161/361] docs --- features/FEATURE_BLE/ble/BLETypes.h | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index ddad511be2..962bee08a3 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -571,8 +571,6 @@ enum advertising_policy_mode_t { ADV_POLICY_FILTER_ALL_REQS = 3, }; - -// FIXME: Add new modes! /** * Scanning policy filter mode. * @@ -588,6 +586,27 @@ enum scanning_policy_mode_t { * The whitelist is used to filter incoming advertising. */ SCAN_POLICY_FILTER_ALL_ADV = 1, + + /** + * Accept all advertising packets except directed advertising packets + * where the initiator's identity address does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + SCAN_POLICY_IGNORE_WHITELIST_INCLUDE_UNRESOLVABLE = 2, + + /** + * Accept all advertising packets except: + * - advertising packets where the advertiser's + * identity address is not in the White List, + * - directed advertising packets where the initiator's identity address + * does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + SCAN_POLICY_FILTER_ALL_ADV_INCLUDE_UNRESOLVABLE = 3 }; /** From 2d1362c2c444361cd2d4726b252ffc788b6e7313 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 13:31:48 +0000 Subject: [PATCH 162/361] BLE: Move GapScanParameters header into ble/gap/ScanParameters --- features/FEATURE_BLE/ble/Gap.h | 20 ++++++++++++------- .../ScanParameters.h} | 14 ++++++------- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 4 files changed, 23 insertions(+), 17 deletions(-) rename features/FEATURE_BLE/ble/{GapScanParameters.h => gap/ScanParameters.h} (90%) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 57fe891b94..db891c7f32 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -19,17 +19,23 @@ #include "BLETypes.h" #include "BLEProtocol.h" -#include "GapAdvertisingData.h" + +// gap headers #include "ble/gap/AdvertisingDataBuilder.h" #include "ble/gap/ExtendedConnectParameters.h" -#include "GapAdvertisingParams.h" -#include "GapScanningParams.h" -#include "GapEvents.h" -#include "ble/GapScanParameters.h" +#include "ble/gap/ScanParameters.h" +#include "ble/gap/AdvertisingParameters.h" + +// leagacy gap headers +#include "ble/GapAdvertisingData.h" +#include "ble/GapAdvertisingParams.h" +#include "ble/GapScanningParams.h" +#include "ble/GapEvents.h" + #include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" -#include "gap/AdvertisingParameters.h" + /** * @addtogroup ble @@ -2433,7 +2439,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setScanParameters( - const GapScanParameters& params + const ScanParameters& params ) { use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/ble/GapScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h similarity index 90% rename from features/FEATURE_BLE/ble/GapScanParameters.h rename to features/FEATURE_BLE/ble/gap/ScanParameters.h index c875629958..329b238f1f 100644 --- a/features/FEATURE_BLE/ble/GapScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -29,7 +29,7 @@ */ -class GapScanParameters { +class ScanParameters { public: typedef ble::unit_scan_window_t scan_window_t; typedef ble::unit_scan_interval_t scan_interval_t; @@ -60,7 +60,7 @@ public: bool active_scanning; }; - GapScanParameters() : + ScanParameters() : own_address_type(PUBLIC_ADDRESS), scanning_filter_policy(ble::SCAN_POLICY_IGNORE_WHITELIST), phys(ble::phy_set_t::PHY_SET_1M), @@ -72,7 +72,7 @@ public: ) { } - GapScanParameters& set_own_address_type(own_address_type_t address) + ScanParameters& set_own_address_type(own_address_type_t address) { own_address_type = address; return *this; @@ -83,7 +83,7 @@ public: return own_address_type; } - GapScanParameters& set_scanning_filter_policy(ble::scanning_policy_mode_t filter_policy) + ScanParameters& set_scanning_filter_policy(ble::scanning_policy_mode_t filter_policy) { scanning_filter_policy = filter_policy; return *this; @@ -94,7 +94,7 @@ public: return scanning_filter_policy; } - GapScanParameters& set_scanning_phys(bool enable_1m, bool enable_coded) + ScanParameters& set_scanning_phys(bool enable_1m, bool enable_coded) { phys.set_1m(enable_1m); phys.set_coded(enable_coded); @@ -106,7 +106,7 @@ public: return phys; } - GapScanParameters& set_1m_phy_configuration( + ScanParameters& set_1m_phy_configuration( scan_interval_t interval, scan_window_t window, bool active_scanning @@ -124,7 +124,7 @@ public: return phy_1m_configuration; } - GapScanParameters& set_coded_phy_configuration( + ScanParameters& set_coded_phy_configuration( scan_interval_t interval, scan_window_t window, bool active_scanning diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index a549fd1286..4753ebaaec 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -132,7 +132,7 @@ public: virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle); - virtual ble_error_t setScanParameters(const GapScanParameters ¶ms); + virtual ble_error_t setScanParameters(const ScanParameters ¶ms); virtual ble_error_t startScan( scanning_filter_duplicates_t filtering, diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b7b28de718..a089e11142 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2351,7 +2351,7 @@ void GenericGap::on_scan_request_received( ); } -ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) +ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) { use_non_deprecated_scan_api(); @@ -2384,7 +2384,7 @@ ble_error_t GenericGap::setScanParameters(const GapScanParameters ¶ms) return BLE_ERROR_INVALID_PARAM; } - GapScanParameters::phy_configuration_t legacy_configuration = + ScanParameters::phy_configuration_t legacy_configuration = params.get_1m_configuration(); return _pal_gap.set_scan_parameters( From 4d3354077e45d515e174fc36bd4bc72708244c59 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 13:40:45 +0000 Subject: [PATCH 163/361] BLE: rename GapExtendedConnectParameters_t into ConnectionParameters --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- ...nectParameters.h => ConnectionParameters.h} | 18 +++++++++--------- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) rename features/FEATURE_BLE/ble/gap/{ExtendedConnectParameters.h => ConnectionParameters.h} (95%) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index db891c7f32..8576b7c880 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -22,7 +22,7 @@ // gap headers #include "ble/gap/AdvertisingDataBuilder.h" -#include "ble/gap/ExtendedConnectParameters.h" +#include "ble/gap/ConnectionParameters.h" #include "ble/gap/ScanParameters.h" #include "ble/gap/AdvertisingParameters.h" @@ -2008,7 +2008,7 @@ public: virtual ble_error_t connect( TargetPeerAddressType_t peerAddressType, const ble::address_t &peerAddress, - const GapExtendedConnectParameters_t &connectionParams + const ConnectionParameters &connectionParams ) { (void)peerAddressType; (void)peerAddress; diff --git a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h similarity index 95% rename from features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h rename to features/FEATURE_BLE/ble/gap/ConnectionParameters.h index a9efba186a..28c4359a3f 100644 --- a/features/FEATURE_BLE/ble/gap/ExtendedConnectParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -27,10 +27,10 @@ * @{ */ -class GapExtendedConnectParameters_t { +class ConnectionParameters { static const uint8_t MAX_PARAM_PHYS = 3; public: - GapExtendedConnectParameters_t() : + ConnectionParameters() : _filterPolicy(ble::SCAN_POLICY_IGNORE_WHITELIST), _ownAddressType(ble::own_address_type_t::PUBLIC) { @@ -49,7 +49,7 @@ public: /* setters */ - GapExtendedConnectParameters_t& setScanParameters( + ConnectionParameters& setScanParameters( ble::unit_scan_interval_t scanInterval, ble::unit_scan_window_t scanWindow, ble::phy_t phy = ble::phy_t::LE_1M @@ -62,7 +62,7 @@ public: return *this; } - GapExtendedConnectParameters_t& setConnectionParameters( + ConnectionParameters& setConnectionParameters( ble::unit_conn_interval_t minConnectionInterval, ble::unit_conn_interval_t maxConnectionInterval, ble::unit_slave_latency_t slaveLatency, @@ -89,7 +89,7 @@ public: return *this; } - GapExtendedConnectParameters_t& setOwnAddressType( + ConnectionParameters& setOwnAddressType( ble::own_address_type_t ownAddress ) { _ownAddressType = ownAddress; @@ -97,7 +97,7 @@ public: return *this; } - GapExtendedConnectParameters_t& setFilterPolicy( + ConnectionParameters& setFilterPolicy( ble::scanning_policy_mode_t filterPolicy ) { _filterPolicy = filterPolicy; @@ -105,7 +105,7 @@ public: return *this; } - GapExtendedConnectParameters_t& togglePhy( + ConnectionParameters& togglePhy( bool phy1M, bool phy2M, bool phyCoded @@ -117,7 +117,7 @@ public: return *this; } - GapExtendedConnectParameters_t& disablePhy( + ConnectionParameters& disablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { handlePhyToggle(phy, false); @@ -125,7 +125,7 @@ public: return *this; } - GapExtendedConnectParameters_t& enablePhy( + ConnectionParameters& enablePhy( ble::phy_t phy = ble::phy_t::LE_1M ) { handlePhyToggle(phy, true); diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 4753ebaaec..279eaa76aa 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -240,7 +240,7 @@ public: virtual ble_error_t connect( ble::target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, - const GapExtendedConnectParameters_t &connectionParams + const ConnectionParameters &connectionParams ); /** diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index a089e11142..e313782923 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -610,7 +610,7 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( ble::target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, - const GapExtendedConnectParameters_t &connectionParams + const ConnectionParameters &connectionParams ) { if (!connectionParams.getNumberOfEnabledPhys()) { return BLE_ERROR_INVALID_PARAM; From 3737e385af7c96de6b242abe56db382b00206f5f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 14:18:08 +0000 Subject: [PATCH 164/361] BLE: Expose ble::pal::connection_role_t in ble namespace. --- features/FEATURE_BLE/ble/BLETypes.h | 55 +++++++++++++++++++++++++ features/FEATURE_BLE/ble/pal/GapTypes.h | 15 +------ 2 files changed, 57 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 962bee08a3..48227f914a 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -1381,6 +1381,61 @@ struct clock_accuracy_t : SafeEnum{ SafeEnum(static_cast(raw_value)) { } }; +/** + * Enumeration of GAP roles. + * + * @note The BLE API does not express the broadcaster and scanner roles. + * + * @attention A device can fulfill different roles concurrently. + */ +struct connection_role_t :SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { + /** + * Central Role. + * + * The device can scan and initiate connection to peripherals. It + * acts as the master when a connection is established. + * + * @note A central is a scanner. + */ + CENTRAL = 0x00, + + /** + * @see CENTRAL + */ + MASTER = 0x00, + + /** + * Peripheral Role. + * + * The device can advertise and it can be connected by a central. It + * acts as a slave when connected. + * + * @note A peripheral is a broadcaster. + */ + PERIPHERAL = 0x01, + + /** + * @see SLAVE + */ + SLAVE = 0x01 + }; + + /** + * Construct a new instance of role_t. + */ + connection_role_t(type value) : + SafeEnum(value) { } + + /** + * Explicit constructor from a raw value. + * @param raw_value The role. + */ + explicit connection_role_t(uint8_t raw_value) : + SafeEnum(raw_value) { } +}; + } // namespace ble /** diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 4979434034..1959499e43 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -531,21 +531,10 @@ struct received_advertising_type_t : SafeEnum(value) { } }; - /** - * Model connection role. Used in GapConnectionCompleteEvent. + * @see ble::connection_role_t */ -struct connection_role_t : SafeEnum { - enum type { - MASTER, - SLAVE - }; - - connection_role_t(type value) : SafeEnum(value) { } - - explicit connection_role_t(uint8_t raw_value) : - SafeEnum(raw_value) { } -}; +typedef ble::connection_role_t connection_role_t; /** * Properties of an advertising event. From 6f21326b6a7bf7273851e5435d5e3a242534d6df Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 14:18:55 +0000 Subject: [PATCH 165/361] BLE: Move Gap event types in dedicated file. --- features/FEATURE_BLE/ble/Gap.h | 487 +---------------- features/FEATURE_BLE/ble/gap/Events.h | 509 ++++++++++++++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 18 +- 3 files changed, 519 insertions(+), 495 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/Events.h diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8576b7c880..46cc61716a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -25,6 +25,7 @@ #include "ble/gap/ConnectionParameters.h" #include "ble/gap/ScanParameters.h" #include "ble/gap/AdvertisingParameters.h" +#include "ble/gap/Events.h" // leagacy gap headers #include "ble/GapAdvertisingData.h" @@ -1162,128 +1163,6 @@ public: * Definition of the general handler of Gap related events. */ struct EventHandler { - - /** Event generated when an advertising packet is seen during passive scanning - * or a scan response is received during active scanning. - */ - struct AdvertisingReportEvent { - /** Create a advertising report event. - * - * @param type Type of advertising used. - * @param peerAddressType Peer address type of advertiser. - * @param peerAddress Peer address of advertiser. - * @param primaryPhy PHY used on the primary channels. - * @param secondaryPhy PHY used on secondary channels. - * @param SID Set identification number. - * @param txPower Transmission power reported by the packet. - * @param rssi Measured signal strength. - * @param periodicInterval Interval of periodic advertising. - * @param directAddressType Directed advertising target address type. - * @param directAddress Directed advertising target address. - * @param advertisingData Advertising payload. - */ - AdvertisingReportEvent( - const AdvertisingEventType_t &type, - const PeerAddressType_t &peerAddressType, - const ble::address_t &peerAddress, - const Phy_t &primaryPhy, - const Phy_t &secondaryPhy, - ble::advertising_sid_t SID, - ble::advertising_power_t txPower, - ble::rssi_t rssi, - UnitPeriodicInterval_t periodicInterval, - const PeerAddressType_t &directAddressType, - const ble::address_t &directAddress, - const mbed::Span &advertisingData - ) : - type(type), - peerAddressType(peerAddressType), - peerAddress(peerAddress), - primaryPhy(primaryPhy), - secondaryPhy(secondaryPhy), - SID(SID), - txPower(txPower), - rssi(rssi), - periodicInterval(periodicInterval), - directAddressType(directAddressType), - directAddress(directAddress), - advertisingData(advertisingData) { } - - /** Get event type. */ - const AdvertisingEventType_t &getType() const { - return type; - } - - /** Get peer address type. */ - const PeerAddressType_t &getPeerAddressType() const { - return peerAddressType; - } - - /** Get peer address. */ - const ble::address_t &getPeerAddress() const { - return peerAddress; - } - - /** Get primary PHY. */ - const Phy_t &getPrimaryPhy() const { - return primaryPhy; - } - - /** Get secondary PHY. */ - const Phy_t &getSecondaryPhy() const { - return secondaryPhy; - } - - /** Get advertising set identifier. */ - ble::advertising_sid_t getSID() const { - return SID; - } - - /** Get TX power. */ - ble::advertising_power_t getTxPower() const { - return txPower; - } - - /** Get received signal strength. */ - ble::rssi_t getRssi() const { - return rssi; - } - - /** Get interval. */ - UnitPeriodicInterval_t getPeriodicInterval() const { - return periodicInterval; - } - - /** Get target address type in directed advertising. */ - const PeerAddressType_t &getDirectAddressType() const { - return directAddressType; - } - - /** Get target address in directed advertising. */ - const ble::address_t &getDirectAddress() const { - return directAddress; - } - - /** Get payload. */ - const mbed::Span &getAdvertisingData() const { - return advertisingData; - } - - private: - AdvertisingEventType_t type; - PeerAddressType_t peerAddressType; - ble::address_t const &peerAddress; - Phy_t primaryPhy; - Phy_t secondaryPhy; - ble::advertising_sid_t SID; - ble::advertising_power_t txPower; - ble::rssi_t rssi; - UnitPeriodicInterval_t periodicInterval; - PeerAddressType_t directAddressType; - const ble::address_t &directAddress; - mbed::Span advertisingData; - }; - /** Called when scanning reads an advertising packet during passive scan or receives * a scan response during an active scan. * @@ -1295,117 +1174,6 @@ public: (void) event; } - /** Event generated when a connection initiation end (successfully or not). - */ - struct ConnectionCompleteEvent { - /** Create a connection complete event. - * - * @param success BLE_ERROR_NONE if connection succeeded. - * @param connectionHandle Connection handle if successful. - * @param ownRole Role of the local device. - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param localResolvablePrivateAddress Local address type if privacy enabled. - * @param peerResolvablePrivateAddress Peer address type if privacy enabled. - * @param connectionInterval Connection interval. - * @param connectionLatency Connection latency in events. - * @param supervisionTimeout Supervision timeout. - * @param masterClockAccuracy Peer clock accuracy in parts per million. - */ - ConnectionCompleteEvent( - ble_error_t status, - Handle_t connectionHandle, - Role_t ownRole, - const PeerAddressType_t &peerAddressType, - const ble::address_t &peerAddress, - const ble::address_t &localResolvablePrivateAddress, - const ble::address_t &peerResolvablePrivateAddress, - UnitConnInterval_t connectionInterval, - UnitSlaveLatency_t connectionLatency, - UnitSupervisionTimeout_t supervisionTimeout, - uint16_t masterClockAccuracy - ) : - status(status), - connectionHandle(connectionHandle), - ownRole(ownRole), - peerAddressType(peerAddressType), - peerAddress(peerAddress), - localResolvablePrivateAddress(localResolvablePrivateAddress), - peerResolvablePrivateAddress(peerResolvablePrivateAddress), - connectionInterval(connectionInterval), - connectionLatency(connectionLatency), - supervisionTimeout(supervisionTimeout), - masterClockAccuracy(masterClockAccuracy) { } - - /** Get connection complete event status. */ - ble_error_t getStatus() const { - return status; - } - - /** Get connection handle (valid only when successful). */ - Handle_t getConnectionHandle() const { - return connectionHandle; - } - - /** Get own role. */ - Role_t getOwnRole() const { - return ownRole; - } - - /** Get peer address type. */ - const PeerAddressType_t &getPeerAddressType() const { - return peerAddressType; - } - - /** Get peer address. */ - const ble::address_t &getPeerAddress() const { - return peerAddress; - } - - /** Get get local resolvable random address if privacy is used. */ - const ble::address_t &getLocalResolvablePrivateAddress() const { - return localResolvablePrivateAddress; - } - - /** Get peer resolvable private address if privacy is used. */ - const ble::address_t &getPeerResolvablePrivateAddress() const { - return peerResolvablePrivateAddress; - } - - /** Get connection interval. */ - UnitConnInterval_t getConnectionInterval() const { - return connectionInterval; - } - - /** Get connection latency. */ - UnitSlaveLatency_t getConnectionLatency() const { - return connectionLatency; - } - - /** Get supervision timeout. */ - UnitSupervisionTimeout_t getSupervisionTimeout() const { - return supervisionTimeout; - } - - /** Get clock accuracy in parts per million. */ - uint16_t getMasterClockAccuracy() const { - return masterClockAccuracy; - } - - private: - ble_error_t status; - Handle_t connectionHandle; - Role_t ownRole; - PeerAddressType_t peerAddressType; - const ble::address_t &peerAddress; - const ble::address_t &localResolvablePrivateAddress; - const ble::address_t &peerResolvablePrivateAddress; - UnitConnInterval_t connectionInterval; - UnitSlaveLatency_t connectionLatency; - UnitSupervisionTimeout_t supervisionTimeout; - uint16_t masterClockAccuracy; - }; - /** Called when connection attempt ends. * * @param event Connection event @see ConnectionCompleteEvent_t for details. @@ -1416,90 +1184,6 @@ public: (void)event; } - /** Event generated when we first receive a periodic advertisement. - */ - struct PeriodicAdvertisingSyncEstablishedEvent { - /** Create advertising sync event. - * - * @param success BLE_ERROR_NONE if synchronisation was achieved. - * @param syncHandle Advertising sync handle. - * @param sid Advertising set identifier. - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param peerPhy PHY used for advertisements. - * @param advertisingInterval Periodic advertising interval. - * @param masterClockAccuracy Peer clock accuracy in parts per million. - */ - PeriodicAdvertisingSyncEstablishedEvent( - ble_error_t status, - ble::periodic_sync_handle_t syncHandle, - ble::advertising_sid_t sid, - const PeerAddressType_t &peerAddressType, - const ble::address_t &peerAddress, - const Phy_t &peerPhy, - uint16_t advertisingInterval, - const ble::clock_accuracy_t &peerClockAccuracy - ) : - status(status), - syncHandle(syncHandle), - sid(sid), - peerAddressType(peerAddressType), - peerAddress(peerAddress), - peerPhy(peerPhy), - advertisingInterval(advertisingInterval), - peerClockAccuracy(peerClockAccuracy) { } - - /** Get sync establishment status. */ - ble_error_t getStatus() const { - return status; - } - - /** Get periodic advertising sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { - return syncHandle; - } - - /** Get advertising set identifier. */ - ble::advertising_sid_t getSid() const { - return sid; - } - - /** Get peer address type. */ - const PeerAddressType_t &getPeerAddressType() const { - return peerAddressType; - } - - /** Get peer address. */ - const ble::address_t &getPeerAddress() const { - return peerAddress; - } - - /** Get PHY used. */ - const Phy_t &getPeerPhy() const { - return peerPhy; - } - - /** Get interval. */ - uint16_t getAdvertisingInterval() const { - return advertisingInterval; - } - - /** Get clock accuracy in parts per million. */ - const ble::clock_accuracy_t &getPeerClockAccuracy() const { - return peerClockAccuracy; - } - - private: - ble_error_t status; - ble::periodic_sync_handle_t syncHandle; - ble::advertising_sid_t sid; - PeerAddressType_t peerAddressType; - const ble::address_t& peerAddress; - Phy_t peerPhy; - uint16_t advertisingInterval; - ble::clock_accuracy_t peerClockAccuracy; - }; - /** Called when first advertising packet in periodic advertising is received. * * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. @@ -1510,63 +1194,6 @@ public: (void) event; } - /** Event generated when periodic advertising packet is received. - */ - struct PeriodicAdvertisingReportEvent { - /** Create periodic advertising report event. - * - * @param syncHandle Periodic advertising sync handle - * @param txPower TX power. - * @param rssi Received signal strength. - * @param dataStatus Status to indicate the completeness of the payload. - * @param payload Periodic advertisement payload. - */ - PeriodicAdvertisingReportEvent( - ble::periodic_sync_handle_t syncHandle, - ble::advertising_power_t txPower, - ble::rssi_t rssi, - ble::advertising_data_status_t dataStatus, - const mbed::Span &payload - ) : - syncHandle(syncHandle), - txPower(txPower), - rssi(rssi), - dataStatus(dataStatus), - payload(payload) { } - - /** Get periodic advertising sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { - return syncHandle; - } - - /** Get TX power as reported by the advertising packet. */ - ble::advertising_power_t getTxPower() const { - return txPower; - } - - /** Get received signal strength. */ - ble::rssi_t getRssi() const { - return rssi; - } - - /** Get data completeness status. */ - const ble::advertising_data_status_t &getDataStatus() const { - return dataStatus; - } - - /** Get payload. */ - const mbed::Span &getPayload() const { - return payload; - } - - private: - ble::periodic_sync_handle_t syncHandle; - ble::advertising_power_t txPower; - ble::rssi_t rssi; - ble::advertising_data_status_t dataStatus; - mbed::Span payload; - }; - /** Called when a periodic advertising packet is received. * * @param event Periodic advertisement event. @@ -1577,89 +1204,16 @@ public: (void) event; } - /** Event generated when periodic advertising sync is lost. - */ - struct PeriodicAdvertisingSyncLoss { - /** Create periodic advertising sync loss event. - * - * @param syncHandle Periodic advertising sync handle. - */ - PeriodicAdvertisingSyncLoss( - ble::periodic_sync_handle_t syncHandle - ) : - syncHandle(syncHandle) { } - - /** Get periodic sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { - return syncHandle; - } - - private: - ble::periodic_sync_handle_t syncHandle; - }; - virtual void onPeriodicAdvertisingSyncLoss( const PeriodicAdvertisingSyncLoss &event ) { (void) event; } - /** Event generated when scan times out. - */ - struct ScanTimeoutEvent { }; - /** Called when scan times out. */ virtual void onScanTimeout(const ScanTimeoutEvent &) { } - /** Event produced when advertising ends. - */ - struct AdvertisingEndEvent_t { - /** Create advertising end event. - * - * @param advHandle Advertising set handle. - * @param connection Connection handle. - * @param completed_events Number of events created during before advertising end. - * @param connected True if connection has been established. - */ - AdvertisingEndEvent_t( - AdvHandle_t advHandle, - Handle_t connection, - uint8_t completed_events, - bool connected - ) : - advHandle(advHandle), - connection(connection), - completed_events(completed_events), - connected(connected) { } - - /** Get advertising handle. */ - AdvHandle_t getAdvHandle() const { - return advHandle; - } - - /** Get connection handle (valid only if connected successfully). */ - Handle_t getConnection() const { - return connection; - } - - /** Get how many events advertising created. */ - uint8_t getCompleted_events() const { - return completed_events; - } - - /** Has the advertising ended with a connection. */ - bool isConnected() const { - return connected; - } - - private: - AdvHandle_t advHandle; - Handle_t connection; - uint8_t completed_events; - bool connected; - }; - /** Called when advertising ends. * * @param event Advertising end event: @see AdvertisingEndEvent_t for details. @@ -1670,45 +1224,6 @@ public: (void) event; } - /** Event produced when a peer requests a scan response from the advertiser. - */ - struct ScanRequestEvent_t { - /** Create scan request event. - * - * @param advHandle Advertising handle. - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - */ - ScanRequestEvent_t( - AdvHandle_t advHandle, - const PeerAddressType_t &peerAddressType, - const ble::address_t &peerAddress - ) : - advHandle(advHandle), - peerAddressType(peerAddressType), - peerAddress(peerAddress) { } - - /** Get advertising handle. */ - AdvHandle_t getAdvHandle() const { - return advHandle; - } - - /** Get peer address type. */ - const PeerAddressType_t &getPeerAddressType() const { - return peerAddressType; - } - - /** Get peer address. */ - const ble::address_t &getPeerAddress() const { - return peerAddress; - } - - private: - AdvHandle_t advHandle; - PeerAddressType_t peerAddressType; - const ble::address_t &peerAddress; - }; - /** Called when a scanning device request a scan response. * * @param event Scan request event: @see ScanRequestEvent_t for details. diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h new file mode 100644 index 0000000000..9a7de3e445 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -0,0 +1,509 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018-2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef BLE_GAP_EVENTS_H +#define BLE_GAP_EVENTS_H + +#include "ble/blecommon.h" +#include "ble/BLETypes.h" +#include "platform/Span.h" + +/** Event generated when an advertising packet is seen during passive scanning + * or a scan response is received during active scanning. + */ +struct AdvertisingReportEvent { + /** Create a advertising report event. + * + * @param type Type of advertising used. + * @param peerAddressType Peer address type of advertiser. + * @param peerAddress Peer address of advertiser. + * @param primaryPhy PHY used on the primary channels. + * @param secondaryPhy PHY used on secondary channels. + * @param SID Set identification number. + * @param txPower Transmission power reported by the packet. + * @param rssi Measured signal strength. + * @param periodicInterval Interval of periodic advertising. + * @param directAddressType Directed advertising target address type. + * @param directAddress Directed advertising target address. + * @param advertisingData Advertising payload. + */ + AdvertisingReportEvent( + const ble::advertising_event_t &type, + const ble::peer_address_type_t &peerAddressType, + const ble::address_t &peerAddress, + const ble::phy_t &primaryPhy, + const ble::phy_t &secondaryPhy, + ble::advertising_sid_t SID, + ble::advertising_power_t txPower, + ble::rssi_t rssi, + ble::unit_periodic_interval_t periodicInterval, + const ble::peer_address_type_t &directAddressType, + const ble::address_t &directAddress, + const mbed::Span &advertisingData + ) : + type(type), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + primaryPhy(primaryPhy), + secondaryPhy(secondaryPhy), + SID(SID), + txPower(txPower), + rssi(rssi), + periodicInterval(periodicInterval), + directAddressType(directAddressType), + directAddress(directAddress), + advertisingData(advertisingData) { } + + /** Get event type. */ + const ble::advertising_event_t &getType() const { + return type; + } + + /** Get peer address type. */ + const ble::peer_address_type_t &getPeerAddressType() const { + return peerAddressType; + } + + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { + return peerAddress; + } + + /** Get primary PHY. */ + const ble::phy_t &getPrimaryPhy() const { + return primaryPhy; + } + + /** Get secondary PHY. */ + const ble::phy_t &getSecondaryPhy() const { + return secondaryPhy; + } + + /** Get advertising set identifier. */ + ble::advertising_sid_t getSID() const { + return SID; + } + + /** Get TX power. */ + ble::advertising_power_t getTxPower() const { + return txPower; + } + + /** Get received signal strength. */ + ble::rssi_t getRssi() const { + return rssi; + } + + /** Get interval. */ + ble::unit_periodic_interval_t getPeriodicInterval() const { + return periodicInterval; + } + + /** Get target address type in directed advertising. */ + const ble::peer_address_type_t &getDirectAddressType() const { + return directAddressType; + } + + /** Get target address in directed advertising. */ + const ble::address_t &getDirectAddress() const { + return directAddress; + } + + /** Get payload. */ + const mbed::Span &getAdvertisingData() const { + return advertisingData; + } + +private: + ble::advertising_event_t type; + ble::peer_address_type_t peerAddressType; + ble::address_t const &peerAddress; + ble::phy_t primaryPhy; + ble::phy_t secondaryPhy; + ble::advertising_sid_t SID; + ble::advertising_power_t txPower; + ble::rssi_t rssi; + ble::unit_periodic_interval_t periodicInterval; + ble::peer_address_type_t directAddressType; + const ble::address_t &directAddress; + mbed::Span advertisingData; +}; + +/** Event generated when a connection initiation end (successfully or not). + */ +struct ConnectionCompleteEvent { + /** Create a connection complete event. + * + * @param success BLE_ERROR_NONE if connection succeeded. + * @param connectionHandle Connection handle if successful. + * @param ownRole Role of the local device. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param localResolvablePrivateAddress Local address type if privacy enabled. + * @param peerResolvablePrivateAddress Peer address type if privacy enabled. + * @param connectionInterval Connection interval. + * @param connectionLatency Connection latency in events. + * @param supervisionTimeout Supervision timeout. + * @param masterClockAccuracy Peer clock accuracy in parts per million. + */ + ConnectionCompleteEvent( + ble_error_t status, + ble::connection_handle_t connectionHandle, + ble::connection_role_t ownRole, + const ble::peer_address_type_t &peerAddressType, + const ble::address_t &peerAddress, + const ble::address_t &localResolvablePrivateAddress, + const ble::address_t &peerResolvablePrivateAddress, + ble::unit_conn_interval_t connectionInterval, + ble::unit_slave_latency_t connectionLatency, + ble::unit_supervision_timeout_t supervisionTimeout, + uint16_t masterClockAccuracy + ) : + status(status), + connectionHandle(connectionHandle), + ownRole(ownRole), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + localResolvablePrivateAddress(localResolvablePrivateAddress), + peerResolvablePrivateAddress(peerResolvablePrivateAddress), + connectionInterval(connectionInterval), + connectionLatency(connectionLatency), + supervisionTimeout(supervisionTimeout), + masterClockAccuracy(masterClockAccuracy) { } + + /** Get connection complete event status. */ + ble_error_t getStatus() const { + return status; + } + + /** Get connection handle (valid only when successful). */ + ble::connection_handle_t getConnectionHandle() const { + return connectionHandle; + } + + /** Get own role. */ + ble::connection_role_t getOwnRole() const { + return ownRole; + } + + /** Get peer address type. */ + const ble::peer_address_type_t &getPeerAddressType() const { + return peerAddressType; + } + + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { + return peerAddress; + } + + /** Get get local resolvable random address if privacy is used. */ + const ble::address_t &getLocalResolvablePrivateAddress() const { + return localResolvablePrivateAddress; + } + + /** Get peer resolvable private address if privacy is used. */ + const ble::address_t &getPeerResolvablePrivateAddress() const { + return peerResolvablePrivateAddress; + } + + /** Get connection interval. */ + ble::unit_conn_interval_t getConnectionInterval() const { + return connectionInterval; + } + + /** Get connection latency. */ + ble::unit_slave_latency_t getConnectionLatency() const { + return connectionLatency; + } + + /** Get supervision timeout. */ + ble::unit_supervision_timeout_t getSupervisionTimeout() const { + return supervisionTimeout; + } + + /** Get clock accuracy in parts per million. */ + uint16_t getMasterClockAccuracy() const { + return masterClockAccuracy; + } + +private: + ble_error_t status; + ble::connection_handle_t connectionHandle; + ble::connection_role_t ownRole; + ble::peer_address_type_t peerAddressType; + const ble::address_t &peerAddress; + const ble::address_t &localResolvablePrivateAddress; + const ble::address_t &peerResolvablePrivateAddress; + ble::unit_conn_interval_t connectionInterval; + ble::unit_slave_latency_t connectionLatency; + ble::unit_supervision_timeout_t supervisionTimeout; + uint16_t masterClockAccuracy; +}; + +/** Event generated when we first receive a periodic advertisement. + */ +struct PeriodicAdvertisingSyncEstablishedEvent { + /** Create advertising sync event. + * + * @param success BLE_ERROR_NONE if synchronisation was achieved. + * @param syncHandle Advertising sync handle. + * @param sid Advertising set identifier. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param peerPhy PHY used for advertisements. + * @param advertisingInterval Periodic advertising interval. + * @param masterClockAccuracy Peer clock accuracy in parts per million. + */ + PeriodicAdvertisingSyncEstablishedEvent( + ble_error_t status, + ble::periodic_sync_handle_t syncHandle, + ble::advertising_sid_t sid, + const ble::peer_address_type_t &peerAddressType, + const ble::address_t &peerAddress, + const ble::phy_t &peerPhy, + uint16_t advertisingInterval, + const ble::clock_accuracy_t &peerClockAccuracy + ) : + status(status), + syncHandle(syncHandle), + sid(sid), + peerAddressType(peerAddressType), + peerAddress(peerAddress), + peerPhy(peerPhy), + advertisingInterval(advertisingInterval), + peerClockAccuracy(peerClockAccuracy) { } + + /** Get sync establishment status. */ + ble_error_t getStatus() const { + return status; + } + + /** Get periodic advertising sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { + return syncHandle; + } + + /** Get advertising set identifier. */ + ble::advertising_sid_t getSid() const { + return sid; + } + + /** Get peer address type. */ + const ble::peer_address_type_t &getPeerAddressType() const { + return peerAddressType; + } + + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { + return peerAddress; + } + + /** Get PHY used. */ + const ble::phy_t &getPeerPhy() const { + return peerPhy; + } + + /** Get interval. */ + uint16_t getAdvertisingInterval() const { + return advertisingInterval; + } + + /** Get clock accuracy in parts per million. */ + const ble::clock_accuracy_t &getPeerClockAccuracy() const { + return peerClockAccuracy; + } + +private: + ble_error_t status; + ble::periodic_sync_handle_t syncHandle; + ble::advertising_sid_t sid; + ble::peer_address_type_t peerAddressType; + const ble::address_t& peerAddress; + ble::phy_t peerPhy; + uint16_t advertisingInterval; + ble::clock_accuracy_t peerClockAccuracy; +}; + +/** Event generated when periodic advertising packet is received. + */ +struct PeriodicAdvertisingReportEvent { + /** Create periodic advertising report event. + * + * @param syncHandle Periodic advertising sync handle + * @param txPower TX power. + * @param rssi Received signal strength. + * @param dataStatus Status to indicate the completeness of the payload. + * @param payload Periodic advertisement payload. + */ + PeriodicAdvertisingReportEvent( + ble::periodic_sync_handle_t syncHandle, + ble::advertising_power_t txPower, + ble::rssi_t rssi, + ble::advertising_data_status_t dataStatus, + const mbed::Span &payload + ) : + syncHandle(syncHandle), + txPower(txPower), + rssi(rssi), + dataStatus(dataStatus), + payload(payload) { } + + /** Get periodic advertising sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { + return syncHandle; + } + + /** Get TX power as reported by the advertising packet. */ + ble::advertising_power_t getTxPower() const { + return txPower; + } + + /** Get received signal strength. */ + ble::rssi_t getRssi() const { + return rssi; + } + + /** Get data completeness status. */ + const ble::advertising_data_status_t &getDataStatus() const { + return dataStatus; + } + + /** Get payload. */ + const mbed::Span &getPayload() const { + return payload; + } + +private: + ble::periodic_sync_handle_t syncHandle; + ble::advertising_power_t txPower; + ble::rssi_t rssi; + ble::advertising_data_status_t dataStatus; + mbed::Span payload; +}; + +/** Event generated when periodic advertising sync is lost. + */ +struct PeriodicAdvertisingSyncLoss { + /** Create periodic advertising sync loss event. + * + * @param syncHandle Periodic advertising sync handle. + */ + PeriodicAdvertisingSyncLoss( + ble::periodic_sync_handle_t syncHandle + ) : + syncHandle(syncHandle) { } + + /** Get periodic sync handle. */ + ble::periodic_sync_handle_t getSyncHandle() const { + return syncHandle; + } + +private: + ble::periodic_sync_handle_t syncHandle; +}; + +/** Event generated when scan times out. + */ +struct ScanTimeoutEvent { }; + +/** Event produced when advertising ends. + */ +struct AdvertisingEndEvent_t { + /** Create advertising end event. + * + * @param advHandle Advertising set handle. + * @param connection Connection handle. + * @param completed_events Number of events created during before advertising end. + * @param connected True if connection has been established. + */ + AdvertisingEndEvent_t( + ble::advertising_handle_t advHandle, + ble::connection_handle_t connection, + uint8_t completed_events, + bool connected + ) : + advHandle(advHandle), + connection(connection), + completed_events(completed_events), + connected(connected) { } + + /** Get advertising handle. */ + ble::advertising_handle_t getAdvHandle() const { + return advHandle; + } + + /** Get connection handle (valid only if connected successfully). */ + ble::connection_handle_t getConnection() const { + return connection; + } + + /** Get how many events advertising created. */ + uint8_t getCompleted_events() const { + return completed_events; + } + + /** Has the advertising ended with a connection. */ + bool isConnected() const { + return connected; + } + +private: + ble::advertising_handle_t advHandle; + ble::connection_handle_t connection; + uint8_t completed_events; + bool connected; +}; + +/** Event produced when a peer requests a scan response from the advertiser. + */ +struct ScanRequestEvent_t { + /** Create scan request event. + * + * @param advHandle Advertising handle. + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + */ + ScanRequestEvent_t( + ble::advertising_handle_t advHandle, + const ble::peer_address_type_t &peerAddressType, + const ble::address_t &peerAddress + ) : + advHandle(advHandle), + peerAddressType(peerAddressType), + peerAddress(peerAddress) { } + + /** Get advertising handle. */ + ble::advertising_handle_t getAdvHandle() const { + return advHandle; + } + + /** Get peer address type. */ + const ble::peer_address_type_t &getPeerAddressType() const { + return peerAddressType; + } + + /** Get peer address. */ + const ble::address_t &getPeerAddress() const { + return peerAddress; + } + +private: + ble::advertising_handle_t advHandle; + ble::peer_address_type_t peerAddressType; + const ble::address_t &peerAddress; +}; + +#endif //BLE_GAP_EVENTS_H diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index e313782923..2cf940633e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1227,7 +1227,7 @@ void GenericGap::on_scan_timeout() return; } - _eventHandler->onScanTimeout(::Gap::EventHandler::ScanTimeoutEvent()); + _eventHandler->onScanTimeout(ScanTimeoutEvent()); } void GenericGap::process_scan_timeout() @@ -2190,10 +2190,10 @@ void GenericGap::on_enhanced_connection_complete( } _eventHandler->onConnectionComplete( - Gap::EventHandler::ConnectionCompleteEvent( + ConnectionCompleteEvent( (status == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, (ble::connection_handle_t)connection_handle, - (Gap::Role_t)own_role.value(), + own_role, (ble::peer_address_type_t::type)peer_address_type.value(), peer_address, local_resolvable_private_address, @@ -2227,7 +2227,7 @@ void GenericGap::on_extended_advertising_report( } _eventHandler->onAdvertisingReport( - ::Gap::EventHandler::AdvertisingReportEvent( + AdvertisingReportEvent( event_type, (PeerAddressType_t::type)(address_type ? address_type->value() : PeerAddressType_t::ANONYMOUS), (BLEProtocol::AddressBytes_t&)address, @@ -2260,7 +2260,7 @@ void GenericGap::on_periodic_advertising_sync_established( } _eventHandler->onPeriodicAdvertisingSyncEstablished( - ::Gap::EventHandler::PeriodicAdvertisingSyncEstablishedEvent( + PeriodicAdvertisingSyncEstablishedEvent( (error == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, sync_handle, advertising_sid, @@ -2288,7 +2288,7 @@ void GenericGap::on_periodic_advertising_report( } _eventHandler->onPeriodicAdvertisingReportEvent( - ::Gap::EventHandler::PeriodicAdvertisingReportEvent( + PeriodicAdvertisingReportEvent( sync_handle, tx_power, rssi, @@ -2305,7 +2305,7 @@ void GenericGap::on_periodic_advertising_sync_loss(pal::sync_handle_t sync_handl } _eventHandler->onPeriodicAdvertisingSyncLoss( - ::Gap::EventHandler::PeriodicAdvertisingSyncLoss(sync_handle) + PeriodicAdvertisingSyncLoss(sync_handle) ); } @@ -2323,7 +2323,7 @@ void GenericGap::on_advertising_set_terminated( } _eventHandler->onAdvertisingEnd( - ::Gap::EventHandler::AdvertisingEndEvent_t( + AdvertisingEndEvent_t( advertising_handle, connection_handle, number_of_completed_extended_advertising_events, @@ -2343,7 +2343,7 @@ void GenericGap::on_scan_request_received( } _eventHandler->onScanRequest( - ::Gap::EventHandler::ScanRequestEvent_t( + ScanRequestEvent_t( advertising_handle, (ble::peer_address_type_t::type) scanner_address_type.value(), address From 68703495f6719dbc7cc276844dd6aa50da02eec0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 15:41:32 +0000 Subject: [PATCH 166/361] BLE: Extract types from GapAdvertisingConstant and add them into ble namespace. --- .../ble/gap/AdvertisingDataBuilder.h | 125 ++++++++++++------ 1 file changed, 81 insertions(+), 44 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 8272145faa..d81166a41e 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -21,9 +21,11 @@ #include #include -#include "blecommon.h" #include "platform/Span.h" -#include "NonCopyable.h" +#include "platform/NonCopyable.h" + +#include "ble/blecommon.h" +#include "ble/SafeEnum.h" /** * @addtogroup ble @@ -32,19 +34,22 @@ * @{ */ -struct GapAdvertisingConstant { - /*! - * List of standard Advertising Data types. - * - * These AD types are used to describe the capabilities of the peripheral - * and are inserted inside the advertising or scan response payloads. - * - * @par Source - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. - * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. - */ - enum DataType { +namespace ble { + +/*! + * List of standard Advertising Data types. + * + * These AD types are used to describe the capabilities of the peripheral + * and are inserted inside the advertising or scan response payloads. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. + * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. + */ +struct adv_data_type_t :SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { /** * Flags, refer to AdvertisingData::Flags_t. */ @@ -132,16 +137,26 @@ struct GapAdvertisingConstant { }; /** - * Enumeration of allowed flags for DataType_t::FLAGS. - * - * @note DataType_t::FLAGS may contain several flags that the bitwise - * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. - * - * @par Source - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. + * Construct a new instance of adv_data_type_t. */ - enum Flags { + adv_data_type_t(type value) : + SafeEnum(value) { } +}; + + +/** + * Enumeration of allowed flags for DataType_t::FLAGS. + * + * @note DataType_t::FLAGS may contain several flags that the bitwise + * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. + */ +struct adv_data_flags_t :SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { /** * Peripheral device is discoverable for a limited period of time. */ @@ -167,21 +182,30 @@ struct GapAdvertisingConstant { * Not relevant - dual mode only. */ SIMULTANEOUS_LE_BREDR_H = 0x10 - }; /** - * Enumeration of values for the DataType_t::APPEARANCE. - * - * These values describe the physical shape or appearance of the device. - * - * @par Source - * - * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. - * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. + * Construct a new instance of adv_data_flags_t. */ - enum Appearance { + adv_data_flags_t(type value) : + SafeEnum(value) { } +}; + + +/** + * Enumeration of values for the DataType_t::APPEARANCE. + * + * These values describe the physical shape or appearance of the device. + * + * @par Source + * + * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. + * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. + */ +struct adv_data_appearance_t :SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { /** * Unknown or unspecified appearance type. */ @@ -426,8 +450,13 @@ struct GapAdvertisingConstant { * Outdoor Location and Navigation Pod. */ OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 - }; + + /** + * Construct a new instance of adv_data_appearance_t. + */ + adv_data_appearance_t(type value) : + SafeEnum(value) { } }; @@ -484,9 +513,12 @@ public: * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the * supplied value is appended to the values present in the payload. */ - ble_error_t addData(GapAdvertisingConstant::DataType advDataType, const uint8_t *payload, uint8_t len) + ble_error_t addData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { - return appendField(advDataType, payload, len); + return appendField(advDataType, fieldData); } /** @@ -513,24 +545,27 @@ private: * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the * advertising buffer to overflow. */ - ble_error_t appendField(GapAdvertisingConstant::DataType advDataType, const uint8_t *payload, uint8_t len) + ble_error_t appendField( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { /* Make sure we don't exceed the buffer size */ - if (_payloadLen + len + 2 > _buffer.size()) { + if (_payloadLen + fieldData.size() + 2 > _buffer.size()) { return BLE_ERROR_BUFFER_OVERFLOW; } /* Field length. */ - memset(_buffer.data() + _payloadLen, len + 1, 1); + memset(_buffer.data() + _payloadLen, fieldData.size() + 1, 1); _payloadLen++; /* Field ID. */ - memset(_buffer.data() + _payloadLen, (uint8_t)advDataType, 1); + memset(_buffer.data() + _payloadLen, advDataType.value(), 1); _payloadLen++; /* Payload. */ - memcpy(_buffer.data() + _payloadLen, payload, len); - _payloadLen += len; + memcpy(_buffer.data() + _payloadLen, fieldData.data(), fieldData.size()); + _payloadLen += fieldData.size(); return BLE_ERROR_NONE; } @@ -543,6 +578,8 @@ protected: uint8_t _payloadLen; }; +} // namespace ble + /** * @} * @} From 20d5de70bdefb0b55c25057a46dd453e09015cf5 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 15:54:13 +0000 Subject: [PATCH 167/361] BLE: Move ble::Duration in its own file. --- features/FEATURE_BLE/ble/BLETypes.h | 185 +----------------- features/FEATURE_BLE/ble/common/Duration.h | 210 +++++++++++++++++++++ 2 files changed, 211 insertions(+), 184 deletions(-) create mode 100644 features/FEATURE_BLE/ble/common/Duration.h diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 48227f914a..8cc52bf4ad 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -20,9 +20,9 @@ #include #include #include -#include "platform/mbed_assert.h" #include "ble/SafeEnum.h" #include "ble/ArrayView.h" +#include "ble/common/Duration.h" /** * @addtogroup ble @@ -43,189 +43,6 @@ void clamp(T& value, const R& min, const R& max) { } } -template -struct Range { - enum { - MIN = Min, - MAX = Max - }; -}; - -template -struct DefaultRange; - -template<> -struct DefaultRange { - typedef Range<0, 0xFF> type; -}; - -template<> -struct DefaultRange { - typedef Range<0, 0xFFFF> type; -}; - -template<> -struct DefaultRange { - typedef Range<0, 0xFFFFFFFF> type; -}; - - -template::type > -struct Duration { - Duration() : duration() { } - - explicit Duration(Rep v) : duration(clamp(v)) { } - - template - Duration(Duration other) : - duration(clamp(other.value() * (OtherTB / TB))) - { - MBED_STATIC_ASSERT(OtherTB >= TB && (OtherTB % TB) == 0, "Incompatible units"); - } - - Rep value() { - return duration; - } - - enum { - TIME_BASE = TB, - MIN = Range::MIN, - MAX = Range::MAX - }; - - static Duration min() - { - return Duration(MIN); - } - - static Duration max() - { - return Duration(MAX); - } - - const Rep* storage() const - { - return &duration; - } - -private: - static Rep clamp(Rep in) { - if (in < MIN) { - return MIN; - } else if (in > MAX) { - return MAX; - } else { - return in; - } - } - - Rep duration; -}; - -typedef Duration microsecond_t; -typedef Duration millisecond_t; -typedef Duration second_t; - -template -DurationOut durationCast(Duration duration) { - return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); -} - -// ADDITION OPERATOR -template -microsecond_t operator+(Duration lhs, Duration rhs) { - return microsecond_t((lhs.value() * lhs.TIME_BASE) + (rhs.value() * rhs.TIME_BASE)); -} - -template -Duration operator+(Duration lhs, Duration rhs) { - return Duration(lhs.value() + rhs.value()); -} - -// MULTIPLICATION OPERATOR - -template -Duration operator*(Duration lhs, uint32_t rhs) { - return Duration(lhs.value() * rhs); -} - -template -Duration operator*(uint32_t lhs, Duration rhs) { - return Duration(lhs * rhs.value()); -} - -// LESS THAN - -template -bool operator<(Duration lhs, Duration rhs) { - return lhs.value() * lhs.TIME_BASE < rhs.value() * rhs.TIME_BASE; -} - -template -bool operator<(Duration lhs, Duration rhs) { - return lhs.value() < rhs.value(); -} - -// LESS OR EQUAL TO - -template -bool operator<=(Duration lhs, Duration rhs) { - return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; -} - -template -bool operator<=(Duration lhs, Duration rhs) { - return lhs.value() <= rhs.value(); -} - -// EQUAL - -template -bool operator==(Duration lhs, Duration rhs) { - return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; -} - -template -bool operator==(Duration lhs, Duration rhs) { - return lhs.value() == rhs.value(); -} - -// NOT EQUAL - -template -bool operator!=(Duration lhs, Duration rhs) { - return !(lhs == rhs); -} - -template -bool operator!=(Duration lhs, Duration rhs) { - return !(lhs == rhs); -} - -// GREATER OR EQUAL - -template -bool operator>=(Duration lhs, Duration rhs) { - return rhs <= lhs; -} - -template -bool operator>=(Duration lhs, Duration rhs) { - return rhs <= lhs; -} - -// GREATER THAN - -template -bool operator>(Duration lhs, Duration rhs) { - return rhs < lhs; -} - -template -bool operator>(Duration lhs, Duration rhs) { - return rhs < lhs; -} - template struct Bounded { Bounded(T v) : _value(v) { diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h new file mode 100644 index 0000000000..9b18c71932 --- /dev/null +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -0,0 +1,210 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_COMMON_DURATION_H_ +#define BLE_COMMON_DURATION_H_ + +#include +#include "platform/mbed_assert.h" + +namespace ble { + +template +struct Range { + enum { + MIN = Min, + MAX = Max + }; +}; + +template +struct DefaultRange; + +template<> +struct DefaultRange { + typedef Range<0, 0xFF> type; +}; + +template<> +struct DefaultRange { + typedef Range<0, 0xFFFF> type; +}; + +template<> +struct DefaultRange { + typedef Range<0, 0xFFFFFFFF> type; +}; + + +template::type > +struct Duration { + Duration() : duration() { } + + explicit Duration(Rep v) : duration(clamp(v)) { } + + template + Duration(Duration other) : + duration(clamp(other.value() * (OtherTB / TB))) + { + MBED_STATIC_ASSERT(OtherTB >= TB && (OtherTB % TB) == 0, "Incompatible units"); + } + + Rep value() { + return duration; + } + + enum { + TIME_BASE = TB, + MIN = Range::MIN, + MAX = Range::MAX + }; + + static Duration min() + { + return Duration(MIN); + } + + static Duration max() + { + return Duration(MAX); + } + + const Rep* storage() const + { + return &duration; + } + +private: + static Rep clamp(Rep in) { + if (in < MIN) { + return MIN; + } else if (in > MAX) { + return MAX; + } else { + return in; + } + } + + Rep duration; +}; + +typedef Duration microsecond_t; +typedef Duration millisecond_t; +typedef Duration second_t; + +template +DurationOut durationCast(Duration duration) { + return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); +} + +// ADDITION OPERATOR +template +microsecond_t operator+(Duration lhs, Duration rhs) { + return microsecond_t((lhs.value() * lhs.TIME_BASE) + (rhs.value() * rhs.TIME_BASE)); +} + +template +Duration operator+(Duration lhs, Duration rhs) { + return Duration(lhs.value() + rhs.value()); +} + +// MULTIPLICATION OPERATOR + +template +Duration operator*(Duration lhs, uint32_t rhs) { + return Duration(lhs.value() * rhs); +} + +template +Duration operator*(uint32_t lhs, Duration rhs) { + return Duration(lhs * rhs.value()); +} + +// LESS THAN + +template +bool operator<(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE < rhs.value() * rhs.TIME_BASE; +} + +template +bool operator<(Duration lhs, Duration rhs) { + return lhs.value() < rhs.value(); +} + +// LESS OR EQUAL TO + +template +bool operator<=(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; +} + +template +bool operator<=(Duration lhs, Duration rhs) { + return lhs.value() <= rhs.value(); +} + +// EQUAL + +template +bool operator==(Duration lhs, Duration rhs) { + return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; +} + +template +bool operator==(Duration lhs, Duration rhs) { + return lhs.value() == rhs.value(); +} + +// NOT EQUAL + +template +bool operator!=(Duration lhs, Duration rhs) { + return !(lhs == rhs); +} + +template +bool operator!=(Duration lhs, Duration rhs) { + return !(lhs == rhs); +} + +// GREATER OR EQUAL + +template +bool operator>=(Duration lhs, Duration rhs) { + return rhs <= lhs; +} + +template +bool operator>=(Duration lhs, Duration rhs) { + return rhs <= lhs; +} + +// GREATER THAN + +template +bool operator>(Duration lhs, Duration rhs) { + return rhs < lhs; +} + +template +bool operator>(Duration lhs, Duration rhs) { + return rhs < lhs; +} + +} + +#endif //BLE_COMMON_DURATION_H_ From a1d464f2c00a594e3636667e935ff9558516e68f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 15:54:34 +0000 Subject: [PATCH 168/361] move ble::Bounded in its own file. --- features/FEATURE_BLE/ble/BLETypes.h | 22 +---------- features/FEATURE_BLE/ble/common/Bounded.h | 47 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 21 deletions(-) create mode 100644 features/FEATURE_BLE/ble/common/Bounded.h diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 8cc52bf4ad..bed82a7bdd 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -23,6 +23,7 @@ #include "ble/SafeEnum.h" #include "ble/ArrayView.h" #include "ble/common/Duration.h" +#include "ble/common/Bounded.h" /** * @addtogroup ble @@ -43,27 +44,6 @@ void clamp(T& value, const R& min, const R& max) { } } -template -struct Bounded { - Bounded(T v) : _value(v) { - if (v < Min) { - _value = v; - } else if (v > Max) { - _value = v; - } - } - - T value() const { - return _value; - } - - static const T min = Min; - static const T max = Max; - -private: - T _value; -}; - typedef Duration > unit_adv_interval_t; typedef Duration > unit_adv_duration_t; typedef Duration > unit_scan_duration_t; diff --git a/features/FEATURE_BLE/ble/common/Bounded.h b/features/FEATURE_BLE/ble/common/Bounded.h new file mode 100644 index 0000000000..192c2387eb --- /dev/null +++ b/features/FEATURE_BLE/ble/common/Bounded.h @@ -0,0 +1,47 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_COMMON_BOUNDED_H_ +#define BLE_COMMON_BOUNDED_H_ + +#include + +namespace ble { + +template +struct Bounded { + Bounded(T v) : _value(v) { + if (v < Min) { + _value = v; + } else if (v > Max) { + _value = v; + } + } + + T value() const { + return _value; + } + + static const T min = Min; + static const T max = Max; + +private: + T _value; +}; + +} // namespace ble + +#endif //BLE_COMMON_BOUNDED_H_ From 13241163771941bb8bd507aa498bae6aef351c80 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 16:29:51 +0000 Subject: [PATCH 169/361] BLE: rename duration type and extract them out of Gap. --- features/FEATURE_BLE/ble/BLETypes.h | 28 +++++++-------- features/FEATURE_BLE/ble/Gap.h | 36 +++++-------------- .../ble/gap/ConnectionParameters.h | 16 ++++----- features/FEATURE_BLE/ble/gap/Events.h | 24 ++++++------- features/FEATURE_BLE/ble/gap/ScanParameters.h | 4 +-- features/FEATURE_BLE/ble/generic/GenericGap.h | 18 +++++----- .../FEATURE_BLE/source/generic/GenericGap.cpp | 24 ++++++------- 7 files changed, 66 insertions(+), 84 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index bed82a7bdd..da93755239 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -44,22 +44,22 @@ void clamp(T& value, const R& min, const R& max) { } } -typedef Duration > unit_adv_interval_t; -typedef Duration > unit_adv_duration_t; -typedef Duration > unit_scan_duration_t; -typedef Duration > unit_scan_period_t; -typedef Duration > unit_scan_interval_t; -typedef Duration > unit_scan_window_t; -typedef Duration > unit_conn_interval_t; -typedef Duration > unit_supervision_timeout_t; -typedef Duration > unit_conn_event_length_t; -typedef Duration > unit_sync_timeout_t; -typedef Duration > unit_periodic_interval_t; +typedef Duration > adv_interval_t; +typedef Duration > adv_duration_t; +typedef Duration > scan_duration_t; +typedef Duration > scan_period_t; +typedef Duration > scan_interval_t; +typedef Duration > scan_window_t; +typedef Duration > conn_interval_t; +typedef Duration > supervision_timeout_t; +typedef Duration > conn_event_length_t; +typedef Duration > sync_timeout_t; +typedef Duration > periodic_interval_t; -typedef Duration unit_ms_t; -typedef Duration unit_us_t; +typedef Duration ms_t; +typedef Duration us_t; -typedef Bounded unit_slave_latency_t; +typedef Bounded slave_latency_t; /** * Opaque reference to a connection. diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 46cc61716a..ca48d3d644 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -535,24 +535,6 @@ public: unsigned connected : 1; }; - /* Time units. */ - typedef ble::unit_adv_interval_t UnitAdvInterval_t; /**< 625us */ - typedef ble::unit_adv_duration_t UnitAdvDuration_t; /**< 10ms */ - typedef ble::unit_scan_duration_t UnitScanDuration_t; /**< 10ms */ - typedef ble::unit_scan_period_t UnitScanPeriod_t; /**< 1.28ms */ - typedef ble::unit_scan_interval_t UnitScanInterval_t; /**< 625us */ - typedef ble::unit_scan_window_t UnitScanWindow_t; /**< 625us */ - typedef ble::unit_conn_interval_t UnitConnInterval_t; /**< 1.25ms */ - typedef ble::unit_supervision_timeout_t UnitSupervisionTimeout_t;/**< 10ms */ - typedef ble::unit_conn_event_length_t UnitConnEventLength_t; /**< 625us */ - typedef ble::unit_sync_timeout_t UnitSyncTimeout_t; /**< 10ms */ - typedef ble::unit_periodic_interval_t UnitPeriodicInterval_t; /**< 1.25ms */ - typedef ble::unit_ms_t UnitMs_t; /**< Milliseconds */ - typedef ble::unit_us_t UnitUs_t; /**< Microseconds */ - - /** Measured in number of events. */ - typedef ble::unit_slave_latency_t UnitSlaveLatency_t; - /** * Opaque value type representing a connection handle. * @@ -1840,7 +1822,7 @@ public: */ virtual ble_error_t startAdvertising( AdvHandle_t handle, - UnitAdvDuration_t maxDuration = UnitAdvDuration_t(0), + ble::adv_duration_t maxDuration = ble::adv_duration_t(0), uint8_t maxEvents = 0 ) { @@ -1881,8 +1863,8 @@ public: */ virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMin, - UnitPeriodicInterval_t periodicAdvertisingIntervalMax, + ble::periodic_interval_t periodicAdvertisingIntervalMin, + ble::periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower = true ) { (void) handle; @@ -1976,8 +1958,8 @@ public: */ virtual ble_error_t startScan( ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, - UnitScanDuration_t duration = UnitScanDuration_t(0), - UnitScanPeriod_t period = UnitScanPeriod_t(0) + ble::scan_duration_t duration = ble::scan_duration_t(0), + ble::scan_period_t period = ble::scan_period_t(0) ) { use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -2000,8 +1982,8 @@ public: PeerAddressType_t peerAddressType, Address_t peerAddress, uint8_t sid, - UnitSlaveLatency_t maxPacketSkip, - UnitSyncTimeout_t timeout + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; @@ -2017,8 +1999,8 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createSync( - UnitSlaveLatency_t maxPacketSkip, - UnitSyncTimeout_t timeout + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 28c4359a3f..18c73eeeeb 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -50,8 +50,8 @@ public: /* setters */ ConnectionParameters& setScanParameters( - ble::unit_scan_interval_t scanInterval, - ble::unit_scan_window_t scanWindow, + ble::scan_interval_t scanInterval, + ble::scan_window_t scanWindow, ble::phy_t phy = ble::phy_t::LE_1M ) { uint8_t phy_index = handlePhyToggle(phy, true); @@ -63,13 +63,13 @@ public: } ConnectionParameters& setConnectionParameters( - ble::unit_conn_interval_t minConnectionInterval, - ble::unit_conn_interval_t maxConnectionInterval, - ble::unit_slave_latency_t slaveLatency, - ble::unit_supervision_timeout_t connectionSupervisionTimeout, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t connectionSupervisionTimeout, ble::phy_t phy = ble::phy_t::LE_1M, - ble::unit_conn_event_length_t minEventLength = ble::unit_conn_event_length_t(0), - ble::unit_conn_event_length_t maxEventLength = ble::unit_conn_event_length_t(0xFFFF) + ble::conn_event_length_t minEventLength = ble::conn_event_length_t(0), + ble::conn_event_length_t maxEventLength = ble::conn_event_length_t(0xFFFF) ) { uint8_t phy_index = handlePhyToggle(phy, true); diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 9a7de3e445..d81e6f688a 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -49,7 +49,7 @@ struct AdvertisingReportEvent { ble::advertising_sid_t SID, ble::advertising_power_t txPower, ble::rssi_t rssi, - ble::unit_periodic_interval_t periodicInterval, + ble::periodic_interval_t periodicInterval, const ble::peer_address_type_t &directAddressType, const ble::address_t &directAddress, const mbed::Span &advertisingData @@ -108,7 +108,7 @@ struct AdvertisingReportEvent { } /** Get interval. */ - ble::unit_periodic_interval_t getPeriodicInterval() const { + ble::periodic_interval_t getPeriodicInterval() const { return periodicInterval; } @@ -136,7 +136,7 @@ private: ble::advertising_sid_t SID; ble::advertising_power_t txPower; ble::rssi_t rssi; - ble::unit_periodic_interval_t periodicInterval; + ble::periodic_interval_t periodicInterval; ble::peer_address_type_t directAddressType; const ble::address_t &directAddress; mbed::Span advertisingData; @@ -167,9 +167,9 @@ struct ConnectionCompleteEvent { const ble::address_t &peerAddress, const ble::address_t &localResolvablePrivateAddress, const ble::address_t &peerResolvablePrivateAddress, - ble::unit_conn_interval_t connectionInterval, - ble::unit_slave_latency_t connectionLatency, - ble::unit_supervision_timeout_t supervisionTimeout, + ble::conn_interval_t connectionInterval, + ble::slave_latency_t connectionLatency, + ble::supervision_timeout_t supervisionTimeout, uint16_t masterClockAccuracy ) : status(status), @@ -220,17 +220,17 @@ struct ConnectionCompleteEvent { } /** Get connection interval. */ - ble::unit_conn_interval_t getConnectionInterval() const { + ble::conn_interval_t getConnectionInterval() const { return connectionInterval; } /** Get connection latency. */ - ble::unit_slave_latency_t getConnectionLatency() const { + ble::slave_latency_t getConnectionLatency() const { return connectionLatency; } /** Get supervision timeout. */ - ble::unit_supervision_timeout_t getSupervisionTimeout() const { + ble::supervision_timeout_t getSupervisionTimeout() const { return supervisionTimeout; } @@ -247,9 +247,9 @@ private: const ble::address_t &peerAddress; const ble::address_t &localResolvablePrivateAddress; const ble::address_t &peerResolvablePrivateAddress; - ble::unit_conn_interval_t connectionInterval; - ble::unit_slave_latency_t connectionLatency; - ble::unit_supervision_timeout_t supervisionTimeout; + ble::conn_interval_t connectionInterval; + ble::slave_latency_t connectionLatency; + ble::supervision_timeout_t supervisionTimeout; uint16_t masterClockAccuracy; }; diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 329b238f1f..0b4d341163 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -31,8 +31,8 @@ class ScanParameters { public: - typedef ble::unit_scan_window_t scan_window_t; - typedef ble::unit_scan_interval_t scan_interval_t; + typedef ble::scan_window_t scan_window_t; + typedef ble::scan_interval_t scan_interval_t; enum own_address_type_t { PUBLIC_ADDRESS = 0x00, diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 279eaa76aa..664f73ebfc 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -106,7 +106,7 @@ public: ble_error_t startAdvertising( AdvHandle_t handle, - UnitAdvDuration_t maxDuration, + adv_duration_t maxDuration, uint8_t maxEvents ); @@ -116,8 +116,8 @@ public: virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMin, - UnitPeriodicInterval_t periodicAdvertisingIntervalMax, + periodic_interval_t periodicAdvertisingIntervalMin, + periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower ); @@ -136,21 +136,21 @@ public: virtual ble_error_t startScan( scanning_filter_duplicates_t filtering, - UnitScanDuration_t duration, - UnitScanPeriod_t period + scan_duration_t duration, + scan_period_t period ); virtual ble_error_t createSync( PeerAddressType_t peerAddressType, uint8_t *peerAddress, uint8_t sid, - Gap::UnitSlaveLatency_t maxPacketSkip, - Gap::UnitSyncTimeout_t timeout + slave_latency_t maxPacketSkip, + sync_timeout_t timeout ); virtual ble_error_t createSync( - Gap::UnitSlaveLatency_t maxPacketSkip, - Gap::UnitSyncTimeout_t timeout + slave_latency_t maxPacketSkip, + sync_timeout_t timeout ); virtual ble_error_t cancelCreateSync(); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 2cf940633e..9569121a55 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1913,7 +1913,7 @@ ble_error_t GenericGap::setAdvertisingData( ble_error_t GenericGap::startAdvertising( AdvHandle_t handle, - UnitAdvDuration_t maxDuration, + adv_duration_t maxDuration, uint8_t maxEvents ) { ble_error_t error = BLE_ERROR_NONE; @@ -2017,8 +2017,8 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { ble_error_t GenericGap::setPeriodicAdvertisingParameters( Gap::AdvHandle_t handle, - UnitPeriodicInterval_t periodicAdvertisingIntervalMin, - UnitPeriodicInterval_t periodicAdvertisingIntervalMax, + periodic_interval_t periodicAdvertisingIntervalMin, + periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower ) { @@ -2198,9 +2198,9 @@ void GenericGap::on_enhanced_connection_complete( peer_address, local_resolvable_private_address, peer_resolvable_private_address, - UnitConnInterval_t(connection_interval), + conn_interval_t(connection_interval), connection_latency, - UnitSupervisionTimeout_t(supervision_timeout), + supervision_timeout_t(supervision_timeout), master_clock_accuracy.get_ppm() ) ); @@ -2236,7 +2236,7 @@ void GenericGap::on_extended_advertising_report( advertising_sid, tx_power, rssi, - UnitPeriodicInterval_t(periodic_advertising_interval), + ble::periodic_interval_t(periodic_advertising_interval), (PeerAddressType_t::type)direct_address_type.value(), (BLEProtocol::AddressBytes_t&)direct_address, mbed::make_Span(data, data_length) @@ -2399,8 +2399,8 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) ble_error_t GenericGap::startScan( scanning_filter_duplicates_t filtering, - UnitScanDuration_t duration, - UnitScanPeriod_t period + scan_duration_t duration, + scan_period_t period ) { use_non_deprecated_scan_api(); @@ -2447,8 +2447,8 @@ ble_error_t GenericGap::createSync( Gap::PeerAddressType_t peerAddressType, uint8_t *peerAddress, uint8_t sid, - UnitSlaveLatency_t maxPacketSkip, - UnitSyncTimeout_t timeout + slave_latency_t maxPacketSkip, + sync_timeout_t timeout ) { if (is_extended_advertising_available() == false) { @@ -2476,8 +2476,8 @@ ble_error_t GenericGap::createSync( } ble_error_t GenericGap::createSync( - UnitSlaveLatency_t maxPacketSkip, - UnitSyncTimeout_t timeout + slave_latency_t maxPacketSkip, + sync_timeout_t timeout ) { if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; From f0cbd9f434ecdbbde131273c6ca17a97ae9d5d73 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 16:46:02 +0000 Subject: [PATCH 170/361] BLE: move GapAdvertisingParameters to ble::AdvertisingParameters --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 8 ++++++-- features/FEATURE_BLE/ble/generic/GenericGap.h | 6 +++--- features/FEATURE_BLE/source/generic/GenericGap.cpp | 8 ++++---- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index ca48d3d644..6da1f6f20f 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1735,7 +1735,7 @@ public: */ virtual ble_error_t createAdvertisingSet( AdvHandle_t *handle, - const GapAdvertisingParameters ¶meters + const ble::AdvertisingParameters ¶meters ) { (void) handle; @@ -1765,7 +1765,7 @@ public: */ virtual ble_error_t setAdvertisingParams( AdvHandle_t handle, - const GapAdvertisingParameters ¶ms + const ble::AdvertisingParameters ¶ms ) { (void) handle; (void) params; diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 95f3229a6e..4e256b5133 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -29,6 +29,8 @@ * @{ */ +namespace ble { + /** * Parameters defining the advertising process. * @@ -42,7 +44,7 @@ * - Duration of the advertising process. As others, it can be set at * construction time, modified by setTimeout() and retrieved by getTimeout(). */ -class GapAdvertisingParameters { +class AdvertisingParameters { public: /** @@ -99,7 +101,7 @@ public: * * @note If value in input are out of range, they will be normalized. */ - GapAdvertisingParameters( + AdvertisingParameters( ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, uint32_t minInterval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, uint32_t maxInterval = GAP_ADV_PARAMS_INTERVAL_MAX, @@ -691,6 +693,8 @@ private: uint8_t _includeHeaderTxPower:1; }; +} // namespace ble + /** * @} * @} diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 664f73ebfc..ff6ec94997 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -82,14 +82,14 @@ public: ble_error_t createAdvertisingSet( AdvHandle_t *handle, - const GapAdvertisingParameters ¶meters + const AdvertisingParameters ¶meters ); ble_error_t destroyAdvertisingSet(AdvHandle_t handle); ble_error_t setAdvertisingParams( AdvHandle_t handle, - const GapAdvertisingParameters ¶ms + const AdvertisingParameters ¶ms ); ble_error_t setAdvertisingPayload( @@ -670,7 +670,7 @@ private: private: ble_error_t setExtendedAdvertisingParameters( AdvHandle_t handle, - const GapAdvertisingParameters ¶meters + const AdvertisingParameters ¶meters ); bool is_extended_advertising_available(); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9569121a55..496af15110 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -435,7 +435,7 @@ GenericGap::GenericGap( if (is_extended_advertising_available()) { setExtendedAdvertisingParameters( LEGACY_ADVERTISING_HANDLE, - GapAdvertisingParameters() + AdvertisingParameters() ); } } @@ -1658,7 +1658,7 @@ uint8_t GenericGap::getMaxAdvertisingDataLength() ble_error_t GenericGap::createAdvertisingSet( AdvHandle_t *handle, - const GapAdvertisingParameters ¶meters + const AdvertisingParameters ¶meters ) { if (is_extended_advertising_available()) { @@ -1724,7 +1724,7 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { ble_error_t GenericGap::setAdvertisingParams( AdvHandle_t handle, - const GapAdvertisingParameters ¶ms + const AdvertisingParameters ¶ms ) { if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; @@ -1762,7 +1762,7 @@ ble_error_t GenericGap::setAdvertisingParams( ble_error_t GenericGap::setExtendedAdvertisingParameters( AdvHandle_t handle, - const GapAdvertisingParameters ¶ms + const AdvertisingParameters ¶ms ) { if (handle >= getMaxAdvertisingSetNumber()) { From 07cf0f5b9183c8113f0ecc6cd1c64515020b8669 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 16:48:30 +0000 Subject: [PATCH 171/361] BLE: Move ConnectionParameters into ble namespace. --- features/FEATURE_BLE/ble/Gap.h | 2 +- .../ble/gap/ConnectionParameters.h | 108 ++++++++++++------ 2 files changed, 72 insertions(+), 38 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 6da1f6f20f..8a916c77d1 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1505,7 +1505,7 @@ public: virtual ble_error_t connect( TargetPeerAddressType_t peerAddressType, const ble::address_t &peerAddress, - const ConnectionParameters &connectionParams + const ble::ConnectionParameters &connectionParams ) { (void)peerAddressType; (void)peerAddress; diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 18c73eeeeb..b097dd6696 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -27,6 +27,8 @@ * @{ */ +namespace ble { + class ConnectionParameters { static const uint8_t MAX_PARAM_PHYS = 3; public: @@ -49,11 +51,12 @@ public: /* setters */ - ConnectionParameters& setScanParameters( + ConnectionParameters &setScanParameters( ble::scan_interval_t scanInterval, ble::scan_window_t scanWindow, ble::phy_t phy = ble::phy_t::LE_1M - ) { + ) + { uint8_t phy_index = handlePhyToggle(phy, true); _scanInterval[phy_index] = scanInterval.value(); @@ -62,15 +65,18 @@ public: return *this; } - ConnectionParameters& setConnectionParameters( + ConnectionParameters &setConnectionParameters( ble::conn_interval_t minConnectionInterval, ble::conn_interval_t maxConnectionInterval, ble::slave_latency_t slaveLatency, ble::supervision_timeout_t connectionSupervisionTimeout, ble::phy_t phy = ble::phy_t::LE_1M, ble::conn_event_length_t minEventLength = ble::conn_event_length_t(0), - ble::conn_event_length_t maxEventLength = ble::conn_event_length_t(0xFFFF) - ) { + ble::conn_event_length_t maxEventLength = ble::conn_event_length_t( + 0xFFFF + ) + ) + { uint8_t phy_index = handlePhyToggle(phy, true); _minConnectionInterval[phy_index] = minConnectionInterval.value(); @@ -89,27 +95,30 @@ public: return *this; } - ConnectionParameters& setOwnAddressType( + ConnectionParameters &setOwnAddressType( ble::own_address_type_t ownAddress - ) { + ) + { _ownAddressType = ownAddress; return *this; } - ConnectionParameters& setFilterPolicy( + ConnectionParameters &setFilterPolicy( ble::scanning_policy_mode_t filterPolicy - ) { + ) + { _filterPolicy = filterPolicy; return *this; } - ConnectionParameters& togglePhy( + ConnectionParameters &togglePhy( bool phy1M, bool phy2M, bool phyCoded - ) { + ) + { handlePhyToggle(ble::phy_t::LE_1M, phy1M); handlePhyToggle(ble::phy_t::LE_2M, phy2M); handlePhyToggle(ble::phy_t::LE_CODED, phyCoded); @@ -117,17 +126,19 @@ public: return *this; } - ConnectionParameters& disablePhy( + ConnectionParameters &disablePhy( ble::phy_t phy = ble::phy_t::LE_1M - ) { + ) + { handlePhyToggle(phy, false); return *this; } - ConnectionParameters& enablePhy( + ConnectionParameters &enablePhy( ble::phy_t phy = ble::phy_t::LE_1M - ) { + ) + { handlePhyToggle(phy, true); return *this; @@ -135,21 +146,27 @@ public: /* getters */ - ble::own_address_type_t getOwnAddressType() const { + ble::own_address_type_t getOwnAddressType() const + { return _ownAddressType; } - ble::scanning_policy_mode_t getFilterPolicy() const { + ble::scanning_policy_mode_t getFilterPolicy() const + { return _filterPolicy; } - uint8_t getNumberOfEnabledPhys() const { - return (_enabledPhy[ble::phy_t::LE_1M] * 1 + - _enabledPhy[ble::phy_t::LE_2M] * 1 + - _enabledPhy[ble::phy_t::LE_CODED] * 1); + uint8_t getNumberOfEnabledPhys() const + { + return ( + _enabledPhy[ble::phy_t::LE_1M] * 1 + + _enabledPhy[ble::phy_t::LE_2M] * 1 + + _enabledPhy[ble::phy_t::LE_CODED] * 1 + ); } - uint8_t getPhySet() const { + uint8_t getPhySet() const + { ble::phy_set_t set( _enabledPhy[ble::phy_t::LE_1M], _enabledPhy[ble::phy_t::LE_2M], @@ -160,40 +177,49 @@ public: /* these return pointers to arrays of settings valid only across the number of active PHYs */ - const uint16_t* getScanIntervalArray() const { + const uint16_t *getScanIntervalArray() const + { return &_scanInterval[getFirstEnabledIndex()]; } - const uint16_t* getScanWindowArray() const { + const uint16_t *getScanWindowArray() const + { return &_scanWindow[getFirstEnabledIndex()]; } - const uint16_t* getMinConnectionIntervalArray() const { + const uint16_t *getMinConnectionIntervalArray() const + { return &_minConnectionInterval[getFirstEnabledIndex()]; } - const uint16_t* getMaxConnectionIntervalArray() const { + const uint16_t *getMaxConnectionIntervalArray() const + { return &_maxConnectionInterval[getFirstEnabledIndex()]; } - const uint16_t* getSlaveLatencyArray() const { + const uint16_t *getSlaveLatencyArray() const + { return &_slaveLatency[getFirstEnabledIndex()]; } - const uint16_t* getConnectionSupervisionTimeoutArray() const { + const uint16_t *getConnectionSupervisionTimeoutArray() const + { return &_connectionSupervisionTimeout[getFirstEnabledIndex()]; } - const uint16_t* getMinEventLengthArray() const { + const uint16_t *getMinEventLengthArray() const + { return &_minEventLength[getFirstEnabledIndex()]; } - const uint16_t* getMaxEventLengthArray() const { + const uint16_t *getMaxEventLengthArray() const + { return &_maxEventLength[getFirstEnabledIndex()]; } private: - uint8_t getFirstEnabledIndex() const { + uint8_t getFirstEnabledIndex() const + { if (_enabledPhy[ble::phy_t::LE_1M]) { return 0; } else if (_enabledPhy[ble::phy_t::LE_2M]) { @@ -203,7 +229,8 @@ private: } /* this should never happen, it means you were trying to start a connection with a blank set * of paramters - you need to enabled at least one phy */ - MBED_ASSERT("Trying to use connection parameters without any PHY defined."); + MBED_ASSERT( + "Trying to use connection parameters without any PHY defined."); return 0; } @@ -213,7 +240,8 @@ private: * @param enable On or Off. * @return The index to the array of settings. */ - uint8_t handlePhyToggle(ble::phy_t phy, bool enable) { + uint8_t handlePhyToggle(ble::phy_t phy, bool enable) + { uint8_t index = phy.value(); bool was_swapped = false; @@ -240,14 +268,18 @@ private: return index; } - bool isSwapped() const { - return (_enabledPhy[ble::phy_t::LE_1M] && + bool isSwapped() const + { + return ( + _enabledPhy[ble::phy_t::LE_1M] && !_enabledPhy[ble::phy_t::LE_2M] && - _enabledPhy[ble::phy_t::LE_CODED]); + _enabledPhy[ble::phy_t::LE_CODED] + ); } /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ - void swapCodedAnd2M() { + void swapCodedAnd2M() + { uint16_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; uint16_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; uint16_t minConnectionInterval = _minConnectionInterval[ble::phy_t::LE_2M]; @@ -292,6 +324,8 @@ private: bool _enabledPhy[MAX_PARAM_PHYS]; }; +} // namespace ble + /** * @} * @} From 5dc6c1d670b0883d67f5036d5ec2d1f51dc0bd00 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 16:58:21 +0000 Subject: [PATCH 172/361] BLE: move ScanParameters into ble namespace. --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/gap/ScanParameters.h | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8a916c77d1..185e7f8603 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1936,7 +1936,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setScanParameters( - const ScanParameters& params + const ble::ScanParameters& params ) { use_non_deprecated_scan_api(); /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 0b4d341163..bf582e40ed 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -28,6 +28,7 @@ * @{ */ +namespace ble { class ScanParameters { public: @@ -152,6 +153,8 @@ private: phy_configuration_t phy_coded_configuration; }; +} // namespace ble + /** * @} * @} From f3c47f135b1a5e147fb4d24e73edfbef5d001cb6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 14 Nov 2018 14:28:16 +0000 Subject: [PATCH 173/361] docs --- features/FEATURE_BLE/ble/generic/GenericGap.h | 54 ++++++++++- features/FEATURE_BLE/ble/pal/PalGap.h | 97 +++++++++---------- 2 files changed, 98 insertions(+), 53 deletions(-) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index ff6ec94997..b0d96c122d 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -51,9 +51,9 @@ public: static const uint8_t MAX_ADVERTISING_SETS = 15; static const size_t MAX_HCI_DATA_LENGTH = 251; /** - * Construct a GenericGap instance for a given BLE instance ID. + * Construct a GenericGap. * - * @param ble_instance_id Id of the BLE instance using this instance. + * @param event_queue Event queue used to serialise execution. * * @param pal_gap GAP Platform abstraction instance containing the base GAP * primitives. @@ -76,44 +76,66 @@ public: */ virtual ~GenericGap(); + /** @copydoc Gap::getMaxAdvertisingSetNumber + */ uint8_t getMaxAdvertisingSetNumber(); + /** @copydoc Gap::getMaxAdvertisingDataLength + */ uint8_t getMaxAdvertisingDataLength(); + /** @copydoc Gap::createAdvertisingSet + */ ble_error_t createAdvertisingSet( AdvHandle_t *handle, const AdvertisingParameters ¶meters ); + /** @copydoc Gap::destroyAdvertisingSet + */ ble_error_t destroyAdvertisingSet(AdvHandle_t handle); + /** @copydoc Gap::setAdvertisingParams + */ ble_error_t setAdvertisingParams( AdvHandle_t handle, const AdvertisingParameters ¶ms ); + /** @copydoc Gap::setAdvertisingPayload + */ ble_error_t setAdvertisingPayload( AdvHandle_t handle, mbed::Span payload, bool minimiseFragmentation ); + /** @copydoc Gap::setAdvertisingScanResponse + */ ble_error_t setAdvertisingScanResponse( AdvHandle_t handle, mbed::Span response, bool minimiseFragmentation ); + /** @copydoc Gap::startAdvertising + */ ble_error_t startAdvertising( AdvHandle_t handle, adv_duration_t maxDuration, uint8_t maxEvents ); + /** @copydoc Gap::stopAdvertising + */ ble_error_t stopAdvertising(AdvHandle_t handle); + /** @copydoc Gap::isAdvertisingActive + */ bool isAdvertisingActive(AdvHandle_t handle); + /** @copydoc Gap::setPeriodicAdvertisingParameters + */ virtual ble_error_t setPeriodicAdvertisingParameters( AdvHandle_t handle, periodic_interval_t periodicAdvertisingIntervalMin, @@ -121,25 +143,39 @@ public: bool advertiseTxPower ); + /** @copydoc Gap::setPeriodicAdvertisingPayload + */ virtual ble_error_t setPeriodicAdvertisingPayload( AdvHandle_t handle, mbed::Span payload ); + /** @copydoc Gap::startPeriodicAdvertising + */ virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle); + /** @copydoc Gap::stopPeriodicAdvertising + */ virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle); + /** @copydoc Gap::isPeriodicAdvertisingActive + */ virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle); + /** @copydoc Gap::setScanParameters + */ virtual ble_error_t setScanParameters(const ScanParameters ¶ms); + /** @copydoc Gap::startScan + */ virtual ble_error_t startScan( scanning_filter_duplicates_t filtering, scan_duration_t duration, scan_period_t period ); + /** @copydoc Gap::createSync + */ virtual ble_error_t createSync( PeerAddressType_t peerAddressType, uint8_t *peerAddress, @@ -148,29 +184,43 @@ public: sync_timeout_t timeout ); + /** @copydoc Gap::createSync + */ virtual ble_error_t createSync( slave_latency_t maxPacketSkip, sync_timeout_t timeout ); + /** @copydoc Gap::cancelCreateSync + */ virtual ble_error_t cancelCreateSync(); + /** @copydoc Gap::terminateSync + */ virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle); + /** @copydoc Gap::addDeviceToPeriodicAdvertiserList + */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( PeerAddressType_t peerAddressType, Address_t peerAddress, uint8_t sid ); + /** @copydoc Gap::removeDeviceFromPeriodicAdvertiserList + */ virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( PeerAddressType_t peerAddressType, uint8_t *peerAddress, uint8_t sid ); + /** @copydoc Gap::clearPeriodicAdvertiserList + */ virtual ble_error_t clearPeriodicAdvertiserList(); + /** @copydoc Gap::getMaxPeriodicAdvertiserListSize + */ virtual uint8_t getMaxPeriodicAdvertiserListSize(); /** diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index 6a0d103049..9c397f48d3 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -134,23 +134,21 @@ struct Gap { clock_accuracy_t master_clock_accuracy ) = 0; - /** - * Should be invoked by the Gap implementation when an extended - * advertising report event happens. + /** Called on advertising report event. * - * @param event_type - * @param address_type - * @param address - * @param primary_phy - * @param secondary_phy - * @param advertising_sid - * @param tx_power - * @param rssi - * @param periodic_advertising_interval - * @param direct_address_type - * @param direct_address - * @param data_length - * @param data_size + * @param event_type Type of advertising used. + * @param address_type Peer address type of advertiser. + * @param address Peer address of advertiser. + * @param primary_phy PHY used on the primary channels. + * @param secondary_phy PHY used on secondary channels. + * @param advertising_sid Set identification number. + * @param tx_power Transmission power reported by the packet. + * @param rssi Measured signal strength. + * @param periodic_advertising_interval Interval of periodic advertising. + * @param direct_address_type Directed advertising target address type. + * @param direct_address Directed advertising target address. + * @param data_length Advertising payload length. + * @param data Advertising payload. * * @note: See Bluetooth 5 Vol 2 PartE: 7.7.65.13 LE extended advertising * report event. @@ -171,18 +169,16 @@ struct Gap { const uint8_t *data_size ) = 0; - /** - * TODO - * @param error - * @param sync_handle - * @param advertising_sid - * @param advertiser_address_type - * @param advertiser_address - * @param periodic_advertising_interval - * @param clock_accuracy + /** Called on advertising sync event. * - * @note: See Bluetooth 5 Vol 2 PartE: 7.7.65.14 LE extended advertising - * report event. + * @param error SUCCESS if synchronisation was achieved. + * @param sync_handle Advertising sync handle. + * @param advertising_sid Advertising set identifier. + * @param advertiser_address_type Peer address type. + * @param advertiser_address Peer address. + * @param advertiser_phy PHY used for advertisements. + * @param periodic_advertising_interval Periodic advertising interval. + * @param clock_accuracy Peer clock accuracy. */ virtual void on_periodic_advertising_sync_established( pal::hci_error_code_t error, @@ -195,14 +191,14 @@ struct Gap { pal::clock_accuracy_t clock_accuracy ) = 0; - /** - * TODO - * @param sync_handle - * @param tx_power - * @param rssi - * @param data_status - * @param data_length - * @param data + /** Called after a periodic advertising report event. + * + * @param sync_handle Periodic advertising sync handle + * @param tx_power TX power. + * @param rssi Received signal strength. + * @param data_status Status to indicate the completeness of the payload. + * @param data_length Periodic advertisement payload length. + * @param data Periodic advertisement payload. */ virtual void on_periodic_advertising_report( sync_handle_t sync_handle, @@ -213,25 +209,24 @@ struct Gap { const uint8_t *data ) = 0; - /** - * TODO - * @param sync_handle + /** Called on periodic advertising sync loss event. + * + * @param sync_handle Advertising sync handle' */ virtual void on_periodic_advertising_sync_loss( sync_handle_t sync_handle ) = 0; - /** - * TODO + /** Called when scanning times out. */ virtual void on_scan_timeout() = 0; - /** - * TODO - * @param status - * @param advertising_handle - * @param connection_handle - * @param number_of_completed_extended_advertising_events + /** Called when advertising set stops advertising. + * + * @param status SUCCESS if connection has been established. + * @param advertising_handle Advertising set handle. + * @param advertising_handle Connection handle. + * @param number_of_completed_extended_advertising_events Number of events created during before advertising end. */ virtual void on_advertising_set_terminated( hci_error_code_t status, @@ -240,11 +235,11 @@ struct Gap { uint8_t number_of_completed_extended_advertising_events ) = 0; - /** - * TODO - * @param advertising_handle - * @param scanner_address_type - * @param address + /** Called when a device receives a scan request from an active scanning device. + * + * @param advertising_handle Advertising set handle. + * @param scanner_address_type Peer address type. + * @param address Peer address. */ virtual void on_scan_request_received( advertising_handle_t advertising_handle, From 05fb66a98752392137e605e417dfc0cd0361d8d0 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 14 Nov 2018 15:35:52 +0000 Subject: [PATCH 174/361] docs --- features/FEATURE_BLE/ble/Gap.h | 66 ++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 185e7f8603..f259399898 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -126,6 +126,72 @@ * gap.startAdvertising(); * @endcode * + * @par Extended advertising + * + * Extended advertising allows for a wider choice of options than legacy advertising. + * You can send bigger payloads and use different PHYs. This allows for bigger throughput + * or longer range. + * + * Extended advertising may be split across many packets and takes place on both the + * regular advertising channels and the rest of the 37 channels normally used by + * connected devices. + * + * The 3 channels used in legacy advertising are called Primary Advertisement channels. + * The remaining 37 channels are used for secondary advertising. Unlike sending data + * during a connection this allows the device to broadcast data to multiple devices. + * + * The advertising starts on the Primary channels (which you may select) and continues + * on the secondary channels as indicated in the packet sent on the Primary channel. + * This way the advertising can send large payloads without saturating the advertising + * channels. Primary channels are limited to 1M and coded PHYs but Secondary channels + * may use the increased throughput 2M PHY. + * + * @par Periodic advertising + * + * Similarly, you can use periodic advertising to transfer regular data to multiple + * devices. + * + * The advertiser will use primary channels to advertise the information needed to + * listen to the periodic advertisements on secondary channels. This sync information + * will be used by the scanner who can now optimise for power consumption and only + * listen for the periodic advertisements at specified times. + * + * Like extended advertising, periodic advertising offers extra PHY options of 2M + * and coded. The payload may be updated at any time and will be updated on the next + * advertisement event when the periodic advertising is active. + * + * @par Advertising sets + * + * Advertisers may advertise multiple payloads at the same time. The configuration + * and identification of these is done through advertising sets. Use a handle + * obtained from createAvertisingSet() for advertising operations. After ending + * all advertising operations you should remove the handle from the system using + * destroyAdvertisingHandle(). + * + * Extended advertising and periodic advertising is an optional feature and not all + * devices support it and will only be able to see the now called legacy advertising. + * + * Legacy advertising is available through a special handle LEGACY_ADVERTISING_HANDLE. + * This handle is always available and doesn't need to be created and cannot be + * destroyed. + * + * There is a limited number of advertising sets available since they require support + * from the controller. Their availability is dynamic and may be queried at any time + * using getMaxAdvertisingSetNumber(). Advertising sets take up resources even if + * they are not actively advertising right now so it's important to destroy the set + * when you're done with it (or reuse it in the next advertisement). + * + * Periodic advertising and extended advertising share the same set. For periodic + * advertising to start the extended advertising of the same set must also be active. + * Subsequently you may disable extended advertising and the periodic advertising + * will continue. If you start periodic advertising while extended advertising is + * inactive, periodic advertising will not start until you start extended advertising + * at a later time. + * + * @par Extended scanning + * + * In order to see extended and periodic advertising you must use extended scanning. + * * @par Privacy * * Privacy is a feature that allows a device to avoid being tracked by other From 09f71d278d1b37e45ab798e3039c8563b81d2f99 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 14 Nov 2018 16:54:17 +0000 Subject: [PATCH 175/361] move feature support into user api --- features/FEATURE_BLE/ble/BLETypes.h | 29 +++++++++++++++++++ features/FEATURE_BLE/ble/Gap.h | 9 ++++++ features/FEATURE_BLE/ble/generic/GenericGap.h | 6 ++++ features/FEATURE_BLE/ble/pal/PalGap.h | 27 ----------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 10 +++++-- .../targets/TARGET_CORDIO/CordioPalGap.h | 2 +- .../TARGET_CORDIO/source/CordioPalGap.cpp | 2 +- 7 files changed, 54 insertions(+), 31 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index da93755239..5ca26aab15 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -44,6 +44,7 @@ void clamp(T& value, const R& min, const R& max) { } } +/* BLE units, using microseconds as the common denominator */ typedef Duration > adv_interval_t; typedef Duration > adv_duration_t; typedef Duration > scan_duration_t; @@ -61,6 +62,34 @@ typedef Duration us_t; typedef Bounded slave_latency_t; +/** Features supported by the controller. + * @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 6, Part B - 4.6 */ +struct ControllerSupportedFeatures_t : SafeEnum { + enum type { + LE_ENCRYPTION = 0, + CONNECTION_PARAMETERS_REQUEST_PROCEDURE, + EXTENDED_REJECT_INDICATION, + SLAVE_INITIATED_FEATURES_EXCHANGE, + LE_PING, + LE_DATA_PACKET_LENGTH_EXTENSION, + LL_PRIVACY, + EXTENDED_SCANNER_FILTER_POLICIES, + LE_2M_PHY, + STABLE_MODULATION_INDEX_TRANSMITTER, + STABLE_MODULATION_INDEX_RECEIVER, + LE_CODED_PHY, + LE_EXTENDED_ADVERTISING, + LE_PERIODIC_ADVERTISING, + CHANNEL_SELECTION_ALGORITHM_2, + LE_POWER_CLASS + }; + + /** + * Construct a new instance of ControllerSupportedFeatures_t. + */ + ControllerSupportedFeatures_t(type value) : SafeEnum(value) { } +}; + /** * Opaque reference to a connection. * diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index f259399898..319c291ca7 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1768,6 +1768,15 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } + /** Check controller support for a specific feature. + * + * @param feature Feature to check. + * @return True if feature is supported. + */ + bool IsFeatureSupported( + ble::ControllerSupportedFeatures_t feature + ); + /* advertising */ /** Return currently available number of supported advertising sets. diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index b0d96c122d..faabfdf785 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -76,6 +76,12 @@ public: */ virtual ~GenericGap(); + /** @copydoc Gap::IsFeatureSupported + */ + bool IsFeatureSupported( + ble::ControllerSupportedFeatures_t feature + ); + /** @copydoc Gap::getMaxAdvertisingSetNumber */ uint8_t getMaxAdvertisingSetNumber(); diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index 9c397f48d3..60fe77162d 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -33,33 +33,6 @@ namespace pal { * by that layer. */ struct Gap { - /** @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 6, Part B - 4.6 */ - struct ControllerSupportedFeatures_t : SafeEnum { - enum type { - LE_ENCRYPTION = 0, - CONNECTION_PARAMETERS_REQUEST_PROCEDURE, - EXTENDED_REJECT_INDICATION, - SLAVE_INITIATED_FEATURES_EXCHANGE, - LE_PING, - LE_DATA_PACKET_LENGTH_EXTENSION, - LL_PRIVACY, - EXTENDED_SCANNER_FILTER_POLICIES, - LE_2M_PHY, - STABLE_MODULATION_INDEX_TRANSMITTER, - STABLE_MODULATION_INDEX_RECEIVER, - LE_CODED_PHY, - LE_EXTENDED_ADVERTISING, - LE_PERIODIC_ADVERTISING, - CHANNEL_SELECTION_ALGORITHM_2, - LE_POWER_CLASS - }; - - /** - * Construct a new instance of ControllerSupportedFeatures_t. - */ - ControllerSupportedFeatures_t(type value) : SafeEnum(value) { } - }; - struct EventHandler { /** * @copydoc Gap::EventHandler::onReadPhy diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 496af15110..b14fa93c7a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -444,6 +444,12 @@ GenericGap::~GenericGap() { } +bool GenericGap::IsFeatureSupported( + ble::ControllerSupportedFeatures_t feature +) { + return _pal_gap.is_feature_supported(feature); +} + ble_error_t GenericGap::setAddress( LegacyAddressType_t type, const Address_t address @@ -2601,8 +2607,8 @@ void GenericGap::use_non_deprecated_scan_api() const bool GenericGap::is_extended_advertising_available() { - return _pal_gap.is_feature_supported( - pal::Gap::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING + return IsFeatureSupported( + ble::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING ); } diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h index 1b7013ae37..cd6c433e53 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h @@ -15,7 +15,7 @@ namespace cordio { class Gap : public ::ble::pal::Gap { public: virtual bool is_feature_supported( - Gap::ControllerSupportedFeatures_t feature + ble::ControllerSupportedFeatures_t feature ); virtual ble_error_t initialize(); diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index b27c81f581..461a6cf914 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -24,7 +24,7 @@ namespace vendor { namespace cordio { bool Gap::is_feature_supported( - Gap::ControllerSupportedFeatures_t feature + ble::ControllerSupportedFeatures_t feature ) { return (HciGetLeSupFeat() & (1 << feature.value())); } From 65d84e422766f62ebf36a04264f41e0a81e24038 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 14 Nov 2018 17:14:17 +0000 Subject: [PATCH 176/361] fix case --- features/FEATURE_BLE/ble/BLETypes.h | 20 +++++++++---------- features/FEATURE_BLE/ble/Gap.h | 6 +++++- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/ble/pal/PalGap.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- .../targets/TARGET_CORDIO/CordioPalGap.h | 2 +- .../TARGET_CORDIO/source/CordioPalGap.cpp | 6 +++--- 7 files changed, 23 insertions(+), 19 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 5ca26aab15..6d60bc8d9f 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -64,7 +64,7 @@ typedef Bounded slave_latency_t; /** Features supported by the controller. * @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 6, Part B - 4.6 */ -struct ControllerSupportedFeatures_t : SafeEnum { +struct controller_supported_features_t : SafeEnum { enum type { LE_ENCRYPTION = 0, CONNECTION_PARAMETERS_REQUEST_PROCEDURE, @@ -87,7 +87,7 @@ struct ControllerSupportedFeatures_t : SafeEnum(value) { } + controller_supported_features_t(type value) : SafeEnum(value) { } }; /** @@ -1123,42 +1123,42 @@ struct clock_accuracy_t : SafeEnum{ /** * 500 PPM */ - PPM_500 = 0x00, + PPM_500 = 0x00, /** * 250 PPM */ - PPM_250 = 0x01, + PPM_250 = 0x01, /** * 150 PPM */ - PPM_150 = 0x02, + PPM_150 = 0x02, /** * 100 PPM */ - PPM_100 = 0x03, + PPM_100 = 0x03, /** * 75 PPM */ - PPM_75 = 0x04, + PPM_75 = 0x04, /** * 50 PPM */ - PPM_50 = 0x05, + PPM_50 = 0x05, /** * 30 PPM */ - PPM_30 = 0x06, + PPM_30 = 0x06, /** * 20 PPM */ - PPM_20 = 0x07 + PPM_20 = 0x07 }; /** Get clock accuracy. diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 319c291ca7..f784c7eb8d 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -601,6 +601,10 @@ public: unsigned connected : 1; }; + /** Enumeration of controller supported features. + */ + typedef ble::controller_supported_features_t ControllerSupportedFeatures_t; + /** * Opaque value type representing a connection handle. * @@ -1774,7 +1778,7 @@ public: * @return True if feature is supported. */ bool IsFeatureSupported( - ble::ControllerSupportedFeatures_t feature + ControllerSupportedFeatures_t feature ); /* advertising */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index faabfdf785..9e36a2b8c5 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -79,7 +79,7 @@ public: /** @copydoc Gap::IsFeatureSupported */ bool IsFeatureSupported( - ble::ControllerSupportedFeatures_t feature + ble::controller_supported_features_t feature ); /** @copydoc Gap::getMaxAdvertisingSetNumber diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index 60fe77162d..f04329e58b 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -1531,7 +1531,7 @@ struct Gap { * @return TRUE if feature is supported. */ virtual bool is_feature_supported( - ControllerSupportedFeatures_t feature + controller_supported_features_t feature ) = 0; /** diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b14fa93c7a..1d5e4f2922 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -445,7 +445,7 @@ GenericGap::~GenericGap() } bool GenericGap::IsFeatureSupported( - ble::ControllerSupportedFeatures_t feature + ble::controller_supported_features_t feature ) { return _pal_gap.is_feature_supported(feature); } @@ -2608,7 +2608,7 @@ void GenericGap::use_non_deprecated_scan_api() const bool GenericGap::is_extended_advertising_available() { return IsFeatureSupported( - ble::ControllerSupportedFeatures_t::LE_EXTENDED_ADVERTISING + ble::controller_supported_features_t::LE_EXTENDED_ADVERTISING ); } diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h index cd6c433e53..02e6910d18 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioPalGap.h @@ -15,7 +15,7 @@ namespace cordio { class Gap : public ::ble::pal::Gap { public: virtual bool is_feature_supported( - ble::ControllerSupportedFeatures_t feature + ble::controller_supported_features_t feature ); virtual ble_error_t initialize(); diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index 461a6cf914..cc867679f6 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -24,7 +24,7 @@ namespace vendor { namespace cordio { bool Gap::is_feature_supported( - ble::ControllerSupportedFeatures_t feature + ble::controller_supported_features_t feature ) { return (HciGetLeSupFeat() & (1 << feature.value())); } @@ -335,8 +335,8 @@ ble_error_t Gap::set_address_resolution( } ble_error_t Gap::read_phy(connection_handle_t connection) { - if (is_feature_supported(ControllerSupportedFeatures_t::LE_2M_PHY) - || is_feature_supported(ControllerSupportedFeatures_t::LE_CODED_PHY)) { + if (is_feature_supported(controller_supported_features_t::LE_2M_PHY) + || is_feature_supported(controller_supported_features_t::LE_CODED_PHY)) { DmReadPhy(connection); return BLE_ERROR_NONE; } From 812b86a1974cecd53b2c13ee186224d7995a5014 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 17:44:21 +0000 Subject: [PATCH 177/361] BLE: cleanup ble::AdvertisingParameters * Use constrained types where relevant. * Remove fields N/A fields --- .../ble/gap/AdvertisingParameters.h | 377 +++++------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 8 +- 2 files changed, 112 insertions(+), 273 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 4e256b5133..d5494ace63 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -17,6 +17,8 @@ #ifndef MBED_ADVERTISING_PARAMETERS_H__ #define MBED_ADVERTISING_PARAMETERS_H__ +#include + #include "BLETypes.h" #include "BLEProtocol.h" #include "blecommon.h" @@ -45,15 +47,10 @@ namespace ble { * construction time, modified by setTimeout() and retrieved by getTimeout(). */ class AdvertisingParameters { -public: - /** - * Minimum Advertising interval for connectable undirected and connectable - * directed events in 625us units. - * - * @note Equal to 20 ms. - */ - static const unsigned GAP_ADV_PARAMS_INTERVAL_MIN = 0x0020; + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; + + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; /** * Minimum Advertising interval for scannable and nonconnectable @@ -61,33 +58,7 @@ public: * * @note Equal to 100ms. */ - static const unsigned GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; - - /** - * Maximum Advertising interval in 625us units. - * - * @note Equal to 10.24s. - */ - static const unsigned GAP_ADV_PARAMS_INTERVAL_MAX = 0x4000; - - /** - * Maximum advertising timeout allowed; in seconds. - */ - static const unsigned GAP_ADV_PARAMS_TIMEOUT_MAX = 0x3FFF; - - /** - * Alias for GapAdvertisingParams::ble::advertising_type_t. - * - * @deprecated Future releases will drop this type alias. - */ - typedef ble::advertising_type_t AdvertisingType; - - typedef ble::advertising_type_t AdvertisingType_t; - - static const ble::advertising_type_t ADV_CONNECTABLE_UNDIRECTED = ble::ADV_CONNECTABLE_UNDIRECTED; - static const ble::advertising_type_t ADV_CONNECTABLE_DIRECTED = ble::ADV_CONNECTABLE_DIRECTED; - static const ble::advertising_type_t ADV_SCANNABLE_UNDIRECTED = ble::ADV_SCANNABLE_UNDIRECTED; - static const ble::advertising_type_t ADV_NON_CONNECTABLE_UNDIRECTED = ble::ADV_NON_CONNECTABLE_UNDIRECTED; + static const uint32_t GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; public: /** @@ -103,14 +74,12 @@ public: */ AdvertisingParameters( ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, - uint32_t minInterval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, - uint32_t maxInterval = GAP_ADV_PARAMS_INTERVAL_MAX, - uint16_t timeout = 0 + adv_interval_t minInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MIN), + adv_interval_t maxInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MAX) ) : _advType(advType), _minInterval(minInterval), _maxInterval(maxInterval), - _timeout(timeout), _peerAddressType(ble::target_peer_address_type_t::PUBLIC), _ownAddressType(ble::own_address_type_t::PUBLIC), _policy(ble::ADV_POLICY_IGNORE_WHITELIST), @@ -127,62 +96,14 @@ public: _legacyPDU(1), _includeHeaderTxPower(0) { - /* Interval checks. */ - if (_advType == ble::ADV_CONNECTABLE_DIRECTED) { - /* Interval must be 0 in directed connectable mode. */ - _minInterval = 0; - _maxInterval = 0; - } else if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { - /* Min interval is slightly larger than in other modes. */ - ble::clamp(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); - ble::clamp(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, GAP_ADV_PARAMS_INTERVAL_MAX); - } else { - ble::clamp(_minInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); - ble::clamp(_maxInterval, GAP_ADV_PARAMS_INTERVAL_MIN, GAP_ADV_PARAMS_INTERVAL_MAX); + /* Min interval is slightly larger than in other modes. */ + if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { + _minInterval = adv_interval_t(std::max(_minInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); + _maxInterval = adv_interval_t(std::max(_maxInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); } - - /* Timeout checks. */ - if (timeout) { - /* Stay within timeout limits. */ - if (_timeout > GAP_ADV_PARAMS_TIMEOUT_MAX) { - _timeout = GAP_ADV_PARAMS_TIMEOUT_MAX; - } - } - - _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(_minInterval); - _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(_maxInterval); } public: - /** - * Number of microseconds in 0.625 milliseconds. - */ - static const uint16_t UNIT_0_625_MS = 625; - - /** - * Convert milliseconds to units of 0.625ms. - * - * @param[in] durationInMillis Number of milliseconds to convert. - * - * @return The value of @p durationInMillis in units of 0.625ms. - */ - static uint16_t MSEC_TO_ADVERTISEMENT_DURATION_UNITS(uint32_t durationInMillis) - { - return (durationInMillis * 1000) / UNIT_0_625_MS; - } - - /** - * Convert units of 0.625ms to milliseconds. - * - * @param[in] gapUnits The number of units of 0.625ms to convert. - * - * @return The value of @p gapUnits in milliseconds. - */ - static uint16_t ADVERTISEMENT_DURATION_UNITS_TO_MS(uint16_t gapUnits) - { - return (gapUnits * UNIT_0_625_MS) / 1000; - } - /** * Get the advertising type. * @@ -193,58 +114,6 @@ public: return _advType; } - /** - * Get the advertising interval in milliseconds. - * - * @return The advertisement interval (in milliseconds). - */ - uint32_t getMinInterval(void) const - { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); - } - - /** - * Get the advertisement interval in units of 0.625ms. - * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). - */ - uint32_t getMinIntervalInADVUnits(void) const - { - return _minInterval; - } - - /** - * Get the max advertising interval in milliseconds. - * - * @return The advertisement interval (in milliseconds). - */ - uint32_t getMaxInterval(void) const - { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); - } - - /** - * Get the max advertisement interval in units of 0.625ms. - * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). - */ - uint32_t getMaxIntervalInADVUnits(void) const - { - return _maxInterval; - } - - /** - * Get the advertising timeout. - * - * @return The advertising timeout (in seconds). - */ - uint16_t getTimeout(void) const - { - return _timeout; - } - /** * Update the advertising type. * @@ -256,26 +125,14 @@ public: } /** - * Update the advertising interval in milliseconds. + * Update the advertising interval. * - * @param[in] newMinInterval The new advertising interval in milliseconds. + * @param[in] newMinInterval The new advertising interval . */ - void setInterval(uint32_t newMinInterval, uint32_t newMaxInterval) + void setInterval(adv_interval_t newMinInterval, adv_interval_t newMaxInterval) { - _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newMinInterval); - _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(newMaxInterval); - } - - /** - * Update the advertising timeout. - * - * @param[in] newTimeout The new advertising timeout (in seconds). - * - * @note 0 is a special value meaning the advertising process never ends. - */ - void setTimeout(uint16_t newTimeout) - { - _timeout = newTimeout; + _minInterval = newMinInterval; + _maxInterval = newMaxInterval; } /** @@ -283,9 +140,8 @@ public: * * @param[in] newAdvType The new advertising type. */ - void setType( - ble::advertising_type_t newAdvType - ) { + void setType(ble::advertising_type_t newAdvType) + { _advType = newAdvType; } @@ -294,7 +150,8 @@ public: * * @return Advertising type. */ - ble::advertising_type_t getType() const { + ble::advertising_type_t getType() const + { return _advType; } @@ -302,7 +159,8 @@ public: * * @return True if advertising is anonymous. */ - bool getAnonymousAdvertising() const { + bool getAnonymousAdvertising() const + { return _anonymous; } @@ -310,42 +168,40 @@ public: * * @param enable Advertising anonymous if true. */ - void setAnonymousAdvertising( - bool enable - ) { + void setAnonymousAdvertising(bool enable) + { _anonymous = enable; } /** Get the advertising intervals on the primary channels. * - * @param min Minimum interval in milliseconds. - * @param max Maximum interval in milliseconds. - * - * @return Error if pointers are invalid. + * @param min Minimum interval. + * @param max Maximum interval. */ ble_error_t getPrimaryInterval( - uint32_t *min /* ms */, - uint32_t *max /* ms */ + adv_interval_t *min /* ms */, + adv_interval_t *max /* ms */ ) const { if (!min || !max) { return BLE_ERROR_INVALID_PARAM; } - *min = ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); - *max = ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); + + *min = _minInterval; + *max = _maxInterval; return BLE_ERROR_NONE; } /** Set the advertising intervals on the primary channels. * - * @param min Minimum interval in milliseconds. - * @param max Maximum interval in milliseconds. + * @param min Minimum interval . + * @param max Maximum interval . */ void setPrimaryInterval( - uint32_t min /* ms */, - uint32_t max /* ms */ + adv_interval_t min , + adv_interval_t max ) { - _minInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(min); - _maxInterval = MSEC_TO_ADVERTISEMENT_DURATION_UNITS(max); + _minInterval = min; + _maxInterval = max; } /** Get channels set for primary advertising. @@ -377,11 +233,8 @@ public: * @param channel38 Use channel 38. * @param channel39 Use channel 39. */ - void setPrimaryChannels( - bool channel37, - bool channel38, - bool channel39 - ) { + void setPrimaryChannels(bool channel37, bool channel38, bool channel39) + { if (!channel37 && !channel38 && !channel39) { channel37 = channel38 = channel39 = true; } @@ -394,15 +247,15 @@ public: * * @return Addres tpe used. */ - ble::own_address_type_t getOwnAddressType() const { + ble::own_address_type_t getOwnAddressType() const + { return _ownAddressType; } /** Get what type of address is to be used as your own address during advertising. */ - void setOwnAddressType( - ble::own_address_type_t addressType - ) { + void setOwnAddressType(ble::own_address_type_t addressType) + { _ownAddressType = addressType; } @@ -414,13 +267,13 @@ public: * @return Error if pointers are invalid. */ ble_error_t getPeer( - BLEProtocol::AddressBytes_t *address, + ble::address_t *address, ble::target_peer_address_type_t *addressType ) const { if (!address || !addressType) { return BLE_ERROR_INVALID_PARAM; } - memcpy(address, _peerAddress, sizeof(BLEProtocol::AddressBytes_t)); + *address = _peerAddress; *addressType = _peerAddressType; return BLE_ERROR_NONE; }; @@ -431,10 +284,10 @@ public: * @param addressType Peer's address type. */ void setPeer( - const BLEProtocol::AddressBytes_t address, + const address_t &address, ble::target_peer_address_type_t addressType ) { - memcpy(_peerAddress, address, sizeof(BLEProtocol::AddressBytes_t)); + _peerAddress = address; _peerAddressType = addressType; }; @@ -442,16 +295,16 @@ public: * * @return Policy used. */ - ble::advertising_policy_mode_t getPolicyMode() const { + ble::advertising_policy_mode_t getPolicyMode() const + { return _policy; } /** Set the policy of whitelist use during advertising; * * @param Policy to use. */ - void setPolicyMode( - ble::advertising_policy_mode_t mode - ) { + void setPolicyMode(ble::advertising_policy_mode_t mode) + { _policy = mode; } @@ -459,7 +312,8 @@ public: * * @return Advertising TX power. */ - int8_t getTxPower() const { + advertising_power_t getTxPower() const + { return _txPower; } @@ -467,9 +321,8 @@ public: * * @param txPower Advertising TX power. */ - void setTxPower( - int8_t txPower - ) { + void setTxPower(advertising_power_t txPower) + { _txPower = txPower; } @@ -479,10 +332,8 @@ public: * * @return Error if pointers are invalid. */ - ble_error_t getPhy( - ble::phy_t *primaryPhy, - ble::phy_t *secondaryPhy - ) const { + ble_error_t getPhy(ble::phy_t *primaryPhy, ble::phy_t *secondaryPhy) const + { if (!primaryPhy || !secondaryPhy) { return BLE_ERROR_INVALID_PARAM; } @@ -496,10 +347,8 @@ public: * @param primaryPhy Primary advertising channels PHY. * @param secondaryPhy Secondary advertising channels PHY. */ - void setPhy( - ble::phy_t primaryPhy, - ble::phy_t secondaryPhy - ) { + void setPhy(ble::phy_t primaryPhy, ble::phy_t secondaryPhy) + { _primaryPhy = primaryPhy; _secondaryPhy = secondaryPhy; } @@ -508,7 +357,8 @@ public: * * @return How many events can be skipped on the secondary channel. */ - uint8_t getSecondaryMaxSkip() const { + uint8_t getSecondaryMaxSkip() const + { return _maxSkip; } @@ -516,9 +366,8 @@ public: * * @param eventNumber Number of events that can be skipped. */ - void setSecondaryMaxSkip( - uint8_t eventNumber - ) { + void setSecondaryMaxSkip(uint8_t eventNumber) + { _maxSkip = eventNumber; } @@ -526,9 +375,8 @@ public: * * @param enable Enable callback if true. */ - void setScanRequestNotification( - bool enable = true - ) { + void setScanRequestNotification(bool enable = true) + { _notifyOnScan = enable; } @@ -536,7 +384,8 @@ public: * * @return True if callback is enabled. */ - bool getScanRequestNotification() const { + bool getScanRequestNotification() const + { return _notifyOnScan; } @@ -544,9 +393,8 @@ public: * * @param enable If true legacy PDU will be used. */ - void setUseLegacyPDU( - bool enable = true - ) { + void setUseLegacyPDU(bool enable = true) + { _legacyPDU = enable; } @@ -554,7 +402,8 @@ public: * * @return True legacy PDU will be used. */ - bool getUseLegacyPDU() const { + bool getUseLegacyPDU() const + { return _legacyPDU; } @@ -562,9 +411,8 @@ public: * * @param enable If true include the TX power in the header. */ - void includeTxPowerInHeader( - bool enable = true - ) { + void includeTxPowerInHeader(bool enable = true) + { _includeHeaderTxPower = enable; } @@ -572,49 +420,35 @@ public: * * @return True if TX power is included in the header. */ - bool getTxPowerInHeader() const { + bool getTxPowerInHeader() const + { return _includeHeaderTxPower; } - /** Get the minimum advertisement interval in units of 0.625ms. + /** Get the minimum advertisement interval. * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). + * @return The advertisement interval. */ - uint32_t getMinPrimaryIntervalInADVUnits() const { + adv_interval_t getMinPrimaryInterval() const + { return _minInterval; } - /** Get the maximum advertisement interval in units of 0.625ms. + /** Get the maximum advertisement interval. * - * @return The advertisement interval in advertisement duration units - * (0.625ms units). + * @return The advertisement interval. */ - uint32_t getMaxPrimaryIntervalInADVUnits() const { + adv_interval_t getMaxPrimaryInterval() const + { return _maxInterval; } - /** Get the minimum advertisement interval in milliseconds. - * - * @return The advertisement interval in milliseconds. - */ - uint32_t getMinPrimaryInterval() const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_minInterval); - } - - /** Get the maximum advertisement interval in milliseconds. - * - * @return The advertisement interval in milliseconds. - */ - uint32_t getMaxPrimaryInterval() const { - return ADVERTISEMENT_DURATION_UNITS_TO_MS(_maxInterval); - } - /** Peer address for directed advertising. * * @return Peer address. */ - const BLEProtocol::AddressBytes_t& getPeerAddress() const { + const address_t& getPeerAddress() const + { return _peerAddress; }; @@ -622,7 +456,8 @@ public: * * @return Peer address type. */ - ble::target_peer_address_type_t getPeerAddressType() const { + target_peer_address_type_t getPeerAddressType() const + { return _peerAddressType; }; @@ -630,7 +465,8 @@ public: * * @return PHY used for primary advertising. */ - ble::phy_t getPrimaryPhy() const { + ble::phy_t getPrimaryPhy() const + { return _primaryPhy; } @@ -638,7 +474,8 @@ public: * * @return PHY used for secondary advertising. */ - ble::phy_t getSecondaryPhy() const { + ble::phy_t getSecondaryPhy() const + { return _secondaryPhy; } @@ -646,7 +483,8 @@ public: * * @return True if channel used. */ - bool getChannel37() const { + bool getChannel37() const + { return _channel37; } @@ -655,7 +493,8 @@ public: * * @return True if channel used. */ - bool getChannel38() const { + bool getChannel38() const + { return _channel37; } @@ -664,24 +503,24 @@ public: * * @return True if channel used. */ - bool getChannel39() const { + bool getChannel39() const + { return _channel37; } private: - ble::advertising_type_t _advType; + advertising_type_t _advType; /* The advertising interval in ADV duration units (in other words, 0.625ms). */ - uint32_t _minInterval; + adv_interval_t _minInterval; /* The advertising max interval in ADV duration units (in other words, 0.625ms) used in extended advertising. */ - uint32_t _maxInterval; - /* The advertising timeout in ADV duration units (in other words, 0.625ms). */ - uint16_t _timeout; - ble::target_peer_address_type_t _peerAddressType; - ble::own_address_type_t _ownAddressType; - ble::advertising_policy_mode_t _policy; - ble::phy_t _primaryPhy; - ble::phy_t _secondaryPhy; - BLEProtocol::AddressBytes_t _peerAddress; + adv_interval_t _maxInterval; + + target_peer_address_type_t _peerAddressType; + own_address_type_t _ownAddressType; + advertising_policy_mode_t _policy; + phy_t _primaryPhy; + phy_t _secondaryPhy; + address_t _peerAddress; uint8_t _txPower; uint8_t _maxSkip; uint8_t _channel37:1; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 1d5e4f2922..28636310dc 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1752,8 +1752,8 @@ ble_error_t GenericGap::setAdvertisingParams( ); return _pal_gap.set_advertising_parameters( - params.getMinIntervalInADVUnits(), - params.getMaxIntervalInADVUnits(), + params.getMinPrimaryInterval().value(), + params.getMaxPrimaryInterval().value(), (pal::advertising_type_t::type) params.getType(), (pal::own_address_type_t::type) params.getOwnAddressType().value(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), @@ -1790,8 +1790,8 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( return _pal_gap.set_extended_advertising_parameters( handle, event_properties, - params.getMinPrimaryIntervalInADVUnits(), - params.getMaxPrimaryIntervalInADVUnits(), + params.getMinPrimaryInterval().value(), + params.getMaxPrimaryInterval().value(), channel_map, (pal::own_address_type_t::type) params.getOwnAddressType().value(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), From a043f49e7c64f3c09d80bd203c4eba8972d755e7 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 17:49:17 +0000 Subject: [PATCH 178/361] BLE: Use common ble::own_address_type_t in ble::ScanParameters. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index bf582e40ed..f6928db7b0 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -35,13 +35,6 @@ public: typedef ble::scan_window_t scan_window_t; typedef ble::scan_interval_t scan_interval_t; - enum own_address_type_t { - PUBLIC_ADDRESS = 0x00, - RANDOM_ADDRESS = 0x01, - PRIVATE_RESOLVABLE_PUBLIC_FALLBACK = 0x02, - PRIVATE_RESOLVABLE_RANDOM_FALLBACK = 0x03 - }; - struct phy_configuration_t { phy_configuration_t( scan_window_t scan_interval, @@ -62,7 +55,7 @@ public: }; ScanParameters() : - own_address_type(PUBLIC_ADDRESS), + own_address_type(own_address_type_t::PUBLIC), scanning_filter_policy(ble::SCAN_POLICY_IGNORE_WHITELIST), phys(ble::phy_set_t::PHY_SET_1M), phy_1m_configuration( From d659bc6561d9dcdb6095da65b5769a8d05bdc967 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 17:54:32 +0000 Subject: [PATCH 179/361] BLE: unwrap own_address_type value in GenericGap. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 28636310dc..80a03288d9 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2378,7 +2378,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) }; return _pal_gap.set_extended_scan_parameters( - (pal::own_address_type_t::type) params.get_own_address_type(), + (pal::own_address_type_t::type) params.get_own_address_type().value(), (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy(), params.get_scanning_phys(), active_scanning, @@ -2397,7 +2397,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) legacy_configuration.active_scanning, legacy_configuration.interval.value(), legacy_configuration.window.value(), - (pal::own_address_type_t::type) params.get_own_address_type(), + (pal::own_address_type_t::type) params.get_own_address_type().value(), (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy() ); } From 184533ab3e3a63ac65fc4af1b454ac90cc6e4e2a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 17:54:57 +0000 Subject: [PATCH 180/361] BLE: Fix second time base. --- features/FEATURE_BLE/ble/common/Duration.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 9b18c71932..ce4588ec1d 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -102,8 +102,8 @@ private: }; typedef Duration microsecond_t; -typedef Duration millisecond_t; -typedef Duration second_t; +typedef Duration millisecond_t; +typedef Duration second_t; template DurationOut durationCast(Duration duration) { From b34d09c47ec1f3011d2e68aabc7ec3cf3f5e7d35 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 14 Nov 2018 17:56:03 +0000 Subject: [PATCH 181/361] BLE: Fix AdvertisingParameters::getChannelXX functions. --- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index d5494ace63..8494c95b28 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -495,7 +495,7 @@ public: */ bool getChannel38() const { - return _channel37; + return _channel38; } @@ -505,7 +505,7 @@ public: */ bool getChannel39() const { - return _channel37; + return _channel39; } private: From a255a790a6f9fcc312607eb85844516f09cab630 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 09:15:02 +0000 Subject: [PATCH 182/361] BLE: Improve ble::AdvertisingParameters field declaration. --- .../FEATURE_BLE/ble/gap/AdvertisingParameters.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 8494c95b28..9f7ca86d39 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -521,15 +521,15 @@ private: phy_t _primaryPhy; phy_t _secondaryPhy; address_t _peerAddress; - uint8_t _txPower; + advertising_power_t _txPower; uint8_t _maxSkip; - uint8_t _channel37:1; - uint8_t _channel38:1; - uint8_t _channel39:1; - uint8_t _anonymous:1; - uint8_t _notifyOnScan:1; - uint8_t _legacyPDU:1; - uint8_t _includeHeaderTxPower:1; + bool _channel37:1; + bool _channel38:1; + bool _channel39:1; + bool _anonymous:1; + bool _notifyOnScan:1; + bool _legacyPDU:1; + bool _includeHeaderTxPower:1; }; } // namespace ble From 47c4784e310a4cf9e17ec2c392f7ecd1fae9635b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 09:54:00 +0000 Subject: [PATCH 183/361] BLE: Rework ble::AdvertisingParameters * Reorganize functions in logical order. * Add separation between legacy and extended advertising. * Update setter to return a reference to this. This allows chain of calls. * Remove getter that can fail due to bad user inputs. --- .../ble/gap/AdvertisingParameters.h | 613 ++++++++---------- 1 file changed, 277 insertions(+), 336 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 9f7ca86d39..737825b919 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -73,7 +73,7 @@ public: * @note If value in input are out of range, they will be normalized. */ AdvertisingParameters( - ble::advertising_type_t advType = ble::ADV_CONNECTABLE_UNDIRECTED, + ble::advertising_type_t advType = ADV_CONNECTABLE_UNDIRECTED, adv_interval_t minInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MIN), adv_interval_t maxInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MAX) ) : @@ -88,61 +88,34 @@ public: _peerAddress(), _txPower(127), _maxSkip(0), - _channel37(1), - _channel38(1), - _channel39(1), - _anonymous(0), - _notifyOnScan(0), - _legacyPDU(1), - _includeHeaderTxPower(0) + _channel37(true), + _channel38(true), + _channel39(true), + _anonymous(false), + _notifyOnScan(false), + _legacyPDU(true), + _includeHeaderTxPower(false) { /* Min interval is slightly larger than in other modes. */ - if (_advType == ble::ADV_NON_CONNECTABLE_UNDIRECTED) { + if (_advType == ADV_NON_CONNECTABLE_UNDIRECTED) { _minInterval = adv_interval_t(std::max(_minInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); _maxInterval = adv_interval_t(std::max(_maxInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); } } public: - /** - * Get the advertising type. - * - * @return The advertising type. - */ - ble::advertising_type_t getAdvertisingType(void) const - { - return _advType; - } /** * Update the advertising type. * * @param[in] newAdvType The new advertising type. + * + * @return reference to this object. */ - void setAdvertisingType(ble::advertising_type_t newAdvType) - { - _advType = newAdvType; - } - - /** - * Update the advertising interval. - * - * @param[in] newMinInterval The new advertising interval . - */ - void setInterval(adv_interval_t newMinInterval, adv_interval_t newMaxInterval) - { - _minInterval = newMinInterval; - _maxInterval = newMaxInterval; - } - - /** - * Update the advertising type. - * - * @param[in] newAdvType The new advertising type. - */ - void setType(ble::advertising_type_t newAdvType) + AdvertisingParameters &setType(advertising_type_t newAdvType) { _advType = newAdvType; + return *this; } /** @@ -150,80 +123,43 @@ public: * * @return Advertising type. */ - ble::advertising_type_t getType() const + advertising_type_t getType() const { return _advType; } - /** Check if advertising is anonymous. - * - * @return True if advertising is anonymous. - */ - bool getAnonymousAdvertising() const - { - return _anonymous; - } - - /** Advertise without your own address. - * - * @param enable Advertising anonymous if true. - */ - void setAnonymousAdvertising(bool enable) - { - _anonymous = enable; - } - - /** Get the advertising intervals on the primary channels. - * - * @param min Minimum interval. - * @param max Maximum interval. - */ - ble_error_t getPrimaryInterval( - adv_interval_t *min /* ms */, - adv_interval_t *max /* ms */ - ) const { - if (!min || !max) { - return BLE_ERROR_INVALID_PARAM; - } - - *min = _minInterval; - *max = _maxInterval; - return BLE_ERROR_NONE; - } - /** Set the advertising intervals on the primary channels. * * @param min Minimum interval . * @param max Maximum interval . + * + * @return reference to this object. */ - void setPrimaryInterval( - adv_interval_t min , - adv_interval_t max - ) { + AdvertisingParameters& setPrimaryInterval( + adv_interval_t min , adv_interval_t max + ) + { _minInterval = min; _maxInterval = max; + return *this; } - /** Get channels set for primary advertising. + /** Get the minimum advertising intervals on the primary channels. * - * @param channel37 Use channel 37. - * @param channel38 Use channel 38. - * @param channel39 Use channel 39. - * - * @return Error if pointers are invalid. + * @return The lower bound of the primary interval selected. */ - ble_error_t getPrimaryChannels( - bool *channel37, - bool *channel38, - bool *channel39 - ) const { - if (!channel37 || !channel38 || !channel39) { - return BLE_ERROR_INVALID_PARAM; - } - *channel37 = _channel37; - *channel38 = _channel38; - *channel39 = _channel39; - return BLE_ERROR_NONE; + adv_interval_t getMinPrimaryInterval() const + { + return _minInterval; + } + + /** Get the maximum advertising intervals on the primary channels. + * + * @return The higher bound of the primary interval selected. + */ + adv_interval_t getMaxPrimaryInterval() const + { + return _maxInterval; } /** Set which channels are to be used for primary advertising. @@ -232,8 +168,12 @@ public: * @param channel37 Use channel 37. * @param channel38 Use channel 38. * @param channel39 Use channel 39. + * + * @return a reference to this object. */ - void setPrimaryChannels(bool channel37, bool channel38, bool channel39) + AdvertisingParameters &setPrimaryChannels( + bool channel37, bool channel38, bool channel39 + ) { if (!channel37 && !channel38 && !channel39) { channel37 = channel38 = channel39 = true; @@ -241,242 +181,7 @@ public: _channel37 = channel37; _channel38 = channel38; _channel39 = channel39; - } - - /** Get what type of address is to be used as your own address during advertising. - * - * @return Addres tpe used. - */ - ble::own_address_type_t getOwnAddressType() const - { - return _ownAddressType; - } - - /** Get what type of address is to be used as your own address during advertising. - */ - void setOwnAddressType(ble::own_address_type_t addressType) - { - _ownAddressType = addressType; - } - - /** Get peer address and type used during directed advertising. - * - * @param address Address that will have the peer address written to. - * @param addressType Pointer to type which will have the address type written to. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPeer( - ble::address_t *address, - ble::target_peer_address_type_t *addressType - ) const { - if (!address || !addressType) { - return BLE_ERROR_INVALID_PARAM; - } - *address = _peerAddress; - *addressType = _peerAddressType; - return BLE_ERROR_NONE; - }; - - /** Set peer address and type used during directed advertising. - * - * @param address Peer's address bytes. - * @param addressType Peer's address type. - */ - void setPeer( - const address_t &address, - ble::target_peer_address_type_t addressType - ) { - _peerAddress = address; - _peerAddressType = addressType; - }; - - /** Get the policy of whitelist use during advertising; - * - * @return Policy used. - */ - ble::advertising_policy_mode_t getPolicyMode() const - { - return _policy; - } - /** Set the policy of whitelist use during advertising; - * - * @param Policy to use. - */ - void setPolicyMode(ble::advertising_policy_mode_t mode) - { - _policy = mode; - } - - /** Get the advertising TX power. - * - * @return Advertising TX power. - */ - advertising_power_t getTxPower() const - { - return _txPower; - } - - /** Set the advertising TX power. - * - * @param txPower Advertising TX power. - */ - void setTxPower(advertising_power_t txPower) - { - _txPower = txPower; - } - - /** Get PHYs used on primary and secondary advertising channels. - * - * @param primaryPhy,secondaryPhy Pointer where the result is written to. - * - * @return Error if pointers are invalid. - */ - ble_error_t getPhy(ble::phy_t *primaryPhy, ble::phy_t *secondaryPhy) const - { - if (!primaryPhy || !secondaryPhy) { - return BLE_ERROR_INVALID_PARAM; - } - *primaryPhy = _primaryPhy; - *secondaryPhy = _secondaryPhy; - return BLE_ERROR_NONE; - } - - /** Get PHYs used on primary and secondary advertising channels. - * - * @param primaryPhy Primary advertising channels PHY. - * @param secondaryPhy Secondary advertising channels PHY. - */ - void setPhy(ble::phy_t primaryPhy, ble::phy_t secondaryPhy) - { - _primaryPhy = primaryPhy; - _secondaryPhy = secondaryPhy; - } - - /** Return how many events can be skipped on the secondary channel. - * - * @return How many events can be skipped on the secondary channel. - */ - uint8_t getSecondaryMaxSkip() const - { - return _maxSkip; - } - - /** Set how many events can be skipped on the secondary channel. - * - * @param eventNumber Number of events that can be skipped. - */ - void setSecondaryMaxSkip(uint8_t eventNumber) - { - _maxSkip = eventNumber; - } - - /** Enabled or disable the callback that notifies the user about a scan request. - * - * @param enable Enable callback if true. - */ - void setScanRequestNotification(bool enable = true) - { - _notifyOnScan = enable; - } - - /** Return of the callback for scan request is enabled. - * - * @return True if callback is enabled. - */ - bool getScanRequestNotification() const - { - return _notifyOnScan; - } - - /** Use legacy PDU during advertising. - * - * @param enable If true legacy PDU will be used. - */ - void setUseLegacyPDU(bool enable = true) - { - _legacyPDU = enable; - } - - /** Check if legacy PDU is used during advertising. - * - * @return True legacy PDU will be used. - */ - bool getUseLegacyPDU() const - { - return _legacyPDU; - } - - /** Set if TX power should be included in the header. - * - * @param enable If true include the TX power in the header. - */ - void includeTxPowerInHeader(bool enable = true) - { - _includeHeaderTxPower = enable; - } - - /** Check if TX power should be included in the header. - * - * @return True if TX power is included in the header. - */ - bool getTxPowerInHeader() const - { - return _includeHeaderTxPower; - } - - /** Get the minimum advertisement interval. - * - * @return The advertisement interval. - */ - adv_interval_t getMinPrimaryInterval() const - { - return _minInterval; - } - - /** Get the maximum advertisement interval. - * - * @return The advertisement interval. - */ - adv_interval_t getMaxPrimaryInterval() const - { - return _maxInterval; - } - - /** Peer address for directed advertising. - * - * @return Peer address. - */ - const address_t& getPeerAddress() const - { - return _peerAddress; - }; - - /** Peer address type for directed advertising. - * - * @return Peer address type. - */ - target_peer_address_type_t getPeerAddressType() const - { - return _peerAddressType; - }; - - /** Get PHY used for primary advertising. - * - * @return PHY used for primary advertising. - */ - ble::phy_t getPrimaryPhy() const - { - return _primaryPhy; - } - - /** Get PHY used for secondary advertising. - * - * @return PHY used for secondary advertising. - */ - ble::phy_t getSecondaryPhy() const - { - return _secondaryPhy; + return *this; } /** Check if channel 37 is used for primary advertising. @@ -508,6 +213,242 @@ public: return _channel39; } + /** Get what type of address is to be used as your own address during advertising. + * + * @return a reference to this object. + */ + AdvertisingParameters &setOwnAddressType(own_address_type_t addressType) + { + _ownAddressType = addressType; + return *this; + } + + /** Get what type of address is to be used as your own address during advertising. + * + * @return Addres tpe used. + */ + own_address_type_t getOwnAddressType() const + { + return _ownAddressType; + } + + /** Set peer address and type used during directed advertising. + * + * @param address Peer's address bytes. + * @param addressType Peer's address type. + * + * @return a reference to this object. + */ + AdvertisingParameters &setPeer( + const address_t &address, + target_peer_address_type_t addressType + ) { + _peerAddress = address; + _peerAddressType = addressType; + return *this; + }; + + /** Get the peer address used during directed advertising. + * + * @return Address of the peer targeted by directed advertising. + */ + const address_t &getPeerAddress() const + { + return _peerAddress; + }; + + + /** Get the peer address type used during directed advertising. + * + * @return The type of address of the peer targeted by directed advertising. + */ + target_peer_address_type_t getPeerAddressType() const + { + return _peerAddressType; + }; + + /** Set the policy of whitelist use during advertising; + * + * @param Policy to use. + * + * @return A reference to this object. + */ + AdvertisingParameters &setPolicyMode(advertising_policy_mode_t mode) + { + _policy = mode; + return *this; + } + + /** Get the policy of whitelist use during advertising; + * + * @return Policy used. + */ + ble::advertising_policy_mode_t getPolicyMode() const + { + return _policy; + } + + /* Extended advertising parameters */ + + + /** Get PHYs used on primary and secondary advertising channels. + * + * @param primaryPhy Primary advertising channels PHY. + * @param secondaryPhy Secondary advertising channels PHY. + * + * @return A reference to this. + */ + AdvertisingParameters &setPhy(ble::phy_t primaryPhy, ble::phy_t secondaryPhy) + { + _primaryPhy = primaryPhy; + _secondaryPhy = secondaryPhy; + return *this; + } + + /** Get PHY used for primary advertising. + * + * @return PHY used for primary advertising. + */ + ble::phy_t getPrimaryPhy() const + { + return _primaryPhy; + } + + /** Get PHY used for secondary advertising. + * + * @return PHY used for secondary advertising. + */ + ble::phy_t getSecondaryPhy() const + { + return _secondaryPhy; + } + + /** Set the advertising TX power. + * + * @param txPower Advertising TX power. + * + * @return A reference to this object. + */ + AdvertisingParameters &setTxPower(advertising_power_t txPower) + { + _txPower = txPower; + return *this; + } + + /** Get the advertising TX power. + * + * @return Advertising TX power. + */ + advertising_power_t getTxPower() const + { + return _txPower; + } + + /** Set how many events can be skipped on the secondary channel. + * + * @param eventNumber Number of events that can be skipped. + * + * @return A reference to this object. + */ + AdvertisingParameters &setSecondaryMaxSkip(uint8_t eventNumber) + { + _maxSkip = eventNumber; + return *this; + } + + /** Return how many events can be skipped on the secondary channel. + * + * @return How many events can be skipped on the secondary channel. + */ + uint8_t getSecondaryMaxSkip() const + { + return _maxSkip; + } + + /** Enabled or disable the callback that notifies the user about a scan request. + * + * @param enable Enable callback if true. + * + * @return A reference to this object. + */ + AdvertisingParameters &setScanRequestNotification(bool enable = true) + { + _notifyOnScan = enable; + return *this; + } + + /** Return of the callback for scan request is enabled. + * + * @return True if callback is enabled. + */ + bool getScanRequestNotification() const + { + return _notifyOnScan; + } + + /** Use legacy PDU during advertising. + * + * @param enable If true legacy PDU will be used. + * + * @return A reference to this object. + */ + AdvertisingParameters &setUseLegacyPDU(bool enable = true) + { + _legacyPDU = enable; + return *this; + } + + /** Check if legacy PDU is used during advertising. + * + * @return True legacy PDU will be used. + */ + bool getUseLegacyPDU() const + { + return _legacyPDU; + } + + /** Set if TX power should be included in the header. + * + * @param enable If true include the TX power in the header. + * + * @return A reference to this object. + */ + AdvertisingParameters &includeTxPowerInHeader(bool enable = true) + { + _includeHeaderTxPower = enable; + return *this; + } + + /** Check if TX power should be included in the header. + * + * @return True if TX power is included in the header. + */ + bool getTxPowerInHeader() const + { + return _includeHeaderTxPower; + } + + /** Advertise without your own address. + * + * @param enable Advertising anonymous if true. + * + * @return reference to this object. + */ + AdvertisingParameters &setAnonymousAdvertising(bool enable) + { + _anonymous = enable; + return *this; + } + + /** Check if advertising is anonymous. + * + * @return True if advertising is anonymous. + */ + bool getAnonymousAdvertising() const + { + return _anonymous; + } + private: advertising_type_t _advType; /* The advertising interval in ADV duration units (in other words, 0.625ms). */ From 2477d0e385ddd382da2e3bfca28ee4f5812bf151 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 09:54:58 +0000 Subject: [PATCH 184/361] BLE: Fix missing initialization in ble::phy_set_t. --- features/FEATURE_BLE/ble/BLETypes.h | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 6d60bc8d9f..e17d0a5723 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -1021,11 +1021,9 @@ public: * @param phy_2m Prefer LE 2M if avaiable * @param phy_coded Prefer coded modulation if avaiable */ - phy_set_t( - bool phy_1m, - bool phy_2m, - bool phy_coded - ) { + phy_set_t(bool phy_1m, bool phy_2m, bool phy_coded) : + _value() + { set_1m(phy_1m); set_2m(phy_2m); set_coded(phy_coded); From 823825ee24b18462410a6ba8302efb0d5bef53f9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 09:55:33 +0000 Subject: [PATCH 185/361] BLE: Fix ternary expression return type. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 80a03288d9..a6b58773e5 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2235,7 +2235,9 @@ void GenericGap::on_extended_advertising_report( _eventHandler->onAdvertisingReport( AdvertisingReportEvent( event_type, - (PeerAddressType_t::type)(address_type ? address_type->value() : PeerAddressType_t::ANONYMOUS), + address_type ? + (peer_address_type_t::type) address_type->value() : + peer_address_type_t::ANONYMOUS, (BLEProtocol::AddressBytes_t&)address, primary_phy, secondary_phy? *secondary_phy : phy_t::NONE, From b4fe04adddd9c3f053390e23d4439f7a47e16521 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 10:04:32 +0000 Subject: [PATCH 186/361] BLE: Improve readability of AdvertisingDataBuilder::appendField --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index d81166a41e..33ce2ac048 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -556,15 +556,15 @@ private: } /* Field length. */ - memset(_buffer.data() + _payloadLen, fieldData.size() + 1, 1); - _payloadLen++; + _buffer[_payloadLen] = fieldData.size() + 1; + ++_payloadLen; /* Field ID. */ - memset(_buffer.data() + _payloadLen, advDataType.value(), 1); - _payloadLen++; + _buffer[_payloadLen] = advDataType.value(); + ++_payloadLen; /* Payload. */ - memcpy(_buffer.data() + _payloadLen, fieldData.data(), fieldData.size()); + memcpy(&_buffer[_payloadLen], fieldData.data(), fieldData.size()); _payloadLen += fieldData.size(); return BLE_ERROR_NONE; From b8db58fe57d7102cadae71789b1b9a99c4338d96 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 10:39:41 +0000 Subject: [PATCH 187/361] BLE: Move new gap types in ble/gap/Types.h --- features/FEATURE_BLE/ble/BLETypes.h | 454 +------------------------ features/FEATURE_BLE/ble/gap/Types.h | 474 +++++++++++++++++++++++++++ 2 files changed, 476 insertions(+), 452 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/Types.h diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index e17d0a5723..35c7f13ae7 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -22,8 +22,7 @@ #include #include "ble/SafeEnum.h" #include "ble/ArrayView.h" -#include "ble/common/Duration.h" -#include "ble/common/Bounded.h" +#include "ble/gap/Types.h" /** * @addtogroup ble @@ -44,24 +43,6 @@ void clamp(T& value, const R& min, const R& max) { } } -/* BLE units, using microseconds as the common denominator */ -typedef Duration > adv_interval_t; -typedef Duration > adv_duration_t; -typedef Duration > scan_duration_t; -typedef Duration > scan_period_t; -typedef Duration > scan_interval_t; -typedef Duration > scan_window_t; -typedef Duration > conn_interval_t; -typedef Duration > supervision_timeout_t; -typedef Duration > conn_event_length_t; -typedef Duration > sync_timeout_t; -typedef Duration > periodic_interval_t; - -typedef Duration ms_t; -typedef Duration us_t; - -typedef Bounded slave_latency_t; - /** Features supported by the controller. * @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 6, Part B - 4.6 */ struct controller_supported_features_t : SafeEnum { @@ -87,7 +68,7 @@ struct controller_supported_features_t : SafeEnum(value) { } + controller_supported_features_t(type value) : SafeEnum(value) { } }; /** @@ -106,20 +87,6 @@ typedef uintptr_t connection_handle_t; */ typedef uint16_t attribute_handle_t; -/** - * Handle of an advertising set. - * - * @note Range of valid handle is comprised between 0x00 and 0xEF. - */ -typedef uint8_t advertising_handle_t; - -/** - * Handle of a sync representing a periodic advertiser. - * - * @note Range of valid handle is comprised between 0x0000 and 0xFFFF. - */ -typedef uint16_t periodic_sync_handle_t; - /** * Inclusive range of GATT attributes handles. * @@ -191,262 +158,6 @@ static inline attribute_handle_range_t attribute_handle_range( return result; } -/** - * Encapsulates the peripheral advertising modes. - * - * It determine how the device appears to other scanner and peripheral - * devices in the scanning range. - */ -enum advertising_type_t { - /** - * Device is connectable, scannable and doesn't expect connection from a - * specific peer. - * - * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. - */ - ADV_CONNECTABLE_UNDIRECTED, - - /** - * Device is connectable and expects connection from a specific peer. - * (3.75 ms or smaller Advertising Interval) - * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. - */ - ADV_CONNECTABLE_DIRECTED, - - /** - * Device is scannable but not connectable. - * - * @see Vol 6, Part B, Section 2.3.1.4. - */ - ADV_SCANNABLE_UNDIRECTED, - - /** - * Device is not connectable and not scannable. - * - * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. - */ - ADV_NON_CONNECTABLE_UNDIRECTED, - - /** - * Device is connectable and expects connection from a specific peer (sent at long user set intervals). - */ - ADV_CONNECTABLE_DIRECTED_LOW_DUTY -}; - -/** Used to indicate if the packet is complete and if it's truncated. - */ -struct advertising_data_status_t : SafeEnum{ - enum type { - COMPLETE = 0x00, /**< Advertising payload complete. */ - INCOMPLETE_MORE_DATA = 0x01, /**< Partial advertising payload, more to come. */ - INCOMPLETE_DATA_TRUNCATED = 0x02 /**< Advertising payload incomplete and no more is comoing. */ - }; - - /** - * Construct a new advertising_data_status_t value. - */ - advertising_data_status_t(type value) : - SafeEnum(value) { } - - /** - * Explicit constructor from a raw value. - */ - explicit advertising_data_status_t(uint8_t raw_value) : - SafeEnum( - static_cast(raw_value) - ) - { } -}; - -/** Properties of an advertising event. - */ -struct advertising_event_t { - /** Create based on a raw value. - * - * @param value - */ - explicit advertising_event_t(uint8_t value) : value(value) { } - - /** Is advertising connectable. - * - * @return True if connectable. - */ - bool connectable() const - { - return static_cast(value & (1 << 0)); - } - - /** Is advertising scannable. - * - * @return True if scannable - */ - bool scannable_advertising() const - { - return static_cast(value & (1 << 1)); - } - - /** Is advertising directed. - * - * @return True if directed. - */ - bool directed_advertising() const - { - return static_cast(value & (1 << 2)); - } - - /** Is this a scan response. - * - * @return True if scan response. - */ - bool scan_response() const - { - return static_cast(value & (1 << 3)); - } - - /** Is this legacy advertising. - * - * @return True if legacy. - */ - bool legacy_advertising() const - { - return static_cast(value & (1 << 4)); - } - - /** Payload completeness status. - * - * @return @see advertising_data_status_t for details. - */ - advertising_data_status_t data_status() const - { - return static_cast((value >> 5) & 0x03); - } - - /** Is payload complete. - * - * @return True if payload is coplete. - */ - bool complete() const - { - return data_status().value() == advertising_data_status_t::COMPLETE; - } - - /** Is there more data coming. - * - * @return True if more data coming. - */ - bool more_data_to_come() const - { - return data_status().value() == advertising_data_status_t::INCOMPLETE_MORE_DATA; - } - - /** Is the payload truncated. - * - * @return True if no more data coming. - */ - bool truncated() const - { - return data_status().value() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; - } - -private: - uint8_t value; -}; - -/** - * Identify an advertising SID. Range: [0x00, 0x0F] - */ -typedef uint8_t advertising_sid_t; - -/** Received signal strength. Range <-127, 20>. - * @note Special value 127 means RSSI is not available. */ -typedef int8_t rssi_t; - -/** - * Describe the advertising power. - * - * Value comprised between -127 and +126 are considered power values in dBm while - * the special value 127 can be used as a wildcard to indicates that the host - * has no preference or if the power information is not available. - */ -typedef int8_t advertising_power_t; - -/** - * Advertising policy filter modes. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. - */ -enum advertising_policy_mode_t { - /** - * The whitelist is not used to filter peer request during advertising. - */ - ADV_POLICY_IGNORE_WHITELIST = 0, - - /** - * The whitelist is used to filter peer scan requests. - */ - ADV_POLICY_FILTER_SCAN_REQS = 1, - - /** - * The whitelist is used to filter peer connection requests. - */ - ADV_POLICY_FILTER_CONN_REQS = 2, - - /** - * The whitelist is used to filter peer scan and connection requests. - */ - ADV_POLICY_FILTER_ALL_REQS = 3, -}; - -/** - * Scanning policy filter mode. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. - */ -enum scanning_policy_mode_t { - /** - * The whitelist is not used for scanning operations. - */ - SCAN_POLICY_IGNORE_WHITELIST = 0, - - /** - * The whitelist is used to filter incoming advertising. - */ - SCAN_POLICY_FILTER_ALL_ADV = 1, - - /** - * Accept all advertising packets except directed advertising packets - * where the initiator's identity address does not address this device. - * - * @note Directed advertising packets where the initiator's address is a - * resolvable private address that cannot be resolved are also accepted. - */ - SCAN_POLICY_IGNORE_WHITELIST_INCLUDE_UNRESOLVABLE = 2, - - /** - * Accept all advertising packets except: - * - advertising packets where the advertiser's - * identity address is not in the White List, - * - directed advertising packets where the initiator's identity address - * does not address this device. - * - * @note Directed advertising packets where the initiator's address is a - * resolvable private address that cannot be resolved are also accepted. - */ - SCAN_POLICY_FILTER_ALL_ADV_INCLUDE_UNRESOLVABLE = 3 -}; - -/** - * Scanning policy filter mode. - * - * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. - */ -enum scanning_filter_duplicates_t { - SCAN_FILTER_DUPLICATES_DISABLED = 0, /**< Do not remove duplicate reports. */ - SCAN_FILTER_DUPLICATES_ENABLED = 1, /**< Remove duplicate reports. */ - SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 /**< Remove reports which are duplicate - within a single period. */ -}; - /** * Type that describes link's encryption state. */ @@ -904,20 +615,6 @@ struct peer_address_type_t :SafeEnum { SafeEnum(PUBLIC) { } }; -struct own_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address. */ - RANDOM, /**< Random Device Address. */ - RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use the public address. */ - RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use previously set random address. */ - }; - own_address_type_t(type value) : ble::SafeEnum(value) { } -}; - struct target_peer_address_type_t : ble::SafeEnum { enum type { PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ @@ -1113,153 +810,6 @@ struct coded_symbol_per_bit_t :SafeEnum { SafeEnum(value) { } }; -/** - * Accuracy of the master clock. - */ -struct clock_accuracy_t : SafeEnum{ - enum type { - /** - * 500 PPM - */ - PPM_500 = 0x00, - - /** - * 250 PPM - */ - PPM_250 = 0x01, - - /** - * 150 PPM - */ - PPM_150 = 0x02, - - /** - * 100 PPM - */ - PPM_100 = 0x03, - - /** - * 75 PPM - */ - PPM_75 = 0x04, - - /** - * 50 PPM - */ - PPM_50 = 0x05, - - /** - * 30 PPM - */ - PPM_30 = 0x06, - - /** - * 20 PPM - */ - PPM_20 = 0x07 - }; - - /** Get clock accuracy. - * - * @return Parts per million as a number. - */ - uint16_t get_ppm() { - uint16_t ppm = 0; - - switch(value()) { - case PPM_500: - ppm = 500; - break; - case PPM_250: - ppm = 250; - break; - case PPM_150: - ppm = 150; - break; - case PPM_100: - ppm = 100; - break; - case PPM_75: - ppm = 75; - break; - case PPM_50: - ppm = 50; - break; - case PPM_30: - ppm = 30; - break; - case PPM_20: - ppm = 20; - break; - } - - return ppm; - } - - /** - * Construct a new clock_accuracy_t value. - */ - clock_accuracy_t(type value) : SafeEnum(value) { } - - explicit clock_accuracy_t(uint8_t raw_value) : - SafeEnum(static_cast(raw_value)) { } -}; - -/** - * Enumeration of GAP roles. - * - * @note The BLE API does not express the broadcaster and scanner roles. - * - * @attention A device can fulfill different roles concurrently. - */ -struct connection_role_t :SafeEnum { - /** struct scoped enum wrapped by the class */ - enum type { - /** - * Central Role. - * - * The device can scan and initiate connection to peripherals. It - * acts as the master when a connection is established. - * - * @note A central is a scanner. - */ - CENTRAL = 0x00, - - /** - * @see CENTRAL - */ - MASTER = 0x00, - - /** - * Peripheral Role. - * - * The device can advertise and it can be connected by a central. It - * acts as a slave when connected. - * - * @note A peripheral is a broadcaster. - */ - PERIPHERAL = 0x01, - - /** - * @see SLAVE - */ - SLAVE = 0x01 - }; - - /** - * Construct a new instance of role_t. - */ - connection_role_t(type value) : - SafeEnum(value) { } - - /** - * Explicit constructor from a raw value. - * @param raw_value The role. - */ - explicit connection_role_t(uint8_t raw_value) : - SafeEnum(raw_value) { } -}; - } // namespace ble /** diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h new file mode 100644 index 0000000000..05ed75ddf0 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -0,0 +1,474 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAP_TYPES_H +#define BLE_GAP_TYPES_H + +#include "ble/common/Duration.h" +#include "ble/common/Bounded.h" +#include "ble/SafeEnum.h" + +namespace ble { + +/* BLE units, using microseconds as the common denominator */ +typedef Duration > adv_interval_t; +typedef Duration > adv_duration_t; +typedef Duration > scan_duration_t; +typedef Duration > scan_period_t; +typedef Duration > scan_interval_t; +typedef Duration > scan_window_t; +typedef Duration > conn_interval_t; +typedef Duration > supervision_timeout_t; +typedef Duration > conn_event_length_t; +typedef Duration > sync_timeout_t; +typedef Duration > periodic_interval_t; + +typedef Bounded slave_latency_t; + +/** + * Handle of an advertising set. + * + * @note Range of valid handle is comprised between 0x00 and 0xEF. + */ +typedef uint8_t advertising_handle_t; + +/** + * Handle of a sync representing a periodic advertiser. + * + * @note Range of valid handle is comprised between 0x0000 and 0xFFFF. + */ +typedef uint16_t periodic_sync_handle_t; + +/** + * Encapsulates the peripheral advertising modes. + * + * It determine how the device appears to other scanner and peripheral + * devices in the scanning range. + */ +enum advertising_type_t { + /** + * Device is connectable, scannable and doesn't expect connection from a + * specific peer. + * + * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. + */ + ADV_CONNECTABLE_UNDIRECTED, + + /** + * Device is connectable and expects connection from a specific peer. + * (3.75 ms or smaller Advertising Interval) + * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. + */ + ADV_CONNECTABLE_DIRECTED, + + /** + * Device is scannable but not connectable. + * + * @see Vol 6, Part B, Section 2.3.1.4. + */ + ADV_SCANNABLE_UNDIRECTED, + + /** + * Device is not connectable and not scannable. + * + * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. + */ + ADV_NON_CONNECTABLE_UNDIRECTED, + + /** + * Device is connectable and expects connection from a specific peer (sent at long user set intervals). + */ + ADV_CONNECTABLE_DIRECTED_LOW_DUTY +}; + +/** Used to indicate if the packet is complete and if it's truncated. + */ +struct advertising_data_status_t : SafeEnum{ + enum type { + COMPLETE = 0x00, /**< Advertising payload complete. */ + INCOMPLETE_MORE_DATA = 0x01, /**< Partial advertising payload, more to come. */ + INCOMPLETE_DATA_TRUNCATED = 0x02 /**< Advertising payload incomplete and no more is comoing. */ + }; + + /** + * Construct a new advertising_data_status_t value. + */ + advertising_data_status_t(type value) : + SafeEnum(value) { } + + /** + * Explicit constructor from a raw value. + */ + explicit advertising_data_status_t(uint8_t raw_value) : + SafeEnum( + static_cast(raw_value) + ) + { } +}; + +/** Properties of an advertising event. + */ +struct advertising_event_t { + /** Create based on a raw value. + * + * @param value + */ + explicit advertising_event_t(uint8_t value) : value(value) { } + + /** Is advertising connectable. + * + * @return True if connectable. + */ + bool connectable() const + { + return static_cast(value & (1 << 0)); + } + + /** Is advertising scannable. + * + * @return True if scannable + */ + bool scannable_advertising() const + { + return static_cast(value & (1 << 1)); + } + + /** Is advertising directed. + * + * @return True if directed. + */ + bool directed_advertising() const + { + return static_cast(value & (1 << 2)); + } + + /** Is this a scan response. + * + * @return True if scan response. + */ + bool scan_response() const + { + return static_cast(value & (1 << 3)); + } + + /** Is this legacy advertising. + * + * @return True if legacy. + */ + bool legacy_advertising() const + { + return static_cast(value & (1 << 4)); + } + + /** Payload completeness status. + * + * @return @see advertising_data_status_t for details. + */ + advertising_data_status_t data_status() const + { + return static_cast((value >> 5) & 0x03); + } + + /** Is payload complete. + * + * @return True if payload is coplete. + */ + bool complete() const + { + return data_status().value() == advertising_data_status_t::COMPLETE; + } + + /** Is there more data coming. + * + * @return True if more data coming. + */ + bool more_data_to_come() const + { + return data_status().value() == advertising_data_status_t::INCOMPLETE_MORE_DATA; + } + + /** Is the payload truncated. + * + * @return True if no more data coming. + */ + bool truncated() const + { + return data_status().value() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; + } + +private: + uint8_t value; +}; + +/** + * Identify an advertising SID. Range: [0x00, 0x0F] + */ +typedef uint8_t advertising_sid_t; + +/** Received signal strength. Range <-127, 20>. + * @note Special value 127 means RSSI is not available. */ +typedef int8_t rssi_t; + +/** + * Describe the advertising power. + * + * Value comprised between -127 and +126 are considered power values in dBm while + * the special value 127 can be used as a wildcard to indicates that the host + * has no preference or if the power information is not available. + */ +typedef int8_t advertising_power_t; + +/** + * Advertising policy filter modes. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. + */ +enum advertising_policy_mode_t { + /** + * The whitelist is not used to filter peer request during advertising. + */ + ADV_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter peer scan requests. + */ + ADV_POLICY_FILTER_SCAN_REQS = 1, + + /** + * The whitelist is used to filter peer connection requests. + */ + ADV_POLICY_FILTER_CONN_REQS = 2, + + /** + * The whitelist is used to filter peer scan and connection requests. + */ + ADV_POLICY_FILTER_ALL_REQS = 3, +}; + +/** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ +enum scanning_policy_mode_t { + /** + * The whitelist is not used for scanning operations. + */ + SCAN_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter incoming advertising. + */ + SCAN_POLICY_FILTER_ALL_ADV = 1, + + /** + * Accept all advertising packets except directed advertising packets + * where the initiator's identity address does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + SCAN_POLICY_IGNORE_WHITELIST_INCLUDE_UNRESOLVABLE = 2, + + /** + * Accept all advertising packets except: + * - advertising packets where the advertiser's + * identity address is not in the White List, + * - directed advertising packets where the initiator's identity address + * does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + SCAN_POLICY_FILTER_ALL_ADV_INCLUDE_UNRESOLVABLE = 3 +}; + +/** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ +enum scanning_filter_duplicates_t { + SCAN_FILTER_DUPLICATES_DISABLED = 0, /**< Do not remove duplicate reports. */ + SCAN_FILTER_DUPLICATES_ENABLED = 1, /**< Remove duplicate reports. */ + SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 /**< Remove reports which are duplicate + within a single period. */ +}; + +struct own_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address. */ + RANDOM, /**< Random Device Address. */ + RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use the public address. */ + RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on + the local IRK from the resolving list. If the resolving list + contains no matching entry, use previously set random address. */ + }; + own_address_type_t(type value) : ble::SafeEnum(value) { } +}; + +/** + * Accuracy of the master clock. + */ +struct clock_accuracy_t : SafeEnum{ + enum type { + /** + * 500 PPM + */ + PPM_500 = 0x00, + + /** + * 250 PPM + */ + PPM_250 = 0x01, + + /** + * 150 PPM + */ + PPM_150 = 0x02, + + /** + * 100 PPM + */ + PPM_100 = 0x03, + + /** + * 75 PPM + */ + PPM_75 = 0x04, + + /** + * 50 PPM + */ + PPM_50 = 0x05, + + /** + * 30 PPM + */ + PPM_30 = 0x06, + + /** + * 20 PPM + */ + PPM_20 = 0x07 + }; + + /** Get clock accuracy. + * + * @return Parts per million as a number. + */ + uint16_t get_ppm() { + uint16_t ppm = 0; + + switch(value()) { + case PPM_500: + ppm = 500; + break; + case PPM_250: + ppm = 250; + break; + case PPM_150: + ppm = 150; + break; + case PPM_100: + ppm = 100; + break; + case PPM_75: + ppm = 75; + break; + case PPM_50: + ppm = 50; + break; + case PPM_30: + ppm = 30; + break; + case PPM_20: + ppm = 20; + break; + } + + return ppm; + } + + /** + * Construct a new clock_accuracy_t value. + */ + clock_accuracy_t(type value) : SafeEnum(value) { } + + explicit clock_accuracy_t(uint8_t raw_value) : + SafeEnum(static_cast(raw_value)) { } +}; + +/** + * Enumeration of GAP roles. + * + * @note The BLE API does not express the broadcaster and scanner roles. + * + * @attention A device can fulfill different roles concurrently. + */ +struct connection_role_t :SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { + /** + * Central Role. + * + * The device can scan and initiate connection to peripherals. It + * acts as the master when a connection is established. + * + * @note A central is a scanner. + */ + CENTRAL = 0x00, + + /** + * @see CENTRAL + */ + MASTER = 0x00, + + /** + * Peripheral Role. + * + * The device can advertise and it can be connected by a central. It + * acts as a slave when connected. + * + * @note A peripheral is a broadcaster. + */ + PERIPHERAL = 0x01, + + /** + * @see SLAVE + */ + SLAVE = 0x01 + }; + + /** + * Construct a new instance of role_t. + */ + connection_role_t(type value) : + SafeEnum(value) { } + + /** + * Explicit constructor from a raw value. + * @param raw_value The role. + */ + explicit connection_role_t(uint8_t raw_value) : + SafeEnum(raw_value) { } +}; + +} // namespace ble + +#endif //BLE_GAP_TYPES_H From b59b29ba9f6ddef0777064ba5beb4b632177e6aa Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 10:42:19 +0000 Subject: [PATCH 188/361] reject conenct request if exteneded not enabled but required --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index a6b58773e5..3ef5d1bb68 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -622,6 +622,13 @@ ble_error_t GenericGap::connect( return BLE_ERROR_INVALID_PARAM; } + if (!is_extended_advertising_available()) { + ble::phy_set_t set(connectionParams.getPhySet()); + if (set.count() != 1 || set.get_1m() == false) { + return BLE_ERROR_INVALID_PARAM; + } + } + return _pal_gap.extended_create_connection( (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), From b4c704c807069eff37576949b32aa7b8ac95c0a8 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 10:44:02 +0000 Subject: [PATCH 189/361] BLE: Move leftover target_peer_address_type_t in ble/gap/Types.h --- features/FEATURE_BLE/ble/BLETypes.h | 8 -------- features/FEATURE_BLE/ble/gap/Types.h | 8 ++++++++ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 35c7f13ae7..62e85e7679 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -615,14 +615,6 @@ struct peer_address_type_t :SafeEnum { SafeEnum(PUBLIC) { } }; -struct target_peer_address_type_t : ble::SafeEnum { - enum type { - PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ - RANDOM /**< Random Device Address or Random (static) Identity Address. */ - }; - target_peer_address_type_t(type value) : ble::SafeEnum(value) { } -}; - /** * Type that describes a bluetooth PHY(sical) transport. */ diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 05ed75ddf0..f4bdeda0fe 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -322,6 +322,14 @@ struct own_address_type_t : ble::SafeEnum { own_address_type_t(type value) : ble::SafeEnum(value) { } }; +struct target_peer_address_type_t : ble::SafeEnum { + enum type { + PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ + RANDOM /**< Random Device Address or Random (static) Identity Address. */ + }; + target_peer_address_type_t(type value) : ble::SafeEnum(value) { } +}; + /** * Accuracy of the master clock. */ From db55540952b68f02712baadebf1e5713421452e9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 11:08:07 +0000 Subject: [PATCH 190/361] BLE: merge ble::advertising_type_t and pal::advertising_type_t. --- .../ble/gap/AdvertisingParameters.h | 4 +- features/FEATURE_BLE/ble/gap/Types.h | 76 +++++++++++-------- features/FEATURE_BLE/ble/pal/GapTypes.h | 69 +---------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 5 +- 4 files changed, 51 insertions(+), 103 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 737825b919..4f6bd1eef3 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -73,7 +73,7 @@ public: * @note If value in input are out of range, they will be normalized. */ AdvertisingParameters( - ble::advertising_type_t advType = ADV_CONNECTABLE_UNDIRECTED, + advertising_type_t advType = advertising_type_t::ADV_CONNECTABLE_UNDIRECTED, adv_interval_t minInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MIN), adv_interval_t maxInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MAX) ) : @@ -97,7 +97,7 @@ public: _includeHeaderTxPower(false) { /* Min interval is slightly larger than in other modes. */ - if (_advType == ADV_NON_CONNECTABLE_UNDIRECTED) { + if (_advType == advertising_type_t::ADV_NON_CONNECTABLE_UNDIRECTED) { _minInterval = adv_interval_t(std::max(_minInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); _maxInterval = adv_interval_t(std::max(_maxInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); } diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index f4bdeda0fe..dbd9360264 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -58,42 +58,56 @@ typedef uint16_t periodic_sync_handle_t; * It determine how the device appears to other scanner and peripheral * devices in the scanning range. */ -enum advertising_type_t { - /** - * Device is connectable, scannable and doesn't expect connection from a - * specific peer. - * - * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. - */ - ADV_CONNECTABLE_UNDIRECTED, +struct advertising_type_t : SafeEnum { + enum type { + /** + * Device is connectable, scannable and doesn't expect connection from a + * specific peer. + * + * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. + */ + ADV_CONNECTABLE_UNDIRECTED = 0x00, + ADV_IND = 0x00, + + /** + * Device is connectable and expects connection from a specific peer. + * (3.75 ms or smaller Advertising Interval) + * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. + */ + ADV_CONNECTABLE_DIRECTED = 0x01, + ADV_DIRECT_IND = 0x01, + + /** + * Device is scannable but not connectable. + * + * @see Vol 6, Part B, Section 2.3.1.4. + */ + ADV_SCANNABLE_UNDIRECTED = 0x02, + ADV_SCAN_IND = 0x02, + + /** + * Device is not connectable and not scannable. + * + * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. + */ + ADV_NON_CONNECTABLE_UNDIRECTED = 0x03, + ADV_NONCONN_IND = 0x03, + + /** + * Device is connectable and expects connection from a specific peer (sent at long user set intervals). + */ + ADV_CONNECTABLE_DIRECTED_LOW_DUTY = 0x04, + ADV_DIRECT_IND_LOW_DUTY_CYCLE = 0x04 + }; /** - * Device is connectable and expects connection from a specific peer. - * (3.75 ms or smaller Advertising Interval) - * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. + * Construct a new advertising_type_t value. */ - ADV_CONNECTABLE_DIRECTED, - - /** - * Device is scannable but not connectable. - * - * @see Vol 6, Part B, Section 2.3.1.4. - */ - ADV_SCANNABLE_UNDIRECTED, - - /** - * Device is not connectable and not scannable. - * - * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. - */ - ADV_NON_CONNECTABLE_UNDIRECTED, - - /** - * Device is connectable and expects connection from a specific peer (sent at long user set intervals). - */ - ADV_CONNECTABLE_DIRECTED_LOW_DUTY + advertising_type_t(type value) : + SafeEnum(value) { } }; + /** Used to indicate if the packet is complete and if it's truncated. */ struct advertising_data_status_t : SafeEnum{ diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 1959499e43..6dd2beb689 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -24,44 +24,7 @@ namespace ble { namespace pal { -/** - * Type of advertising the LE subsystem can use when it advertise. - */ -struct advertising_type_t : SafeEnum { - enum type { - /** - * Connectable and scannable undirected advertising. - */ - ADV_IND = 0x00, - - /** - * Connectable high duty cycle directed advertising. - */ - ADV_DIRECT_IND = 0x01, - - /** - * Scannable undirected advertising. - */ - ADV_SCAN_IND = 0x02, - - /** - * Non connectable undirected advertising. - */ - ADV_NONCONN_IND = 0x03, - - /** - * Connectable low duty cycle directed advertising. - */ - ADV_DIRECT_IND_LOW_DUTY_CYCLE = 0x04 - }; - - /** - * Construct a new advertising_type_t value. - */ - advertising_type_t(type value) : - SafeEnum(value) { } -}; - +typedef ble::advertising_type_t advertising_type_t; /** * Type used to model the own address used during the following GAP operations: @@ -602,7 +565,7 @@ struct advertising_event_properties_t { omit_advertiser_address(false), include_tx_power(false) { - switch ((advertising_type_t::type) adv_type.value()) { + switch (adv_type.value()) { case advertising_type_t::ADV_IND: connectable = true; scannable = true; @@ -625,34 +588,6 @@ struct advertising_event_properties_t { } } - explicit advertising_event_properties_t(ble::advertising_type_t adv_type) : - connectable(false), - scannable(false), - directed(false), - high_duty_cycle(false), - use_legacy_pdu(true), - omit_advertiser_address(false), - include_tx_power(false) - { - switch (adv_type) { - case ADV_CONNECTABLE_UNDIRECTED: - connectable = true; - scannable = true; - break; - case ADV_CONNECTABLE_DIRECTED: - case ADV_CONNECTABLE_DIRECTED_LOW_DUTY: - connectable = true; - directed = true; - break; - case ADV_SCANNABLE_UNDIRECTED: - scannable = true; - break; - case ADV_NON_CONNECTABLE_UNDIRECTED: - break; - } - } - - /** * If set the advertising event is connectable. */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3ef5d1bb68..8f066c6ab6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1761,7 +1761,7 @@ ble_error_t GenericGap::setAdvertisingParams( return _pal_gap.set_advertising_parameters( params.getMinPrimaryInterval().value(), params.getMaxPrimaryInterval().value(), - (pal::advertising_type_t::type) params.getType(), + params.getType(), (pal::own_address_type_t::type) params.getOwnAddressType().value(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), @@ -1782,8 +1782,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( return BLE_ERROR_INVALID_PARAM; } - pal::advertising_event_properties_t event_properties( - (pal::advertising_type_t::type)params.getType()); + pal::advertising_event_properties_t event_properties(params.getType()); event_properties.include_tx_power = params.getTxPowerInHeader(); event_properties.omit_advertiser_address = params.getAnonymousAdvertising(); event_properties.use_legacy_pdu = params.getUseLegacyPDU(); From c6cdfd0b7eb4d562139691670bdba0b0d678c1c3 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 11:20:30 +0000 Subject: [PATCH 191/361] BLE: Merve ble::advertising_policy_mode and pal::advertising_filter_policy . --- .../ble/gap/AdvertisingParameters.h | 8 ++-- features/FEATURE_BLE/ble/gap/Types.h | 42 +++++++++++-------- features/FEATURE_BLE/ble/pal/GapTypes.h | 40 +----------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 +- 4 files changed, 32 insertions(+), 62 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 4f6bd1eef3..942f504254 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -82,7 +82,7 @@ public: _maxInterval(maxInterval), _peerAddressType(ble::target_peer_address_type_t::PUBLIC), _ownAddressType(ble::own_address_type_t::PUBLIC), - _policy(ble::ADV_POLICY_IGNORE_WHITELIST), + _policy(advertising_filter_policy_t::NO_FILTER), _primaryPhy(ble::phy_t::LE_1M), _secondaryPhy(ble::phy_t::LE_1M), _peerAddress(), @@ -273,7 +273,7 @@ public: * * @return A reference to this object. */ - AdvertisingParameters &setPolicyMode(advertising_policy_mode_t mode) + AdvertisingParameters &setPolicyMode(advertising_filter_policy_t mode) { _policy = mode; return *this; @@ -283,7 +283,7 @@ public: * * @return Policy used. */ - ble::advertising_policy_mode_t getPolicyMode() const + ble::advertising_filter_policy_t getPolicyMode() const { return _policy; } @@ -458,7 +458,7 @@ private: target_peer_address_type_t _peerAddressType; own_address_type_t _ownAddressType; - advertising_policy_mode_t _policy; + advertising_filter_policy_t _policy; phy_t _primaryPhy; phy_t _secondaryPhy; address_t _peerAddress; diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index dbd9360264..b3717540ca 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -250,26 +250,34 @@ typedef int8_t advertising_power_t; * * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. */ -enum advertising_policy_mode_t { - /** - * The whitelist is not used to filter peer request during advertising. - */ - ADV_POLICY_IGNORE_WHITELIST = 0, +struct advertising_filter_policy_t : SafeEnum { + enum type { + /** + * Process connection and scan requests from all devices. The whitelist is + * not used. + */ + NO_FILTER = 0x00, - /** - * The whitelist is used to filter peer scan requests. - */ - ADV_POLICY_FILTER_SCAN_REQS = 1, + /** + * Process connection requests from all devices but filter out scan requests + * of devices which are not in the whitelist. + */ + FILTER_SCAN_REQUESTS = 0x01, - /** - * The whitelist is used to filter peer connection requests. - */ - ADV_POLICY_FILTER_CONN_REQS = 2, + /** + * Process scan requests from all devices but filter out connection requests + * of devices which are not in the whitelist. + */ + FILTER_CONNECTION_REQUEST = 0x02, - /** - * The whitelist is used to filter peer scan and connection requests. - */ - ADV_POLICY_FILTER_ALL_REQS = 3, + /** + * Filter out scan or connection requests of devices which are not in the + * whitelist. + */ + FILTER_SCAN_AND_CONNECTION_REQUESTS = 0x03 + }; + + advertising_filter_policy_t(type value) : SafeEnum(value) { } }; /** diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 6dd2beb689..4f320ea2a5 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -297,45 +297,7 @@ struct disconnection_reason_t : SafeEnum { SafeEnum(value) { } }; - -/** - * Filter policy which can be used during advertising. - */ -struct advertising_filter_policy_t : - SafeEnum { - enum type { - /** - * Process connection and scan requests from all devices. The whitelist is - * not used. - */ - NO_FILTER = 0x00, - - /** - * Process connection requests from all devices but filter out scan requests - * of devices which are not in the whitelist. - */ - FILTER_SCAN_REQUESTS = 0x01, - - /** - * Process scan requests from all devices but filter out connection requests - * of devices which are not in the whitelist. - */ - FILTER_CONNECTION_REQUEST = 0x02, - - /** - * Filter out scan or connection requests of devices which are not in the - * whitelist. - */ - FILTER_SCAN_AND_CONNECTION_REQUESTS = 0x03 - }; - - /** - * Construct a new instance of advertising_filter_policy_t. - */ - advertising_filter_policy_t(type value) : - SafeEnum(value) { } -}; - +typedef ble::advertising_filter_policy_t advertising_filter_policy_t; /** * Filter policy which can be used during a scan. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 8f066c6ab6..b0c3ab9a8e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1766,7 +1766,7 @@ ble_error_t GenericGap::setAdvertisingParams( (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), channel_map, - (pal::advertising_filter_policy_t::type) params.getPolicyMode() + params.getPolicyMode() ); } else { return setExtendedAdvertisingParameters(handle, params); @@ -1802,7 +1802,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( (pal::own_address_type_t::type) params.getOwnAddressType().value(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), - (pal::advertising_filter_policy_t::type) params.getPolicyMode(), + params.getPolicyMode(), params.getTxPower(), params.getPrimaryPhy(), params.getSecondaryMaxSkip(), From 3b334b814d19c1337b8c700a694606e6f8a387d9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 11:23:27 +0000 Subject: [PATCH 192/361] BLE: Revert space change in ble/GapAdvertisingParams.h --- features/FEATURE_BLE/ble/GapAdvertisingParams.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/GapAdvertisingParams.h b/features/FEATURE_BLE/ble/GapAdvertisingParams.h index 9cd6ad6729..2b8e74d94f 100644 --- a/features/FEATURE_BLE/ble/GapAdvertisingParams.h +++ b/features/FEATURE_BLE/ble/GapAdvertisingParams.h @@ -81,28 +81,28 @@ public: * * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. */ - ADV_CONNECTABLE_UNDIRECTED, + ADV_CONNECTABLE_UNDIRECTED, /** * Device is connectable and expects connection from a specific peer. * * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. */ - ADV_CONNECTABLE_DIRECTED, + ADV_CONNECTABLE_DIRECTED, /** * Device is scannable but not connectable. * * @see Vol 6, Part B, Section 2.3.1.4. */ - ADV_SCANNABLE_UNDIRECTED, + ADV_SCANNABLE_UNDIRECTED, /** * Device is not connectable and not scannable. * * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. */ - ADV_NON_CONNECTABLE_UNDIRECTED + ADV_NON_CONNECTABLE_UNDIRECTED }; /** From 07d73d5e20a94f0002d52bd555795a31d270016b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 12:17:26 +0000 Subject: [PATCH 193/361] BLE: merge ble::scanning_policy_mode_t and gap::scanning_filter_policy_t This change set also introduce ble::initiator_filter_policy_t and fix a type issue ble::ConnectionParameters. --- features/FEATURE_BLE/ble/Gap.h | 25 ++++-- .../ble/gap/ConnectionParameters.h | 14 ++- features/FEATURE_BLE/ble/gap/ScanParameters.h | 8 +- features/FEATURE_BLE/ble/gap/Types.h | 86 +++++++++++++------ features/FEATURE_BLE/ble/pal/GapTypes.h | 49 +---------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 6 +- 6 files changed, 90 insertions(+), 98 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index f784c7eb8d..99ec5adac3 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -548,6 +548,23 @@ public: ADV_POLICY_FILTER_ALL_REQS = 3, }; + /** + * Scanning policy filter mode. + * + * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. + */ + enum ScanningPolicyMode_t { + /** + * The whitelist is not used for scanning operations. + */ + SCAN_POLICY_IGNORE_WHITELIST = 0, + + /** + * The whitelist is used to filter incoming advertising. + */ + SCAN_POLICY_FILTER_ALL_ADV = 1, + }; + /** * Connection initiation policy filter mode. * @@ -635,14 +652,6 @@ public: */ typedef ble::target_peer_address_type_t TargetPeerAddressType_t; - /** - * Scanning filter policy based on the whitelist - */ - typedef ble::scanning_policy_mode_t ScanningPolicyMode_t; - - static const ScanningPolicyMode_t SCAN_POLICY_IGNORE_WHITELIST = ble::SCAN_POLICY_IGNORE_WHITELIST; - static const ScanningPolicyMode_t SCAN_POLICY_FILTER_ALL_ADV = ble::SCAN_POLICY_FILTER_ALL_ADV; - /** * Enumeration of BLE PHY */ diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index b097dd6696..f9a6811758 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -33,7 +33,7 @@ class ConnectionParameters { static const uint8_t MAX_PARAM_PHYS = 3; public: ConnectionParameters() : - _filterPolicy(ble::SCAN_POLICY_IGNORE_WHITELIST), + _filterPolicy(initiator_filter_policy_t::NO_FILTER), _ownAddressType(ble::own_address_type_t::PUBLIC) { for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { @@ -104,9 +104,7 @@ public: return *this; } - ConnectionParameters &setFilterPolicy( - ble::scanning_policy_mode_t filterPolicy - ) + ConnectionParameters &setFilterPolicy(initiator_filter_policy_t filterPolicy) { _filterPolicy = filterPolicy; @@ -151,7 +149,7 @@ public: return _ownAddressType; } - ble::scanning_policy_mode_t getFilterPolicy() const + initiator_filter_policy_t getFilterPolicy() const { return _filterPolicy; } @@ -160,8 +158,8 @@ public: { return ( _enabledPhy[ble::phy_t::LE_1M] * 1 + - _enabledPhy[ble::phy_t::LE_2M] * 1 + - _enabledPhy[ble::phy_t::LE_CODED] * 1 + _enabledPhy[ble::phy_t::LE_2M] * 1 + + _enabledPhy[ble::phy_t::LE_CODED] * 1 ); } @@ -309,7 +307,7 @@ private: } private: - ble::scanning_policy_mode_t _filterPolicy; + initiator_filter_policy_t _filterPolicy; ble::own_address_type_t _ownAddressType; uint16_t _scanInterval[MAX_PARAM_PHYS]; /* 0.625 ms */ diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index f6928db7b0..770926605a 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -56,7 +56,7 @@ public: ScanParameters() : own_address_type(own_address_type_t::PUBLIC), - scanning_filter_policy(ble::SCAN_POLICY_IGNORE_WHITELIST), + scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), phys(ble::phy_set_t::PHY_SET_1M), phy_1m_configuration( scan_interval_t::min(), scan_window_t::min(), true @@ -77,13 +77,13 @@ public: return own_address_type; } - ScanParameters& set_scanning_filter_policy(ble::scanning_policy_mode_t filter_policy) + ScanParameters& set_scanning_filter_policy(ble::scanning_filter_policy_t filter_policy) { scanning_filter_policy = filter_policy; return *this; } - ble::scanning_policy_mode_t get_scanning_filter_policy() const + ble::scanning_filter_policy_t get_scanning_filter_policy() const { return scanning_filter_policy; } @@ -138,7 +138,7 @@ public: private: own_address_type_t own_address_type; - ble::scanning_policy_mode_t scanning_filter_policy; + ble::scanning_filter_policy_t scanning_filter_policy; ble::phy_set_t phys; diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index b3717540ca..cdae5e8e6e 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -285,39 +285,69 @@ struct advertising_filter_policy_t : SafeEnum { + enum type { + /** + * Accept all advertising packets except directed advertising packet not + * addressed to this device. + */ + NO_FILTER = 0x00, + + /** + * Accept only advertising packets from devices in the whitelist except + * directed advertising packet not addressed to this device. + */ + FILTER_ADVERTISING = 0x01, + + + /** + * Accept all advertising packets except directed advertising packets + * where the initiator's identity address does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + NO_FILTER_INCLUDE_UNRESOLVABLE_DIRECTED = 2, + + /** + * Accept all advertising packets except: + * - advertising packets where the advertiser's + * identity address is not in the White List, + * - directed advertising packets where the initiator's identity address + * does not address this device. + * + * @note Directed advertising packets where the initiator's address is a + * resolvable private address that cannot be resolved are also accepted. + */ + FILTER_ADVERTISING_INCLUDE_UNRESOLVABLE_DIRECTED = 3 + }; /** - * The whitelist is used to filter incoming advertising. + * Construct a new instance of scanning_filter_policy_t. */ - SCAN_POLICY_FILTER_ALL_ADV = 1, - - /** - * Accept all advertising packets except directed advertising packets - * where the initiator's identity address does not address this device. - * - * @note Directed advertising packets where the initiator's address is a - * resolvable private address that cannot be resolved are also accepted. - */ - SCAN_POLICY_IGNORE_WHITELIST_INCLUDE_UNRESOLVABLE = 2, - - /** - * Accept all advertising packets except: - * - advertising packets where the advertiser's - * identity address is not in the White List, - * - directed advertising packets where the initiator's identity address - * does not address this device. - * - * @note Directed advertising packets where the initiator's address is a - * resolvable private address that cannot be resolved are also accepted. - */ - SCAN_POLICY_FILTER_ALL_ADV_INCLUDE_UNRESOLVABLE = 3 + scanning_filter_policy_t(type value) : SafeEnum(value) { } }; +/** + * Filter policy which can be used during connection initiation. + */ +struct initiator_filter_policy_t : SafeEnum { + enum type { + /** + * The whitelist is not used to determine which advertiser to connect to. + */ + NO_FILTER, + + /** + * Whitelist is used to determine which advertiser to connect to. + */ + USE_WHITE_LIST + }; + + initiator_filter_policy_t(type value) : SafeEnum(value) { } +}; + + /** * Scanning policy filter mode. * diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 4f320ea2a5..90d8fbb0dd 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -299,54 +299,9 @@ struct disconnection_reason_t : SafeEnum { typedef ble::advertising_filter_policy_t advertising_filter_policy_t; -/** - * Filter policy which can be used during a scan. - */ -struct scanning_filter_policy_t : SafeEnum { - enum type { - /** - * Accept all advertising packets except directed advertising packet not - * addressed to this device. - */ - NO_FILTER = 0x00, +typedef ble::scanning_filter_policy_t scanning_filter_policy_t; - /** - * Accept only advertising packets from devices in the whitelist except - * directed advertising packet not addressed to this device. - */ - FILTER_ADVERTISING = 0x01 - - // EXTENDED ADVERTISING FILTER POLICY (accept private resolvable direct advertising) - }; - - /** - * Construct a new instance of scanning_filter_policy_t. - */ - scanning_filter_policy_t(type value) : - SafeEnum(value) { } - -}; - - -/** - * Filter policy which can be used during connection initiation. - */ -struct initiator_policy_t : SafeEnum { - enum type { - /** - * The whitelist is not used to determine which advertiser to connect to. - */ - NO_FILTER, - - /** - * Whitelist is used to determine which advertiser to connect to. - */ - USE_WHITE_LIST - }; - - initiator_policy_t(type value) : - SafeEnum(value) { } -}; +typedef ble::initiator_filter_policy_t initiator_policy_t; /** * Hold advertising data. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b0c3ab9a8e..4f4ee03a1b 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -630,7 +630,7 @@ ble_error_t GenericGap::connect( } return _pal_gap.extended_create_connection( - (ble::pal::initiator_policy_t::type)connectionParams.getFilterPolicy(), + connectionParams.getFilterPolicy(), (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), (ble::peer_address_type_t::type)peerAddressType.value(), peerAddress, @@ -2387,7 +2387,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) return _pal_gap.set_extended_scan_parameters( (pal::own_address_type_t::type) params.get_own_address_type().value(), - (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy(), + params.get_scanning_filter_policy(), params.get_scanning_phys(), active_scanning, scan_interval, @@ -2406,7 +2406,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) legacy_configuration.interval.value(), legacy_configuration.window.value(), (pal::own_address_type_t::type) params.get_own_address_type().value(), - (pal::scanning_filter_policy_t::type) params.get_scanning_filter_policy() + params.get_scanning_filter_policy() ); } } From cc8b43f3ab057974f373be5f1230c7f8659aefac Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 12:40:15 +0000 Subject: [PATCH 194/361] update gap overview --- features/FEATURE_BLE/ble/Gap.h | 139 +++++---------------------------- 1 file changed, 19 insertions(+), 120 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 99ec5adac3..f2392305e3 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -188,10 +188,6 @@ * inactive, periodic advertising will not start until you start extended advertising * at a later time. * - * @par Extended scanning - * - * In order to see extended and periodic advertising you must use extended scanning. - * * @par Privacy * * Privacy is a feature that allows a device to avoid being tracked by other @@ -221,131 +217,33 @@ * If the device scans actively, then it will send scan request to scannable * advertisers and collect their scan response. * - * @code - * // assuming gap has been initialized - * Gap& gap; + * Scanning is done by creating ScanParameters and applying then with + * setScanParameters(). One configure you may call startScan(). * - * // Handle advertising packet by dumping their content - * void handle_advertising_packet(const AdvertisementCallbackParams_t* packet) - * { - * printf("Packet received: \r\n"); - * printf(" - peer address: %02X:%02X:%02X:%02X:%02X:%02X\r\n", - * packet->peerAddr[5], packet->peerAddr[4], packet->peerAddr[3], - * packet->peerAddr[2], packet->peerAddr[1], packet->peerAddr[0]); - * printf(" - rssi: %d", packet->rssi); - * printf(" - scan response: %s\r\n", packet->isScanresponse ? "true" : "false"); - * printf(" - advertising type: %d\r\n", packet->type); - * printf(" - advertising type: %d\r\n", packet->type); - * printf(" - Advertising data: \r\n"); - * - * // parse advertising data, it is a succession of AD structures where - * // the first byte is the size of the AD structure, the second byte the - * // type of the data and remaining bytes are the value. - * - * for (size_t i = 0; i < packet->advertisingDataLen; i += packet->advertisingData[i]) { - * printf(" - type: 0X%02X, data: ", packet->advertisingData[i + 1]); - * for (size_t j = 0; j < packet->advertisingData[i] - 2; ++j) { - * printf("0X%02X ", packet->advertisingData[i + 2 + j]); - * } - * printf("\r\n"); - * } - * } - * - * // set the scan parameters - * gap.setScanParams( - * 100, // interval between two scan window in ms - * 50, // scan window: period during which the device listen for advertising packets. - * 0, // the scan process never ends - * true // the device sends scan request to scannable peers. - * ); - * - * // start the scan procedure - * gap.startScan(handle_advertising_packet); - * @endcode + * When a scanning device receives an advertising packet it will call + * onAdvertisingReport() in the registered event handler. A whitelist may be used + * to limit the advertising reports by setting the correct policy in the scan + * parameters. * * @par Connection event handling * - * A peer may connect device advertising connectable packets. The - * advertising procedure ends as soon as the device is connected. + * A peer may connect device advertising connectable packets. The advertising + * procedure ends as soon as the device is connected. If an advertising timeout + * has been set in the advertising parameters then onAdvertisingEnd will be called + * in the registered eventHandler when it runs out. * * A device accepting a connection request from a peer is named a peripheral, * and the device initiating the connection is named a central. * + * Connection is initiated by central devices. A call to connect() will result in + * the device scanning on any PHYs set in ConectionParamters passed in. + * * Peripheral and central receive a connection event when the connection is - * effective. + * effective. If successful will result in a call to onConnectionComplete in the + * EventHandler registered with the Gap. * - * @code - * Gap& gap; - * - * // handle connection event - * void when_connected(const ConnectionCallbackParams_t *connection_event) { - * // If this callback is entered, then the connection to a peer is effective. - * } - * - * // register connection event handler, which will be invoked whether the device - * // acts as a central or a peripheral - * gap.onConnection(when_connected); - * @endcode - * - * @par Connection initiation - * - * Connection is initiated central devices. - * - * @code - * // assuming gap has been initialized - * Gap& gap; - * - * // Handle the connection event - * void handle_connection(const ConnectionCallbackParams_t* connection_event) - * { - * // event handling - * } - * - * // Handle advertising packet: connect to the first connectable device - * void handle_advertising_packet(const AdvertisementCallbackParams_t* packet) - * { - * if (packet->type != GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED) { - * return; - * } - * - * // register connection event handler - * gap.onConnection(handle_connection); - * - * Gap::ConnectionParams_t connection_parameters = { - * 50, // min connection interval - * 100, // max connection interval - * 0, // slave latency - * 600 // connection supervision timeout - * }; - * - * // scan parameter used to find the device to connect to - * GapScanningParams scanning_params( - * 100, // interval - * 100, // window - * 0, // timeout - * false // active - * ); - * - * // Initiate the connection procedure - * gap.connect( - * packet->peerAddr, - * packet->addressType, - * &connection_parameters, - * &scanning_params - * ); - * } - * - * // set the scan parameters - * gap.setScanParams( - * 100, // interval between two scan window in ms - * 50, // scan window: period during which the device listen for advertising packets. - * 0, // the scan process never ends - * true // the device sends scan request to scannable peers. - * ); - * - * // start the scan procedure - * gap.startScan(handle_advertising_packet); - * @endcode + * It the connection attempt fails it will result in onConnectionComplete called + * on the central device with the event carrying the error flag. * * @par Changing the PHYsical transport of a connection * @@ -354,7 +252,8 @@ * can either increase the bandwidth or increase the communication range. * An increased bandwidth equals a better power consumption but also a loss in * sensibility and therefore a degraded range. - * Symmetrically an increased range means a lowered bandwith and a degraded power + * + * Symmetrically an increased range means a lowered bandwidth and a degraded power * consumption. * * Applications can change the PHY used by calling the function setPhy. Once the From d1cb1e1a39ef3d719b350d7114fa21b202ca7ef0 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 12:32:28 +0000 Subject: [PATCH 195/361] BLE: merge ble::scanning_filter_duplicates_t and pal::duplicate_filter_t --- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/gap/Types.h | 28 +++++++++++++++---- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/ble/pal/GapTypes.h | 25 +---------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 6 ++-- 5 files changed, 28 insertions(+), 35 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index f2392305e3..22c815fbbd 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1944,7 +1944,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startScan( - ble::scanning_filter_duplicates_t filtering = ble::SCAN_FILTER_DUPLICATES_DISABLED, + ble::duplicates_filter_t filtering = ble::duplicates_filter_t::DISABLE, ble::scan_duration_t duration = ble::scan_duration_t(0), ble::scan_period_t period = ble::scan_period_t(0) ) { diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index cdae5e8e6e..96268f8d27 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -347,17 +347,33 @@ struct initiator_filter_policy_t : SafeEnum initiator_filter_policy_t(type value) : SafeEnum(value) { } }; - /** * Scanning policy filter mode. * * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. */ -enum scanning_filter_duplicates_t { - SCAN_FILTER_DUPLICATES_DISABLED = 0, /**< Do not remove duplicate reports. */ - SCAN_FILTER_DUPLICATES_ENABLED = 1, /**< Remove duplicate reports. */ - SCAN_FILTER_DUPLICATES_ENABLED_PER_PERIOD = 2 /**< Remove reports which are duplicate - within a single period. */ +struct duplicates_filter_t : SafeEnum{ + enum type { + /** + * Disable duplicate filtering. + */ + DISABLE, + + /** + * Enable duplicate filtering. + */ + ENABLE, + + /** + * Enable duplicate filtering, reset the cache periodically. + */ + PERIODIC_RESET + }; + + /** + * Construct a new duplicates_filter_t value. + */ + duplicates_filter_t(type value) : SafeEnum(value) { } }; struct own_address_type_t : ble::SafeEnum { diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 9e36a2b8c5..02badf5017 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -175,7 +175,7 @@ public: /** @copydoc Gap::startScan */ virtual ble_error_t startScan( - scanning_filter_duplicates_t filtering, + duplicates_filter_t filtering, scan_duration_t duration, scan_period_t period ); diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 90d8fbb0dd..8755ba7d9e 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -644,30 +644,7 @@ struct advertising_fragment_description_t : SafeEnum(value) { } }; -struct duplicates_filter_t : SafeEnum{ - enum type { - /** - * Disable duplicate filtering. - */ - DISABLE, - - /** - * Enable duplicate filtering. - */ - ENABLE, - - /** - * Enable duplicate filtering, reset the cache periodically. - */ - PERIODIC_RESET - }; - - /** - * Construct a new duplicates_filter_t value. - */ - duplicates_filter_t(type value) : - SafeEnum(value) { } -}; +typedef ble::duplicates_filter_t duplicates_filter_t; /** * Identify a periodic advertising sync. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 4f4ee03a1b..7137086346 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2412,7 +2412,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) } ble_error_t GenericGap::startScan( - scanning_filter_duplicates_t filtering, + duplicates_filter_t filtering, scan_duration_t duration, scan_period_t period ) @@ -2427,7 +2427,7 @@ ble_error_t GenericGap::startScan( if (is_extended_advertising_available()) { return _pal_gap.extended_scan_enable( /* enable */true, - (pal::duplicates_filter_t::type) filtering, + filtering, duration.value(), period.value() ); @@ -2438,7 +2438,7 @@ ble_error_t GenericGap::startScan( ble_error_t err = _pal_gap.scan_enable( true, - filtering == SCAN_FILTER_DUPLICATES_DISABLED ? false : true + filtering == duplicates_filter_t::DISABLE ? false : true ); if (err) { From ad127d76af708afe236027334b5eeeced5533b20 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 12:43:32 +0000 Subject: [PATCH 196/361] BLE: merge ble::own_address_t and pal::own_address_type_t. --- features/FEATURE_BLE/ble/gap/Types.h | 45 ++++++++++++++----- features/FEATURE_BLE/ble/pal/GapTypes.h | 38 +--------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 10 ++--- 3 files changed, 41 insertions(+), 52 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 96268f8d27..de3066cc7c 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -376,18 +376,43 @@ struct duplicates_filter_t : SafeEnum{ duplicates_filter_t(type value) : SafeEnum(value) { } }; -struct own_address_type_t : ble::SafeEnum { +/** + * Type used to model the own address used during the following GAP operations: + * advertising, scanning and initiating + */ +struct own_address_type_t : SafeEnum { enum type { - PUBLIC = 0, /**< Public Device Address. */ - RANDOM, /**< Random Device Address. */ - RANDOM_RESOLVABLE_PUBLIC_FALLBACK, /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use the public address. */ - RANDOM_RESOLVABLE_RANDOM_FALLBACK /**< Controller generates the Resolvable Private Address based on - the local IRK from the resolving list. If the resolving list - contains no matching entry, use previously set random address. */ + /** + * Use the public device address. + */ + PUBLIC_ADDRESS = 0x00, + PUBLIC = 0x00, + + /** + * Use the random device address. + */ + RANDOM_ADDRESS = 0x01, + RANDOM = 0x01, + + /** + * Generated resolvable private address based on the local IRK from the + * resolving list. Use the public address if no entry match in the resolving + * list. + */ + RESOLVABLE_PRIVATE_ADDRESS_PUBLIC_FALLBACK = 0x02, + + /** + * Generated resolvable private address based on the local IRK from the + * resolving list. Use the random address if no entry match in the resolving + * list. + */ + RESOLVABLE_PRIVATE_ADDRESS_RANDOM_FALLBACK = 0x03, }; - own_address_type_t(type value) : ble::SafeEnum(value) { } + + /** + * Construct a new instance of own_address_type_t. + */ + own_address_type_t(type value) : SafeEnum(value) { } }; struct target_peer_address_type_t : ble::SafeEnum { diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 8755ba7d9e..aaf9b2f280 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -26,43 +26,7 @@ namespace pal { typedef ble::advertising_type_t advertising_type_t; -/** - * Type used to model the own address used during the following GAP operations: - * advertising, scanning and initiating - */ -struct own_address_type_t : SafeEnum { - enum type { - /** - * Use the public device address. - */ - PUBLIC_ADDRESS = 0x00, - - /** - * Use the random device address. - */ - RANDOM_ADDRESS = 0x01, - - /** - * Generated resolvable private address based on the local IRK from the - * resolving list. Use the public address if no entry match in the resolving - * list. - */ - RESOLVABLE_PRIVATE_ADDRESS_PUBLIC_FALLBACK = 0x02, - - /** - * Generated resolvable private address based on the local IRK from the - * resolving list. Use the random address if no entry match in the resolving - * list. - */ - RESOLVABLE_PRIVATE_ADDRESS_RANDOM_FALLBACK = 0x03, - }; - - /** - * Construct a new instance of own_address_type_t. - */ - own_address_type_t(type value) : - SafeEnum(value) { } -}; +typedef ble::own_address_type_t own_address_type_t; /** diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7137086346..0394a6e1ff 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -631,7 +631,7 @@ ble_error_t GenericGap::connect( return _pal_gap.extended_create_connection( connectionParams.getFilterPolicy(), - (ble::pal::own_address_type_t::type)connectionParams.getOwnAddressType().value(), + connectionParams.getOwnAddressType(), (ble::peer_address_type_t::type)peerAddressType.value(), peerAddress, (ble::phy_set_t)connectionParams.getPhySet(), @@ -1762,7 +1762,7 @@ ble_error_t GenericGap::setAdvertisingParams( params.getMinPrimaryInterval().value(), params.getMaxPrimaryInterval().value(), params.getType(), - (pal::own_address_type_t::type) params.getOwnAddressType().value(), + params.getOwnAddressType(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), channel_map, @@ -1799,7 +1799,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( params.getMinPrimaryInterval().value(), params.getMaxPrimaryInterval().value(), channel_map, - (pal::own_address_type_t::type) params.getOwnAddressType().value(), + params.getOwnAddressType(), (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), params.getPeerAddress(), params.getPolicyMode(), @@ -2386,7 +2386,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) }; return _pal_gap.set_extended_scan_parameters( - (pal::own_address_type_t::type) params.get_own_address_type().value(), + params.get_own_address_type(), params.get_scanning_filter_policy(), params.get_scanning_phys(), active_scanning, @@ -2405,7 +2405,7 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) legacy_configuration.active_scanning, legacy_configuration.interval.value(), legacy_configuration.window.value(), - (pal::own_address_type_t::type) params.get_own_address_type().value(), + params.get_own_address_type(), params.get_scanning_filter_policy() ); } From 33ab365d2ccdeffebc1605e2e57ea90a1d7f0df9 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 13:42:16 +0000 Subject: [PATCH 197/361] advertising data --- features/FEATURE_BLE/ble/Gap.h | 53 +++++++++++----------------------- 1 file changed, 17 insertions(+), 36 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 22c815fbbd..921f011c69 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -87,44 +87,23 @@ * sending a scan request. If the broadcaster accepts scan requests, it can reply * with a scan response packet containing additional information. * - * @code - * // assuming gap has been initialized - * Gap& gap; + * Advertising parameters are updated using setAdvertisingParams(). The main + * advertising payload is updated using setAdvertisingPayload() and the scan response + * is updated using setAdvertisingScanResponse(). If the advertising is already active + * updated the data will take effect from the next advertising event. * - * // construct the packet to advertise - * GapAdvertisingData advertising_data; + * To create a valid advertising payload and scan response you may use + * AdvertisingDataBuilder(). You must first allocate memory and crate an mbed::Span and + * pass that into the AdvertisingDataBuilder which will only be able to add as much + * data as fits in the provided buffer. The builder will accept any size of the buffer + * but for the created data to be usable it must be smaller than the maximum data + * length returned from getMaxAdvertisingDataLength(). * - * // Add advertiser flags - * advertising_data.addFlags( - * GapAdvertisingData::LE_GENERAL_DISCOVERABLE | - * GapAdvertisingData::BREDR_NOT_SUPPORTED - * ); - * - * // Add the name of the device to the advertising data - * static const uint8_t device_name[] = "HRM"; - * advertising_data.addData( - * GapAdvertisingData::COMPLETE_LOCAL_NAME, - * device_name, - * sizeof(device_name) - * ); - * - * // set the advertising data in the gap instance, they will be used when - * // advertising starts. - * gap.setAdvertisingPayload(advertising_data); - * - * // Configure the advertising procedure - * GapAdvertisingParams advertising_params( - * GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED, // type of advertising - * GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000), // interval - * 0 // The advertising procedure will not timeout - * ); - * - * gap.setAdvertisingParams(advertising_params); - * - * // start the advertising procedure, the device will advertise its flag and the - * // name "HRM". Other peers will also be allowed to connect to it. - * gap.startAdvertising(); - * @endcode + * @note The maximum size of data depends on the controller and its support for + * extended advertising however even if the controller supports larger data lengths if + * you wish to be compatible with older devices you may wish to use legacy + * advertising and then should use LEGACY_ADVERTISING_MAX_SIZE instead of + * getMaxAdvertisingDataLength(). * * @par Extended advertising * @@ -1116,6 +1095,8 @@ public: /** Special advertising set handle used for the legacy advertising set. */ static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; + static const uint8_t LEGACY_ADVERTISING_MAX_SIZE = 0x1F; + /** Special advertising set handle used as return or parameter to signify an invalid handle. */ static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; From 7ea560a955c82e437a8c713a725d95134c1bd76b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 13:46:55 +0000 Subject: [PATCH 198/361] size clarification --- features/FEATURE_BLE/ble/Gap.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 921f011c69..9321c85560 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -102,8 +102,7 @@ * @note The maximum size of data depends on the controller and its support for * extended advertising however even if the controller supports larger data lengths if * you wish to be compatible with older devices you may wish to use legacy - * advertising and then should use LEGACY_ADVERTISING_MAX_SIZE instead of - * getMaxAdvertisingDataLength(). + * advertising and should not use payloads larger than LEGACY_ADVERTISING_MAX_SIZE. * * @par Extended advertising * From d8eb9de459f745bca432667dd92aba13ff159d5e Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 14:18:27 +0000 Subject: [PATCH 199/361] fix names --- features/FEATURE_BLE/ble/Gap.h | 3 ++- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 9321c85560..7fd907937d 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1094,6 +1094,7 @@ public: /** Special advertising set handle used for the legacy advertising set. */ static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; + /** Maximum advertising data length that can fit in a legacy PDU. */ static const uint8_t LEGACY_ADVERTISING_MAX_SIZE = 0x1F; /** Special advertising set handle used as return or parameter to signify an invalid handle. */ @@ -1730,7 +1731,7 @@ public: * @param params New advertising parameters. * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t setAdvertisingParams( + virtual ble_error_t setAdvertisingParameters( AdvHandle_t handle, const ble::AdvertisingParameters ¶ms ) { diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 02badf5017..7a7915f30f 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -103,7 +103,7 @@ public: /** @copydoc Gap::setAdvertisingParams */ - ble_error_t setAdvertisingParams( + ble_error_t setAdvertisingParameters( AdvHandle_t handle, const AdvertisingParameters ¶ms ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0394a6e1ff..57cf57eb56 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1735,7 +1735,7 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { return BLE_ERROR_NONE; } -ble_error_t GenericGap::setAdvertisingParams( +ble_error_t GenericGap::setAdvertisingParameters( AdvHandle_t handle, const AdvertisingParameters ¶ms ) { From 7aa1e951930425e3d85c59bdfa545130d67ed26e Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 14:24:10 +0000 Subject: [PATCH 200/361] BLE: merge ble::target_peer_address_type_t and advertising_peer_address_type_t --- features/FEATURE_BLE/ble/gap/Types.h | 11 +++++--- features/FEATURE_BLE/ble/pal/GapTypes.h | 26 +------------------ .../FEATURE_BLE/source/generic/GenericGap.cpp | 4 +-- 3 files changed, 10 insertions(+), 31 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index de3066cc7c..148c626d42 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -415,12 +415,15 @@ struct own_address_type_t : SafeEnum { own_address_type_t(type value) : SafeEnum(value) { } }; -struct target_peer_address_type_t : ble::SafeEnum { +struct target_peer_address_type_t : SafeEnum { enum type { - PUBLIC = 0, /**< Public Device Address or Public Identity Address. */ - RANDOM /**< Random Device Address or Random (static) Identity Address. */ + PUBLIC = 0x00, /**< Public Device Address or Public Identity Address. */ + PUBLIC_ADDRESS = 0x00, + + RANDOM = 0x01, /**< Random Device Address or Random (static) Identity Address. */ + RANDOM_ADDRESS = 0x01 }; - target_peer_address_type_t(type value) : ble::SafeEnum(value) { } + target_peer_address_type_t(type value) : SafeEnum(value) { } }; /** diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index aaf9b2f280..68f754c9e3 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -28,31 +28,7 @@ typedef ble::advertising_type_t advertising_type_t; typedef ble::own_address_type_t own_address_type_t; - -/** - * Type modeling the peer address type during direct advertising. - */ -struct advertising_peer_address_type_t : - SafeEnum { - enum type { - /** - * Public device address or identity address. - */ - PUBLIC_ADDRESS = 0x00, - - /** - * Random device address or random (static) identity address. - */ - RANDOM_ADDRESS = 0x01 - }; - - /** - * Construct a new instance of advertising_peer_address_type_t. - */ - advertising_peer_address_type_t(type value) : - SafeEnum(value) { } -}; - +typedef ble::target_peer_address_type_t advertising_peer_address_type_t; /** * Peer address type used during connection initiating. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 57cf57eb56..ce73789bdc 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1763,7 +1763,7 @@ ble_error_t GenericGap::setAdvertisingParameters( params.getMaxPrimaryInterval().value(), params.getType(), params.getOwnAddressType(), - (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), + params.getPeerAddressType(), params.getPeerAddress(), channel_map, params.getPolicyMode() @@ -1800,7 +1800,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( params.getMaxPrimaryInterval().value(), channel_map, params.getOwnAddressType(), - (pal::advertising_peer_address_type_t::type) params.getPeerAddressType().value(), + params.getPeerAddressType(), params.getPeerAddress(), params.getPolicyMode(), params.getTxPower(), From 3e72570c5277a12b4be7254de3da338b3cde4902 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 15 Nov 2018 14:32:32 +0000 Subject: [PATCH 201/361] move values out of GAP --- features/FEATURE_BLE/ble/BLETypes.h | 9 +++++++++ features/FEATURE_BLE/ble/Gap.h | 13 ++----------- features/FEATURE_BLE/source/generic/GenericGap.cpp | 8 ++++---- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 62e85e7679..47936d699a 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -43,6 +43,15 @@ void clamp(T& value, const R& min, const R& max) { } } +/** Special advertising set handle used for the legacy advertising set. */ +static const advertising_handle_t LEGACY_ADVERTISING_HANDLE = 0x00; + +/** Special advertising set handle used as return or parameter to signify an invalid handle. */ +static const advertising_handle_t INVALID_ADVERTISING_HANDLE = 0xFF; + +/** Maximum advertising data length that can fit in a legacy PDU. */ +static const uint8_t LEGACY_ADVERTISING_MAX_SIZE = 0x1F; + /** Features supported by the controller. * @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 6, Part B - 4.6 */ struct controller_supported_features_t : SafeEnum { diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 7fd907937d..ceb306b2a3 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1091,15 +1091,6 @@ public: /** Type of advertisement scanned. */ typedef ble::advertising_event_t AdvertisingEventType_t; - /** Special advertising set handle used for the legacy advertising set. */ - static const AdvHandle_t LEGACY_ADVERTISING_HANDLE = 0x00; - - /** Maximum advertising data length that can fit in a legacy PDU. */ - static const uint8_t LEGACY_ADVERTISING_MAX_SIZE = 0x1F; - - /** Special advertising set handle used as return or parameter to signify an invalid handle. */ - static const AdvHandle_t INVALID_ADVERTISING_HANDLE = 0xFF; - /** * Definition of the general handler of Gap related events. */ @@ -1695,7 +1686,7 @@ public: * by this function must be used for all other calls that accept an advertising handle. * When done with advertising, remove from the system using destroyAdvertisingSet(). * - * @note The exception is the LEGACY_ADVERTISING_HANDLE which may be used at any time. + * @note The exception is the ble::LEGACY_ADVERTISING_HANDLE which may be used at any time. * * @param[out] handle Advertising handle returned, valid only if function returned success. * @param parameters Advertising parameters for the newly created set. @@ -1714,7 +1705,7 @@ public: /** Remove the advertising set (resets its set parameters). The advertising set must not * be active. * - * @note LEGACY_ADVERTISING_HANDLE may not be destroyed. + * @note ble::LEGACY_ADVERTISING_HANDLE may not be destroyed. * * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index ce73789bdc..cc5d9f27e1 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1858,11 +1858,11 @@ ble_error_t GenericGap::setAdvertisingData( // handle special case of legacy advertising if (!is_extended_advertising_available()) { - if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { + if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } - if (payload.size() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) { + if (payload.size() > LEGACY_ADVERTISING_MAX_SIZE) { return BLE_ERROR_INVALID_PARAM; } @@ -1939,7 +1939,7 @@ ble_error_t GenericGap::startAdvertising( } if (!is_extended_advertising_available()) { - if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { + if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -1999,7 +1999,7 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { } if (!is_extended_advertising_available()) { - if (handle != Gap::LEGACY_ADVERTISING_HANDLE) { + if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } From 493c8580cc92df36dfbe609c9652ef1e690b97eb Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 14:35:52 +0000 Subject: [PATCH 202/361] BLE: cleanup of clock_accuracy_t --- features/FEATURE_BLE/ble/gap/Types.h | 62 +++++++++++----------------- 1 file changed, 23 insertions(+), 39 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 148c626d42..efc76d25b3 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -434,42 +434,42 @@ struct clock_accuracy_t : SafeEnum{ /** * 500 PPM */ - PPM_500 = 0x00, + PPM_500 = 0x00, /** * 250 PPM */ - PPM_250 = 0x01, + PPM_250 = 0x01, /** * 150 PPM */ - PPM_150 = 0x02, + PPM_150 = 0x02, /** * 100 PPM */ - PPM_100 = 0x03, + PPM_100 = 0x03, /** * 75 PPM */ - PPM_75 = 0x04, + PPM_75 = 0x04, /** * 50 PPM */ - PPM_50 = 0x05, + PPM_50 = 0x05, /** * 30 PPM */ - PPM_30 = 0x06, + PPM_30 = 0x06, /** * 20 PPM */ - PPM_20 = 0x07 + PPM_20 = 0x07 }; /** Get clock accuracy. @@ -477,45 +477,29 @@ struct clock_accuracy_t : SafeEnum{ * @return Parts per million as a number. */ uint16_t get_ppm() { - uint16_t ppm = 0; - switch(value()) { - case PPM_500: - ppm = 500; - break; - case PPM_250: - ppm = 250; - break; - case PPM_150: - ppm = 150; - break; - case PPM_100: - ppm = 100; - break; - case PPM_75: - ppm = 75; - break; - case PPM_50: - ppm = 50; - break; - case PPM_30: - ppm = 30; - break; - case PPM_20: - ppm = 20; - break; + case PPM_500: return 500; + case PPM_250: return 250; + case PPM_150: return 150; + case PPM_100: return 100; + case PPM_75: return 75; + case PPM_50: return 50; + case PPM_30: return 30; + case PPM_20: return 20; + default: return 0; } - - return ppm; } /** * Construct a new clock_accuracy_t value. */ - clock_accuracy_t(type value) : SafeEnum(value) { } + clock_accuracy_t(type value) : SafeEnum(value) { } - explicit clock_accuracy_t(uint8_t raw_value) : - SafeEnum(static_cast(raw_value)) { } + /** + * Construct a new clock_accuracy_t value from a raw value. + * @param raw_value The value of the clock accuracy. + */ + explicit clock_accuracy_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; /** From c1cd5ede84010cb171989d9491d4ec1ba6bf8db4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 14:42:48 +0000 Subject: [PATCH 203/361] BLE: Cleanup ble::connection_role_t. --- features/FEATURE_BLE/ble/gap/Types.h | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index efc76d25b3..872a9f16ee 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -520,12 +520,12 @@ struct connection_role_t :SafeEnum { * * @note A central is a scanner. */ - CENTRAL = 0x00, + CENTRAL = 0x00, /** * @see CENTRAL */ - MASTER = 0x00, + MASTER = 0x00, /** * Peripheral Role. @@ -535,26 +535,24 @@ struct connection_role_t :SafeEnum { * * @note A peripheral is a broadcaster. */ - PERIPHERAL = 0x01, + PERIPHERAL = 0x01, /** - * @see SLAVE + * @see PERIPHERAL */ - SLAVE = 0x01 + SLAVE = 0x01 }; /** * Construct a new instance of role_t. */ - connection_role_t(type value) : - SafeEnum(value) { } + connection_role_t(type value) : SafeEnum(value) { } /** * Explicit constructor from a raw value. * @param raw_value The role. */ - explicit connection_role_t(uint8_t raw_value) : - SafeEnum(raw_value) { } + explicit connection_role_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; } // namespace ble From 712336467457c89e2075b0516d4d859516a373f5 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 15:45:58 +0000 Subject: [PATCH 204/361] BLE: remove not required prefixes in ble::ConnectionParameters. --- .../ble/gap/ConnectionParameters.h | 133 ++++++++---------- 1 file changed, 60 insertions(+), 73 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index f9a6811758..d85ce867aa 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -34,7 +34,7 @@ class ConnectionParameters { public: ConnectionParameters() : _filterPolicy(initiator_filter_policy_t::NO_FILTER), - _ownAddressType(ble::own_address_type_t::PUBLIC) + _ownAddressType(own_address_type_t::PUBLIC) { for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { _scanInterval[i] = 4; @@ -52,9 +52,9 @@ public: /* setters */ ConnectionParameters &setScanParameters( - ble::scan_interval_t scanInterval, - ble::scan_window_t scanWindow, - ble::phy_t phy = ble::phy_t::LE_1M + scan_interval_t scanInterval, + scan_window_t scanWindow, + phy_t phy = phy_t::LE_1M ) { uint8_t phy_index = handlePhyToggle(phy, true); @@ -66,15 +66,13 @@ public: } ConnectionParameters &setConnectionParameters( - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t connectionSupervisionTimeout, - ble::phy_t phy = ble::phy_t::LE_1M, - ble::conn_event_length_t minEventLength = ble::conn_event_length_t(0), - ble::conn_event_length_t maxEventLength = ble::conn_event_length_t( - 0xFFFF - ) + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t connectionSupervisionTimeout, + phy_t phy = phy_t::LE_1M, + conn_event_length_t minEventLength = conn_event_length_t(0), + conn_event_length_t maxEventLength = conn_event_length_t(0xFFFF) ) { uint8_t phy_index = handlePhyToggle(phy, true); @@ -95,9 +93,7 @@ public: return *this; } - ConnectionParameters &setOwnAddressType( - ble::own_address_type_t ownAddress - ) + ConnectionParameters &setOwnAddressType(own_address_type_t ownAddress) { _ownAddressType = ownAddress; @@ -111,31 +107,23 @@ public: return *this; } - ConnectionParameters &togglePhy( - bool phy1M, - bool phy2M, - bool phyCoded - ) + ConnectionParameters &togglePhy(bool phy1M, bool phy2M, bool phyCoded) { - handlePhyToggle(ble::phy_t::LE_1M, phy1M); - handlePhyToggle(ble::phy_t::LE_2M, phy2M); - handlePhyToggle(ble::phy_t::LE_CODED, phyCoded); + handlePhyToggle(phy_t::LE_1M, phy1M); + handlePhyToggle(phy_t::LE_2M, phy2M); + handlePhyToggle(phy_t::LE_CODED, phyCoded); return *this; } - ConnectionParameters &disablePhy( - ble::phy_t phy = ble::phy_t::LE_1M - ) + ConnectionParameters &disablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, false); return *this; } - ConnectionParameters &enablePhy( - ble::phy_t phy = ble::phy_t::LE_1M - ) + ConnectionParameters &enablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, true); @@ -144,7 +132,7 @@ public: /* getters */ - ble::own_address_type_t getOwnAddressType() const + own_address_type_t getOwnAddressType() const { return _ownAddressType; } @@ -157,18 +145,18 @@ public: uint8_t getNumberOfEnabledPhys() const { return ( - _enabledPhy[ble::phy_t::LE_1M] * 1 + - _enabledPhy[ble::phy_t::LE_2M] * 1 + - _enabledPhy[ble::phy_t::LE_CODED] * 1 + _enabledPhy[phy_t::LE_1M] * 1 + + _enabledPhy[phy_t::LE_2M] * 1 + + _enabledPhy[phy_t::LE_CODED] * 1 ); } uint8_t getPhySet() const { - ble::phy_set_t set( - _enabledPhy[ble::phy_t::LE_1M], - _enabledPhy[ble::phy_t::LE_2M], - _enabledPhy[ble::phy_t::LE_CODED] + phy_set_t set( + _enabledPhy[phy_t::LE_1M], + _enabledPhy[phy_t::LE_2M], + _enabledPhy[phy_t::LE_CODED] ); return set.value(); } @@ -218,17 +206,16 @@ public: private: uint8_t getFirstEnabledIndex() const { - if (_enabledPhy[ble::phy_t::LE_1M]) { + if (_enabledPhy[phy_t::LE_1M]) { return 0; - } else if (_enabledPhy[ble::phy_t::LE_2M]) { + } else if (_enabledPhy[phy_t::LE_2M]) { return 1; - } else if (_enabledPhy[ble::phy_t::LE_CODED]) { + } else if (_enabledPhy[phy_t::LE_CODED]) { return 2; } /* this should never happen, it means you were trying to start a connection with a blank set * of paramters - you need to enabled at least one phy */ - MBED_ASSERT( - "Trying to use connection parameters without any PHY defined."); + MBED_ASSERT("Trying to use connection parameters without any PHY defined."); return 0; } @@ -238,7 +225,7 @@ private: * @param enable On or Off. * @return The index to the array of settings. */ - uint8_t handlePhyToggle(ble::phy_t phy, bool enable) + uint8_t handlePhyToggle(phy_t phy, bool enable) { uint8_t index = phy.value(); @@ -259,7 +246,7 @@ private: swapCodedAnd2M(); } - if (is_swapped && phy == ble::phy_t::LE_CODED) { + if (is_swapped && phy == phy_t::LE_CODED) { index -= 1; } @@ -269,46 +256,46 @@ private: bool isSwapped() const { return ( - _enabledPhy[ble::phy_t::LE_1M] && - !_enabledPhy[ble::phy_t::LE_2M] && - _enabledPhy[ble::phy_t::LE_CODED] + _enabledPhy[phy_t::LE_1M] && + !_enabledPhy[phy_t::LE_2M] && + _enabledPhy[phy_t::LE_CODED] ); } /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ void swapCodedAnd2M() { - uint16_t scanInterval = _scanInterval[ble::phy_t::LE_2M]; - uint16_t scanWindow = _scanWindow[ble::phy_t::LE_2M]; - uint16_t minConnectionInterval = _minConnectionInterval[ble::phy_t::LE_2M]; - uint16_t maxConnectionInterval = _maxConnectionInterval[ble::phy_t::LE_2M]; - uint16_t slaveLatency = _maxConnectionInterval[ble::phy_t::LE_2M]; - uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[ble::phy_t::LE_2M]; - uint16_t minEventLength = _minEventLength[ble::phy_t::LE_2M]; - uint16_t maxEventLength = _maxEventLength[ble::phy_t::LE_2M]; + uint16_t scanInterval = _scanInterval[phy_t::LE_2M]; + uint16_t scanWindow = _scanWindow[phy_t::LE_2M]; + uint16_t minConnectionInterval = _minConnectionInterval[phy_t::LE_2M]; + uint16_t maxConnectionInterval = _maxConnectionInterval[phy_t::LE_2M]; + uint16_t slaveLatency = _maxConnectionInterval[phy_t::LE_2M]; + uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[phy_t::LE_2M]; + uint16_t minEventLength = _minEventLength[phy_t::LE_2M]; + uint16_t maxEventLength = _maxEventLength[phy_t::LE_2M]; - _scanInterval[ble::phy_t::LE_2M] = _scanInterval[ble::phy_t::LE_CODED]; - _scanWindow[ble::phy_t::LE_2M] = _scanWindow[ble::phy_t::LE_CODED]; - _minConnectionInterval[ble::phy_t::LE_2M] = _minConnectionInterval[ble::phy_t::LE_CODED]; - _maxConnectionInterval[ble::phy_t::LE_2M] = _maxConnectionInterval[ble::phy_t::LE_CODED]; - _slaveLatency[ble::phy_t::LE_2M] = _slaveLatency[ble::phy_t::LE_CODED]; - _connectionSupervisionTimeout[ble::phy_t::LE_2M] = _connectionSupervisionTimeout[ble::phy_t::LE_CODED]; - _minEventLength[ble::phy_t::LE_2M] = _minEventLength[ble::phy_t::LE_CODED]; - _maxEventLength[ble::phy_t::LE_2M] = _maxEventLength[ble::phy_t::LE_CODED]; + _scanInterval[phy_t::LE_2M] = _scanInterval[phy_t::LE_CODED]; + _scanWindow[phy_t::LE_2M] = _scanWindow[phy_t::LE_CODED]; + _minConnectionInterval[phy_t::LE_2M] = _minConnectionInterval[phy_t::LE_CODED]; + _maxConnectionInterval[phy_t::LE_2M] = _maxConnectionInterval[phy_t::LE_CODED]; + _slaveLatency[phy_t::LE_2M] = _slaveLatency[phy_t::LE_CODED]; + _connectionSupervisionTimeout[phy_t::LE_2M] = _connectionSupervisionTimeout[phy_t::LE_CODED]; + _minEventLength[phy_t::LE_2M] = _minEventLength[phy_t::LE_CODED]; + _maxEventLength[phy_t::LE_2M] = _maxEventLength[phy_t::LE_CODED]; - _scanInterval[ble::phy_t::LE_CODED] = scanInterval; - _scanWindow[ble::phy_t::LE_CODED] = scanWindow; - _minConnectionInterval[ble::phy_t::LE_CODED] = minConnectionInterval; - _maxConnectionInterval[ble::phy_t::LE_CODED] = maxConnectionInterval; - _slaveLatency[ble::phy_t::LE_CODED] = slaveLatency; - _connectionSupervisionTimeout[ble::phy_t::LE_CODED] = connectionSupervisionTimeout; - _minEventLength[ble::phy_t::LE_CODED] = minEventLength; - _maxEventLength[ble::phy_t::LE_CODED] = maxEventLength; + _scanInterval[phy_t::LE_CODED] = scanInterval; + _scanWindow[phy_t::LE_CODED] = scanWindow; + _minConnectionInterval[phy_t::LE_CODED] = minConnectionInterval; + _maxConnectionInterval[phy_t::LE_CODED] = maxConnectionInterval; + _slaveLatency[phy_t::LE_CODED] = slaveLatency; + _connectionSupervisionTimeout[phy_t::LE_CODED] = connectionSupervisionTimeout; + _minEventLength[phy_t::LE_CODED] = minEventLength; + _maxEventLength[phy_t::LE_CODED] = maxEventLength; } private: initiator_filter_policy_t _filterPolicy; - ble::own_address_type_t _ownAddressType; + own_address_type_t _ownAddressType; uint16_t _scanInterval[MAX_PARAM_PHYS]; /* 0.625 ms */ uint16_t _scanWindow[MAX_PARAM_PHYS]; /* 0.625 ms */ From 6c75c53127f788807ddfde952b953cfce747dabe Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 16:08:52 +0000 Subject: [PATCH 205/361] BLE: Move gap events into ble namespace. --- features/FEATURE_BLE/ble/Gap.h | 26 +-- features/FEATURE_BLE/ble/gap/Events.h | 284 +++++++++++++++----------- 2 files changed, 176 insertions(+), 134 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index ceb306b2a3..b42922e805 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1100,9 +1100,7 @@ public: * * @param event Advertising report @see AdvertisingReportEvent_t for details. */ - void onAdvertisingReport( - const AdvertisingReportEvent &event - ) { + void onAdvertisingReport(const ble::AdvertisingReportEvent &event) { (void) event; } @@ -1110,9 +1108,7 @@ public: * * @param event Connection event @see ConnectionCompleteEvent_t for details. */ - void onConnectionComplete( - const ConnectionCompleteEvent &event - ) { + void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { (void)event; } @@ -1121,7 +1117,7 @@ public: * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. */ virtual void onPeriodicAdvertisingSyncEstablished( - const PeriodicAdvertisingSyncEstablishedEvent &event + const ble::PeriodicAdvertisingSyncEstablishedEvent &event ) { (void) event; } @@ -1131,28 +1127,27 @@ public: * @param event Periodic advertisement event. */ virtual void onPeriodicAdvertisingReportEvent( - const PeriodicAdvertisingReportEvent & event + const ble::PeriodicAdvertisingReportEvent & event ) { (void) event; } virtual void onPeriodicAdvertisingSyncLoss( - const PeriodicAdvertisingSyncLoss &event + const ble::PeriodicAdvertisingSyncLoss &event ) { (void) event; } /** Called when scan times out. */ - virtual void onScanTimeout(const ScanTimeoutEvent &) { } + virtual void onScanTimeout(const ble::ScanTimeoutEvent &) { } /** Called when advertising ends. * * @param event Advertising end event: @see AdvertisingEndEvent_t for details. */ - virtual void onAdvertisingEnd( - const AdvertisingEndEvent_t& event - ) { + virtual void onAdvertisingEnd(const ble::AdvertisingEndEvent_t& event) + { (void) event; } @@ -1160,9 +1155,8 @@ public: * * @param event Scan request event: @see ScanRequestEvent_t for details. */ - virtual void onScanRequest( - const ScanRequestEvent_t& event - ) { + virtual void onScanRequest(const ble::ScanRequestEvent_t& event) + { (void) event; } diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index d81e6f688a..6bd4b87b8f 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -21,6 +21,8 @@ #include "ble/BLETypes.h" #include "platform/Span.h" +namespace ble { + /** Event generated when an advertising packet is seen during passive scanning * or a scan response is received during active scanning. */ @@ -41,17 +43,17 @@ struct AdvertisingReportEvent { * @param advertisingData Advertising payload. */ AdvertisingReportEvent( - const ble::advertising_event_t &type, - const ble::peer_address_type_t &peerAddressType, - const ble::address_t &peerAddress, - const ble::phy_t &primaryPhy, - const ble::phy_t &secondaryPhy, - ble::advertising_sid_t SID, - ble::advertising_power_t txPower, - ble::rssi_t rssi, - ble::periodic_interval_t periodicInterval, - const ble::peer_address_type_t &directAddressType, - const ble::address_t &directAddress, + const advertising_event_t &type, + const peer_address_type_t &peerAddressType, + const address_t &peerAddress, + const phy_t &primaryPhy, + const phy_t &secondaryPhy, + advertising_sid_t SID, + advertising_power_t txPower, + rssi_t rssi, + periodic_interval_t periodicInterval, + const peer_address_type_t &directAddressType, + const address_t &directAddress, const mbed::Span &advertisingData ) : type(type), @@ -68,77 +70,89 @@ struct AdvertisingReportEvent { advertisingData(advertisingData) { } /** Get event type. */ - const ble::advertising_event_t &getType() const { + const advertising_event_t &getType() const + { return type; } /** Get peer address type. */ - const ble::peer_address_type_t &getPeerAddressType() const { + const peer_address_type_t &getPeerAddressType() const + { return peerAddressType; } /** Get peer address. */ - const ble::address_t &getPeerAddress() const { + const address_t &getPeerAddress() const + { return peerAddress; } /** Get primary PHY. */ - const ble::phy_t &getPrimaryPhy() const { + const phy_t &getPrimaryPhy() const + { return primaryPhy; } /** Get secondary PHY. */ - const ble::phy_t &getSecondaryPhy() const { + const phy_t &getSecondaryPhy() const + { return secondaryPhy; } /** Get advertising set identifier. */ - ble::advertising_sid_t getSID() const { + advertising_sid_t getSID() const + { return SID; } /** Get TX power. */ - ble::advertising_power_t getTxPower() const { + advertising_power_t getTxPower() const + { return txPower; } /** Get received signal strength. */ - ble::rssi_t getRssi() const { + rssi_t getRssi() const + { return rssi; } /** Get interval. */ - ble::periodic_interval_t getPeriodicInterval() const { + periodic_interval_t getPeriodicInterval() const + { return periodicInterval; } /** Get target address type in directed advertising. */ - const ble::peer_address_type_t &getDirectAddressType() const { + const peer_address_type_t &getDirectAddressType() const + { return directAddressType; } /** Get target address in directed advertising. */ - const ble::address_t &getDirectAddress() const { + const address_t &getDirectAddress() const + { return directAddress; } /** Get payload. */ - const mbed::Span &getAdvertisingData() const { + const mbed::Span &getAdvertisingData() const + { return advertisingData; } private: - ble::advertising_event_t type; - ble::peer_address_type_t peerAddressType; - ble::address_t const &peerAddress; - ble::phy_t primaryPhy; - ble::phy_t secondaryPhy; - ble::advertising_sid_t SID; - ble::advertising_power_t txPower; - ble::rssi_t rssi; - ble::periodic_interval_t periodicInterval; - ble::peer_address_type_t directAddressType; - const ble::address_t &directAddress; + advertising_event_t type; + peer_address_type_t peerAddressType; + address_t const &peerAddress; + phy_t primaryPhy; + phy_t secondaryPhy; + advertising_sid_t SID; + advertising_power_t txPower; + rssi_t rssi; + periodic_interval_t periodicInterval; + peer_address_type_t directAddressType; + const address_t &directAddress; mbed::Span advertisingData; }; @@ -161,15 +175,15 @@ struct ConnectionCompleteEvent { */ ConnectionCompleteEvent( ble_error_t status, - ble::connection_handle_t connectionHandle, - ble::connection_role_t ownRole, - const ble::peer_address_type_t &peerAddressType, - const ble::address_t &peerAddress, - const ble::address_t &localResolvablePrivateAddress, - const ble::address_t &peerResolvablePrivateAddress, - ble::conn_interval_t connectionInterval, - ble::slave_latency_t connectionLatency, - ble::supervision_timeout_t supervisionTimeout, + connection_handle_t connectionHandle, + connection_role_t ownRole, + const peer_address_type_t &peerAddressType, + const address_t &peerAddress, + const address_t &localResolvablePrivateAddress, + const address_t &peerResolvablePrivateAddress, + conn_interval_t connectionInterval, + slave_latency_t connectionLatency, + supervision_timeout_t supervisionTimeout, uint16_t masterClockAccuracy ) : status(status), @@ -185,72 +199,83 @@ struct ConnectionCompleteEvent { masterClockAccuracy(masterClockAccuracy) { } /** Get connection complete event status. */ - ble_error_t getStatus() const { + ble_error_t getStatus() const + { return status; } /** Get connection handle (valid only when successful). */ - ble::connection_handle_t getConnectionHandle() const { + connection_handle_t getConnectionHandle() const + { return connectionHandle; } /** Get own role. */ - ble::connection_role_t getOwnRole() const { + connection_role_t getOwnRole() const + { return ownRole; } /** Get peer address type. */ - const ble::peer_address_type_t &getPeerAddressType() const { + const peer_address_type_t &getPeerAddressType() const + { return peerAddressType; } /** Get peer address. */ - const ble::address_t &getPeerAddress() const { + const address_t &getPeerAddress() const + { return peerAddress; } /** Get get local resolvable random address if privacy is used. */ - const ble::address_t &getLocalResolvablePrivateAddress() const { + const address_t &getLocalResolvablePrivateAddress() const + { return localResolvablePrivateAddress; } /** Get peer resolvable private address if privacy is used. */ - const ble::address_t &getPeerResolvablePrivateAddress() const { + const address_t &getPeerResolvablePrivateAddress() const + { return peerResolvablePrivateAddress; } /** Get connection interval. */ - ble::conn_interval_t getConnectionInterval() const { + conn_interval_t getConnectionInterval() const + { return connectionInterval; } /** Get connection latency. */ - ble::slave_latency_t getConnectionLatency() const { + slave_latency_t getConnectionLatency() const + { return connectionLatency; } /** Get supervision timeout. */ - ble::supervision_timeout_t getSupervisionTimeout() const { + supervision_timeout_t getSupervisionTimeout() const + { return supervisionTimeout; } /** Get clock accuracy in parts per million. */ - uint16_t getMasterClockAccuracy() const { + uint16_t getMasterClockAccuracy() const + { return masterClockAccuracy; } private: - ble_error_t status; - ble::connection_handle_t connectionHandle; - ble::connection_role_t ownRole; - ble::peer_address_type_t peerAddressType; - const ble::address_t &peerAddress; - const ble::address_t &localResolvablePrivateAddress; - const ble::address_t &peerResolvablePrivateAddress; - ble::conn_interval_t connectionInterval; - ble::slave_latency_t connectionLatency; - ble::supervision_timeout_t supervisionTimeout; - uint16_t masterClockAccuracy; + ble_error_t status; + connection_handle_t connectionHandle; + connection_role_t ownRole; + peer_address_type_t peerAddressType; + const address_t &peerAddress; + const address_t &localResolvablePrivateAddress; + const address_t &peerResolvablePrivateAddress; + conn_interval_t connectionInterval; + slave_latency_t connectionLatency; + supervision_timeout_t supervisionTimeout; + uint16_t masterClockAccuracy; }; /** Event generated when we first receive a periodic advertisement. @@ -269,13 +294,13 @@ struct PeriodicAdvertisingSyncEstablishedEvent { */ PeriodicAdvertisingSyncEstablishedEvent( ble_error_t status, - ble::periodic_sync_handle_t syncHandle, - ble::advertising_sid_t sid, - const ble::peer_address_type_t &peerAddressType, - const ble::address_t &peerAddress, - const ble::phy_t &peerPhy, + periodic_sync_handle_t syncHandle, + advertising_sid_t sid, + const peer_address_type_t &peerAddressType, + const address_t &peerAddress, + const phy_t &peerPhy, uint16_t advertisingInterval, - const ble::clock_accuracy_t &peerClockAccuracy + const clock_accuracy_t &peerClockAccuracy ) : status(status), syncHandle(syncHandle), @@ -287,54 +312,62 @@ struct PeriodicAdvertisingSyncEstablishedEvent { peerClockAccuracy(peerClockAccuracy) { } /** Get sync establishment status. */ - ble_error_t getStatus() const { + ble_error_t getStatus() const + { return status; } /** Get periodic advertising sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { + periodic_sync_handle_t getSyncHandle() const + { return syncHandle; } /** Get advertising set identifier. */ - ble::advertising_sid_t getSid() const { + advertising_sid_t getSid() const + { return sid; } /** Get peer address type. */ - const ble::peer_address_type_t &getPeerAddressType() const { + const peer_address_type_t &getPeerAddressType() const + { return peerAddressType; } /** Get peer address. */ - const ble::address_t &getPeerAddress() const { + const address_t &getPeerAddress() const + { return peerAddress; } /** Get PHY used. */ - const ble::phy_t &getPeerPhy() const { + const phy_t &getPeerPhy() const + { return peerPhy; } /** Get interval. */ - uint16_t getAdvertisingInterval() const { + uint16_t getAdvertisingInterval() const + { return advertisingInterval; } /** Get clock accuracy in parts per million. */ - const ble::clock_accuracy_t &getPeerClockAccuracy() const { + const clock_accuracy_t &getPeerClockAccuracy() const + { return peerClockAccuracy; } private: ble_error_t status; - ble::periodic_sync_handle_t syncHandle; - ble::advertising_sid_t sid; - ble::peer_address_type_t peerAddressType; - const ble::address_t& peerAddress; - ble::phy_t peerPhy; + periodic_sync_handle_t syncHandle; + advertising_sid_t sid; + peer_address_type_t peerAddressType; + const address_t &peerAddress; + phy_t peerPhy; uint16_t advertisingInterval; - ble::clock_accuracy_t peerClockAccuracy; + clock_accuracy_t peerClockAccuracy; }; /** Event generated when periodic advertising packet is received. @@ -349,10 +382,10 @@ struct PeriodicAdvertisingReportEvent { * @param payload Periodic advertisement payload. */ PeriodicAdvertisingReportEvent( - ble::periodic_sync_handle_t syncHandle, - ble::advertising_power_t txPower, - ble::rssi_t rssi, - ble::advertising_data_status_t dataStatus, + periodic_sync_handle_t syncHandle, + advertising_power_t txPower, + rssi_t rssi, + advertising_data_status_t dataStatus, const mbed::Span &payload ) : syncHandle(syncHandle), @@ -362,35 +395,40 @@ struct PeriodicAdvertisingReportEvent { payload(payload) { } /** Get periodic advertising sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { + periodic_sync_handle_t getSyncHandle() const + { return syncHandle; } /** Get TX power as reported by the advertising packet. */ - ble::advertising_power_t getTxPower() const { + advertising_power_t getTxPower() const + { return txPower; } /** Get received signal strength. */ - ble::rssi_t getRssi() const { + rssi_t getRssi() const + { return rssi; } /** Get data completeness status. */ - const ble::advertising_data_status_t &getDataStatus() const { + const advertising_data_status_t &getDataStatus() const + { return dataStatus; } /** Get payload. */ - const mbed::Span &getPayload() const { + const mbed::Span &getPayload() const + { return payload; } private: - ble::periodic_sync_handle_t syncHandle; - ble::advertising_power_t txPower; - ble::rssi_t rssi; - ble::advertising_data_status_t dataStatus; + periodic_sync_handle_t syncHandle; + advertising_power_t txPower; + rssi_t rssi; + advertising_data_status_t dataStatus; mbed::Span payload; }; @@ -402,17 +440,18 @@ struct PeriodicAdvertisingSyncLoss { * @param syncHandle Periodic advertising sync handle. */ PeriodicAdvertisingSyncLoss( - ble::periodic_sync_handle_t syncHandle + periodic_sync_handle_t syncHandle ) : syncHandle(syncHandle) { } /** Get periodic sync handle. */ - ble::periodic_sync_handle_t getSyncHandle() const { + periodic_sync_handle_t getSyncHandle() const + { return syncHandle; } private: - ble::periodic_sync_handle_t syncHandle; + periodic_sync_handle_t syncHandle; }; /** Event generated when scan times out. @@ -430,8 +469,8 @@ struct AdvertisingEndEvent_t { * @param connected True if connection has been established. */ AdvertisingEndEvent_t( - ble::advertising_handle_t advHandle, - ble::connection_handle_t connection, + advertising_handle_t advHandle, + connection_handle_t connection, uint8_t completed_events, bool connected ) : @@ -441,28 +480,32 @@ struct AdvertisingEndEvent_t { connected(connected) { } /** Get advertising handle. */ - ble::advertising_handle_t getAdvHandle() const { + advertising_handle_t getAdvHandle() const + { return advHandle; } /** Get connection handle (valid only if connected successfully). */ - ble::connection_handle_t getConnection() const { + connection_handle_t getConnection() const + { return connection; } /** Get how many events advertising created. */ - uint8_t getCompleted_events() const { + uint8_t getCompleted_events() const + { return completed_events; } /** Has the advertising ended with a connection. */ - bool isConnected() const { + bool isConnected() const + { return connected; } private: - ble::advertising_handle_t advHandle; - ble::connection_handle_t connection; + advertising_handle_t advHandle; + connection_handle_t connection; uint8_t completed_events; bool connected; }; @@ -477,33 +520,38 @@ struct ScanRequestEvent_t { * @param peerAddress Peer address. */ ScanRequestEvent_t( - ble::advertising_handle_t advHandle, - const ble::peer_address_type_t &peerAddressType, - const ble::address_t &peerAddress + advertising_handle_t advHandle, + const peer_address_type_t &peerAddressType, + const address_t &peerAddress ) : advHandle(advHandle), peerAddressType(peerAddressType), peerAddress(peerAddress) { } /** Get advertising handle. */ - ble::advertising_handle_t getAdvHandle() const { + advertising_handle_t getAdvHandle() const + { return advHandle; } /** Get peer address type. */ - const ble::peer_address_type_t &getPeerAddressType() const { + const peer_address_type_t &getPeerAddressType() const + { return peerAddressType; } /** Get peer address. */ - const ble::address_t &getPeerAddress() const { + const address_t &getPeerAddress() const + { return peerAddress; } private: - ble::advertising_handle_t advHandle; - ble::peer_address_type_t peerAddressType; - const ble::address_t &peerAddress; + advertising_handle_t advHandle; + peer_address_type_t peerAddressType; + const address_t &peerAddress; }; +} // namespace ble + #endif //BLE_GAP_EVENTS_H From 46815cc371a98a5904091bb1a3672559c5c53fbc Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 16:09:25 +0000 Subject: [PATCH 206/361] BLE: remove ble:: prefixes in ble::ScanParameters. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 770926605a..3312a47f77 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -32,9 +32,6 @@ namespace ble { class ScanParameters { public: - typedef ble::scan_window_t scan_window_t; - typedef ble::scan_interval_t scan_interval_t; - struct phy_configuration_t { phy_configuration_t( scan_window_t scan_interval, @@ -57,7 +54,7 @@ public: ScanParameters() : own_address_type(own_address_type_t::PUBLIC), scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), - phys(ble::phy_set_t::PHY_SET_1M), + phys(phy_set_t::PHY_SET_1M), phy_1m_configuration( scan_interval_t::min(), scan_window_t::min(), true ), @@ -77,13 +74,13 @@ public: return own_address_type; } - ScanParameters& set_scanning_filter_policy(ble::scanning_filter_policy_t filter_policy) + ScanParameters& set_scanning_filter_policy(scanning_filter_policy_t filter_policy) { scanning_filter_policy = filter_policy; return *this; } - ble::scanning_filter_policy_t get_scanning_filter_policy() const + scanning_filter_policy_t get_scanning_filter_policy() const { return scanning_filter_policy; } @@ -95,7 +92,7 @@ public: return *this; } - ble::phy_set_t get_scanning_phys() const + phy_set_t get_scanning_phys() const { return phys; } @@ -138,9 +135,9 @@ public: private: own_address_type_t own_address_type; - ble::scanning_filter_policy_t scanning_filter_policy; + scanning_filter_policy_t scanning_filter_policy; - ble::phy_set_t phys; + phy_set_t phys; phy_configuration_t phy_1m_configuration; phy_configuration_t phy_coded_configuration; From 5f435debd0adcc23f4a2a95b3d17eb217487f76a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 16:10:39 +0000 Subject: [PATCH 207/361] BLE: remove ble:: prefixes in ble::AdvertisingParameters. --- .../ble/gap/AdvertisingParameters.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 942f504254..ca8ce80216 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -37,7 +37,7 @@ namespace ble { * Parameters defining the advertising process. * * Advertising parameters for legacy advertising are a triplet of three value: - * - The Advertising mode modelled after ble::advertising_type_t. It defines + * - The Advertising mode modelled after advertising_type_t. It defines * if the device is connectable and scannable. This value can be set at * construction time, updated with setAdvertisingType() and queried by * getAdvertisingType(). @@ -80,11 +80,11 @@ public: _advType(advType), _minInterval(minInterval), _maxInterval(maxInterval), - _peerAddressType(ble::target_peer_address_type_t::PUBLIC), - _ownAddressType(ble::own_address_type_t::PUBLIC), + _peerAddressType(target_peer_address_type_t::PUBLIC), + _ownAddressType(own_address_type_t::PUBLIC), _policy(advertising_filter_policy_t::NO_FILTER), - _primaryPhy(ble::phy_t::LE_1M), - _secondaryPhy(ble::phy_t::LE_1M), + _primaryPhy(phy_t::LE_1M), + _secondaryPhy(phy_t::LE_1M), _peerAddress(), _txPower(127), _maxSkip(0), @@ -283,7 +283,7 @@ public: * * @return Policy used. */ - ble::advertising_filter_policy_t getPolicyMode() const + advertising_filter_policy_t getPolicyMode() const { return _policy; } @@ -298,7 +298,7 @@ public: * * @return A reference to this. */ - AdvertisingParameters &setPhy(ble::phy_t primaryPhy, ble::phy_t secondaryPhy) + AdvertisingParameters &setPhy(phy_t primaryPhy, phy_t secondaryPhy) { _primaryPhy = primaryPhy; _secondaryPhy = secondaryPhy; @@ -309,7 +309,7 @@ public: * * @return PHY used for primary advertising. */ - ble::phy_t getPrimaryPhy() const + phy_t getPrimaryPhy() const { return _primaryPhy; } @@ -318,7 +318,7 @@ public: * * @return PHY used for secondary advertising. */ - ble::phy_t getSecondaryPhy() const + phy_t getSecondaryPhy() const { return _secondaryPhy; } From 6de585f7bf3ed2c76dddd8404b88876f71f96c9a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 20:52:07 +0000 Subject: [PATCH 208/361] BLE: rename Gap::IsFeatureSupported into Gap::isFeatureSupported --- features/FEATURE_BLE/ble/Gap.h | 4 +--- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index b42922e805..8525dc7f22 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1651,9 +1651,7 @@ public: * @param feature Feature to check. * @return True if feature is supported. */ - bool IsFeatureSupported( - ControllerSupportedFeatures_t feature - ); + bool isFeatureSupported(ble::controller_supported_features_t feature); /* advertising */ diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 7a7915f30f..ce16e24b0d 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -78,7 +78,7 @@ public: /** @copydoc Gap::IsFeatureSupported */ - bool IsFeatureSupported( + bool isFeatureSupported( ble::controller_supported_features_t feature ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index cc5d9f27e1..ff8ad61065 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -444,7 +444,7 @@ GenericGap::~GenericGap() { } -bool GenericGap::IsFeatureSupported( +bool GenericGap::isFeatureSupported( ble::controller_supported_features_t feature ) { return _pal_gap.is_feature_supported(feature); @@ -2615,7 +2615,7 @@ void GenericGap::use_non_deprecated_scan_api() const bool GenericGap::is_extended_advertising_available() { - return IsFeatureSupported( + return isFeatureSupported( ble::controller_supported_features_t::LE_EXTENDED_ADVERTISING ); } From d3c26f428333bc2257d92169a52ad4ae32da2e7f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 20:54:02 +0000 Subject: [PATCH 209/361] BLE: rename functions that trap concurrent use of incorect GAP APIs --- features/FEATURE_BLE/ble/Gap.h | 8 ++++---- features/FEATURE_BLE/ble/generic/GenericGap.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 14 +++++++------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8525dc7f22..77a8e174fe 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1889,7 +1889,7 @@ public: virtual ble_error_t setScanParameters( const ble::ScanParameters& params ) { - use_non_deprecated_scan_api(); + useVersionTwoAPI(); /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; }; @@ -1912,7 +1912,7 @@ public: ble::scan_duration_t duration = ble::scan_duration_t(0), ble::scan_period_t period = ble::scan_period_t(0) ) { - use_non_deprecated_scan_api(); + useVersionTwoAPI(); /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; }; @@ -2035,12 +2035,12 @@ protected: /** Can only be called if use_non_deprecated_scan_api() hasn't been called. * This guards against mixed use of deprecated and nondeprecated API. */ - virtual void use_deprecated_scan_api() const { } + virtual void useVersionOneAPI() const { } /** Can only be called if use_deprecated_scan_api() hasn't been called. * This guards against mixed use of deprecated and nondeprecated API. */ - virtual void use_non_deprecated_scan_api() const { } + virtual void useVersionTwoAPI() const { } public: diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index ce16e24b0d..cbffa591f1 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -574,9 +574,9 @@ private: void on_address_rotation_timeout(); - virtual void use_deprecated_scan_api() const; + virtual void useVersionOneAPI() const; - virtual void use_non_deprecated_scan_api() const; + virtual void useVersionTwoAPI() const; /* implements pal::Gap::EventHandler */ private: diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index ff8ad61065..d2ef8b4edc 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -942,7 +942,7 @@ ble_error_t GenericGap::setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) { - use_deprecated_scan_api(); + useVersionOneAPI(); if (mode > Gap::SCAN_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; @@ -969,7 +969,7 @@ Gap::AdvertisingPolicyMode_t GenericGap::getAdvertisingPolicyMode(void) const Gap::ScanningPolicyMode_t GenericGap::getScanningPolicyMode(void) const { - use_deprecated_scan_api(); + useVersionOneAPI(); return (ScanningPolicyMode_t) _scanning_filter_policy.value(); } @@ -980,7 +980,7 @@ Gap::InitiatorPolicyMode_t GenericGap::getInitiatorPolicyMode(void) const ble_error_t GenericGap::startRadioScan(const GapScanningParams &scanningParams) { - use_deprecated_scan_api(); + useVersionOneAPI(); if (is_scan_params_valid(&scanningParams) == false) { return BLE_ERROR_INVALID_PARAM; @@ -2367,7 +2367,7 @@ void GenericGap::on_scan_request_received( ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) { - use_non_deprecated_scan_api(); + useVersionTwoAPI(); if (is_extended_advertising_available()) { bool active_scanning[] = { @@ -2417,7 +2417,7 @@ ble_error_t GenericGap::startScan( scan_period_t period ) { - use_non_deprecated_scan_api(); + useVersionTwoAPI(); if(_privacy_enabled && _central_privacy_configuration.use_non_resolvable_random_address) { @@ -2597,7 +2597,7 @@ uint8_t GenericGap::getMaxPeriodicAdvertiserListSize() return _pal_gap.read_periodic_advertiser_list_size(); } -void GenericGap::use_deprecated_scan_api() const +void GenericGap::useVersionOneAPI() const { if (_non_deprecated_scan_api_used) { MBED_ERROR(mixed_scan_api_error, "Use of deprecated scan API with up to date API"); @@ -2605,7 +2605,7 @@ void GenericGap::use_deprecated_scan_api() const _deprecated_scan_api_used = true; } -void GenericGap::use_non_deprecated_scan_api() const +void GenericGap::useVersionTwoAPI() const { if (_deprecated_scan_api_used) { MBED_ERROR(mixed_scan_api_error, "Use of up to date scan API with deprecated API"); From fa4aa8f068f9a1fae3c9527681efdd8640e4a908 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 20:55:39 +0000 Subject: [PATCH 210/361] BLE: remove inner V2 typedef in Gap class. --- features/FEATURE_BLE/ble/Gap.h | 53 ++++++------------- features/FEATURE_BLE/ble/generic/GenericGap.h | 32 +++++------ .../FEATURE_BLE/source/generic/GenericGap.cpp | 36 ++++++------- 3 files changed, 49 insertions(+), 72 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 77a8e174fe..2c799fe97a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -495,10 +495,6 @@ public: unsigned connected : 1; }; - /** Enumeration of controller supported features. - */ - typedef ble::controller_supported_features_t ControllerSupportedFeatures_t; - /** * Opaque value type representing a connection handle. * @@ -519,16 +515,6 @@ public: */ typedef ble::peer_address_type_t PeerAddressType_t; - /** - * Enumeration of own address types - */ - typedef ble::own_address_type_t OwnAddressType_t; - - /** - * Enumeration of peer address types - */ - typedef ble::target_peer_address_type_t TargetPeerAddressType_t; - /** * Enumeration of BLE PHY */ @@ -1082,15 +1068,6 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; - /** Advertising handle used to identify advertising sets. */ - typedef ble::advertising_handle_t AdvHandle_t; - - /** Advertising handle used to identify periodic advertising sets. */ - typedef ble::periodic_sync_handle_t PeriodicSyncHandle_t; - - /** Type of advertisement scanned. */ - typedef ble::advertising_event_t AdvertisingEventType_t; - /** * Definition of the general handler of Gap related events. */ @@ -1447,7 +1424,7 @@ public: * a connection event. */ virtual ble_error_t connect( - TargetPeerAddressType_t peerAddressType, + ble::target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ble::ConnectionParameters &connectionParams ) { @@ -1685,7 +1662,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t createAdvertisingSet( - AdvHandle_t *handle, + ble::advertising_handle_t *handle, const ble::AdvertisingParameters ¶meters ) { @@ -1702,7 +1679,7 @@ public: * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t destroyAdvertisingSet(AdvHandle_t handle) { + virtual ble_error_t destroyAdvertisingSet(ble::advertising_handle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; @@ -1715,7 +1692,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingParameters( - AdvHandle_t handle, + ble::advertising_handle_t handle, const ble::AdvertisingParameters ¶ms ) { (void) handle; @@ -1732,7 +1709,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingPayload( - AdvHandle_t handle, + ble::advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation = false ) @@ -1752,7 +1729,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingScanResponse( - AdvHandle_t handle, + ble::advertising_handle_t handle, mbed::Span response, bool minimiseFragmentation = false ) @@ -1772,7 +1749,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t startAdvertising( - AdvHandle_t handle, + ble::advertising_handle_t handle, ble::adv_duration_t maxDuration = ble::adv_duration_t(0), uint8_t maxEvents = 0 ) @@ -1789,7 +1766,7 @@ public: * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t stopAdvertising(AdvHandle_t handle) { + virtual ble_error_t stopAdvertising(ble::advertising_handle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; @@ -1800,7 +1777,7 @@ public: * @param handle Advertising set handle. * @return True if advertising is active on this set. */ - virtual bool isAdvertisingActive(AdvHandle_t handle) { + virtual bool isAdvertisingActive(ble::advertising_handle_t handle) { return false; } @@ -1813,7 +1790,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setPeriodicAdvertisingParameters( - AdvHandle_t handle, + ble::advertising_handle_t handle, ble::periodic_interval_t periodicAdvertisingIntervalMin, ble::periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower = true @@ -1833,7 +1810,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setPeriodicAdvertisingPayload( - AdvHandle_t handle, + ble::advertising_handle_t handle, mbed::Span payload ) { (void) handle; @@ -1848,7 +1825,7 @@ public: * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle) + virtual ble_error_t startPeriodicAdvertising(ble::advertising_handle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1860,7 +1837,7 @@ public: * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. */ - virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle) + virtual ble_error_t stopPeriodicAdvertising(ble::advertising_handle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1872,7 +1849,7 @@ public: * @param handle Advertising set handle. * @return True if periodic advertising is active on this set. */ - virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle) + virtual bool isPeriodicAdvertisingActive(ble::advertising_handle_t handle) { (void) handle; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1973,7 +1950,7 @@ public: * @return BLE_ERROR_NONE on success. */ virtual ble_error_t terminateSync( - PeriodicSyncHandle_t handle + ble::periodic_sync_handle_t handle ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index cbffa591f1..9193ca4b95 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -93,25 +93,25 @@ public: /** @copydoc Gap::createAdvertisingSet */ ble_error_t createAdvertisingSet( - AdvHandle_t *handle, + advertising_handle_t *handle, const AdvertisingParameters ¶meters ); /** @copydoc Gap::destroyAdvertisingSet */ - ble_error_t destroyAdvertisingSet(AdvHandle_t handle); + ble_error_t destroyAdvertisingSet(advertising_handle_t handle); /** @copydoc Gap::setAdvertisingParams */ ble_error_t setAdvertisingParameters( - AdvHandle_t handle, + advertising_handle_t handle, const AdvertisingParameters ¶ms ); /** @copydoc Gap::setAdvertisingPayload */ ble_error_t setAdvertisingPayload( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation ); @@ -119,7 +119,7 @@ public: /** @copydoc Gap::setAdvertisingScanResponse */ ble_error_t setAdvertisingScanResponse( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span response, bool minimiseFragmentation ); @@ -127,23 +127,23 @@ public: /** @copydoc Gap::startAdvertising */ ble_error_t startAdvertising( - AdvHandle_t handle, + advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents ); /** @copydoc Gap::stopAdvertising */ - ble_error_t stopAdvertising(AdvHandle_t handle); + ble_error_t stopAdvertising(advertising_handle_t handle); /** @copydoc Gap::isAdvertisingActive */ - bool isAdvertisingActive(AdvHandle_t handle); + bool isAdvertisingActive(advertising_handle_t handle); /** @copydoc Gap::setPeriodicAdvertisingParameters */ virtual ble_error_t setPeriodicAdvertisingParameters( - AdvHandle_t handle, + advertising_handle_t handle, periodic_interval_t periodicAdvertisingIntervalMin, periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower @@ -152,21 +152,21 @@ public: /** @copydoc Gap::setPeriodicAdvertisingPayload */ virtual ble_error_t setPeriodicAdvertisingPayload( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload ); /** @copydoc Gap::startPeriodicAdvertising */ - virtual ble_error_t startPeriodicAdvertising(AdvHandle_t handle); + virtual ble_error_t startPeriodicAdvertising(advertising_handle_t handle); /** @copydoc Gap::stopPeriodicAdvertising */ - virtual ble_error_t stopPeriodicAdvertising(AdvHandle_t handle); + virtual ble_error_t stopPeriodicAdvertising(advertising_handle_t handle); /** @copydoc Gap::isPeriodicAdvertisingActive */ - virtual bool isPeriodicAdvertisingActive(AdvHandle_t handle); + virtual bool isPeriodicAdvertisingActive(advertising_handle_t handle); /** @copydoc Gap::setScanParameters */ @@ -203,7 +203,7 @@ public: /** @copydoc Gap::terminateSync */ - virtual ble_error_t terminateSync(PeriodicSyncHandle_t handle); + virtual ble_error_t terminateSync(periodic_sync_handle_t handle); /** @copydoc Gap::addDeviceToPeriodicAdvertiserList */ @@ -518,7 +518,7 @@ public: private: ble_error_t setAdvertisingData( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation, bool scan_response @@ -725,7 +725,7 @@ private: private: ble_error_t setExtendedAdvertisingParameters( - AdvHandle_t handle, + advertising_handle_t handle, const AdvertisingParameters ¶meters ); diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index d2ef8b4edc..302a2d0376 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1588,7 +1588,7 @@ void GenericGap::update_random_address() /* ignore the error, if it fails to cycle because it's connectable */ _pal_gap.set_advertising_set_random_address( - (AdvHandle_t)i, + (advertising_handle_t)i, address ); } @@ -1670,7 +1670,7 @@ uint8_t GenericGap::getMaxAdvertisingDataLength() } ble_error_t GenericGap::createAdvertisingSet( - AdvHandle_t *handle, + advertising_handle_t *handle, const AdvertisingParameters ¶meters ) { @@ -1701,7 +1701,7 @@ ble_error_t GenericGap::createAdvertisingSet( return BLE_ERROR_NO_MEM; } -ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { +ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) { if (is_extended_advertising_available()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1736,7 +1736,7 @@ ble_error_t GenericGap::destroyAdvertisingSet(AdvHandle_t handle) { } ble_error_t GenericGap::setAdvertisingParameters( - AdvHandle_t handle, + advertising_handle_t handle, const AdvertisingParameters ¶ms ) { if (handle >= getMaxAdvertisingSetNumber()) { @@ -1774,7 +1774,7 @@ ble_error_t GenericGap::setAdvertisingParameters( } ble_error_t GenericGap::setExtendedAdvertisingParameters( - AdvHandle_t handle, + advertising_handle_t handle, const AdvertisingParameters ¶ms ) { @@ -1813,7 +1813,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( } ble_error_t GenericGap::setAdvertisingPayload( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation ) { @@ -1821,7 +1821,7 @@ ble_error_t GenericGap::setAdvertisingPayload( } ble_error_t GenericGap::setAdvertisingScanResponse( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span response, bool minimiseFragmentation ) { @@ -1829,7 +1829,7 @@ ble_error_t GenericGap::setAdvertisingScanResponse( } ble_error_t GenericGap::setAdvertisingData( - AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation, bool scan_response @@ -1862,7 +1862,7 @@ ble_error_t GenericGap::setAdvertisingData( return BLE_ERROR_INVALID_PARAM; } - if (payload.size() > LEGACY_ADVERTISING_MAX_SIZE) { + if (payload.size() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) { return BLE_ERROR_INVALID_PARAM; } @@ -1924,7 +1924,7 @@ ble_error_t GenericGap::setAdvertisingData( } ble_error_t GenericGap::startAdvertising( - AdvHandle_t handle, + advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents ) { @@ -1989,7 +1989,7 @@ ble_error_t GenericGap::startAdvertising( return error; } -ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { +ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) { if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2019,7 +2019,7 @@ ble_error_t GenericGap::stopAdvertising(AdvHandle_t handle) { ); } -bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { +bool GenericGap::isAdvertisingActive(advertising_handle_t handle) { if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2028,7 +2028,7 @@ bool GenericGap::isAdvertisingActive(AdvHandle_t handle) { } ble_error_t GenericGap::setPeriodicAdvertisingParameters( - Gap::AdvHandle_t handle, + advertising_handle_t handle, periodic_interval_t periodicAdvertisingIntervalMin, periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower @@ -2059,7 +2059,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( } ble_error_t GenericGap::setPeriodicAdvertisingPayload( - Gap::AdvHandle_t handle, + advertising_handle_t handle, mbed::Span payload ) { @@ -2116,7 +2116,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( return BLE_ERROR_NONE; } -ble_error_t GenericGap::startPeriodicAdvertising(Gap::AdvHandle_t handle) +ble_error_t GenericGap::startPeriodicAdvertising(advertising_handle_t handle) { if (handle == LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; @@ -2147,7 +2147,7 @@ ble_error_t GenericGap::startPeriodicAdvertising(Gap::AdvHandle_t handle) return BLE_ERROR_NONE; } -ble_error_t GenericGap::stopPeriodicAdvertising(Gap::AdvHandle_t handle) +ble_error_t GenericGap::stopPeriodicAdvertising(advertising_handle_t handle) { if (handle == LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; @@ -2175,7 +2175,7 @@ ble_error_t GenericGap::stopPeriodicAdvertising(Gap::AdvHandle_t handle) return BLE_ERROR_NONE; } -bool GenericGap::isPeriodicAdvertisingActive(Gap::AdvHandle_t handle) +bool GenericGap::isPeriodicAdvertisingActive(advertising_handle_t handle) { if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; @@ -2516,7 +2516,7 @@ ble_error_t GenericGap::cancelCreateSync() return _pal_gap.cancel_periodic_advertising_create_sync(); } -ble_error_t GenericGap::terminateSync(Gap::PeriodicSyncHandle_t handle) +ble_error_t GenericGap::terminateSync(periodic_sync_handle_t handle) { if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; From c165bd98b715d11be9ddabd3e8f235a7f6a6bb8c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 21:19:40 +0000 Subject: [PATCH 211/361] BLE: Add explicit constructor for Duration that accepts millisecond in input. --- features/FEATURE_BLE/ble/common/Duration.h | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index ce4588ec1d..f37a03025e 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -18,6 +18,7 @@ #define BLE_COMMON_DURATION_H_ #include +#include #include "platform/mbed_assert.h" namespace ble { @@ -62,6 +63,11 @@ struct Duration { MBED_STATIC_ASSERT(OtherTB >= TB && (OtherTB % TB) == 0, "Incompatible units"); } + template + explicit Duration(Duration other_ms, void* = NULL) : + duration(clamp(((other_ms.value() * 1000) + TB - 1) / TB)) + { } + Rep value() { return duration; } From 7d7ccea827157b0b8d9a635126a9667171a0188b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 15 Nov 2018 22:29:38 +0000 Subject: [PATCH 212/361] BLE: clean separation between GAP v1 and GAP v2 API. --- features/FEATURE_BLE/ble/Gap.h | 1264 ++++++++--------- features/FEATURE_BLE/ble/generic/GenericGap.h | 18 +- features/FEATURE_BLE/source/Gap.cpp | 237 ++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 22 +- 4 files changed, 812 insertions(+), 729 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 2c799fe97a..0816c82b81 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -269,6 +269,561 @@ * controller or by the peer. */ class Gap { + +public: + + /** + * Definition of the general handler of Gap related events. + */ + struct EventHandler { + /** Called when a scanning device request a scan response. + * + * @param event Scan request event: @see ScanRequestEvent_t for details. + */ + virtual void onScanRequest(const ble::ScanRequestEvent_t& event) { } + + /** Called when advertising ends. + * + * @param event Advertising end event: @see AdvertisingEndEvent_t for details. + */ + virtual void onAdvertisingEnd(const ble::AdvertisingEndEvent_t& event) + { } + + /** Called when scanning reads an advertising packet during passive scan or receives + * a scan response during an active scan. + * + * @param event Advertising report @see AdvertisingReportEvent_t for details. + */ + void onAdvertisingReport(const ble::AdvertisingReportEvent &event) { } + + /** Called when scan times out. + */ + virtual void onScanTimeout(const ble::ScanTimeoutEvent &) { } + + /** Called when first advertising packet in periodic advertising is received. + * + * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. + */ + virtual void onPeriodicAdvertisingSyncEstablished( + const ble::PeriodicAdvertisingSyncEstablishedEvent &event + ) { } + + /** Called when a periodic advertising packet is received. + * + * @param event Periodic advertisement event. + */ + virtual void onPeriodicAdvertisingReportEvent( + const ble::PeriodicAdvertisingReportEvent & event + ) { } + + virtual void onPeriodicAdvertisingSyncLoss( + const ble::PeriodicAdvertisingSyncLoss &event + ) { } + + /** Called when connection attempt ends. + * + * @param event Connection event @see ConnectionCompleteEvent_t for details. + */ + void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { } + + /** + * Function invoked when the current transmitter and receiver PHY have + * been read for a given connection. + * + * @param status Status of the operation: BLE_ERROR_NONE in case of + * success or an appropriate error code. + * + * @param connectionHandle: The handle of the connection for which the + * PHYs have been read. + * + * @param txPhy PHY used by the transmitter. + * + * @param rxPhy PHY used by the receiver. + */ + virtual void onReadPhy( + ble_error_t status, + ble::connection_handle_t connectionHandle, + ble::phy_t txPhy, + ble::phy_t rxPhy + ) { } + + /** + * Function invoked when the update process of the PHY has been completed. + * + * The process can be initiated by a call to the function setPhy, the + * local bluetooth subsystem or the peer. + * + * @param status Status of the operation: BLE_ERROR_NONE in case of + * success or an appropriate error code. + * + * @param connectionHandle: The handle of the connection on which the + * operation was made. + * + * @param txPhy PHY used by the transmitter. + * + * @param rxPhy PHY used by the receiver. + * + * @note Success doesn't mean the PHY has been updated it means both + * ends have negotiated the best PHY according to their configuration and + * capabilities. The PHY currently used are present in the txPhy and + * rxPhy parameters. + */ + virtual void onPhyUpdateComplete( + ble_error_t status, + ble::connection_handle_t connectionHandle, + ble::phy_t txPhy, + ble::phy_t rxPhy + ) { } + + protected: + /** + * Prevent polymorphic deletion and avoid unnecessary virtual destructor + * as the Gap class will never delete the instance it contains. + */ + ~EventHandler() { } + }; + + /** + * Representation of a whitelist of addresses. + */ + struct Whitelist_t { + /** + * Pointer to the array of the addresses composing the whitelist. + */ + BLEProtocol::Address_t *addresses; + + /** + * Number addresses in this whitelist. + */ + uint8_t size; + + /** + * Capacity of the array holding the addresses. + */ + uint8_t capacity; + }; + + + /** Check controller support for a specific feature. + * + * @param feature Feature to check. + * @return True if feature is supported. + */ + virtual bool isFeatureSupported(ble::controller_supported_features_t feature) + { + // TODO: deal with legacy implementation + } + + /* advertising */ + + /** Return currently available number of supported advertising sets. + * This may change at runtime. + * + * @return Number of advertising sets that may be created at the same time. + */ + virtual uint8_t getMaxAdvertisingSetNumber(); + + /** Return maximum advertising data length supported. + * + * @return Maximum advertising data length supported. + */ + virtual uint8_t getMaxAdvertisingDataLength(); + + /** Create an advertising set and apply the passed in parameters. The handle returned + * by this function must be used for all other calls that accept an advertising handle. + * When done with advertising, remove from the system using destroyAdvertisingSet(). + * + * @note The exception is the ble::LEGACY_ADVERTISING_HANDLE which may be used at any time. + * + * @param[out] handle Advertising handle returned, valid only if function returned success. + * @param parameters Advertising parameters for the newly created set. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createAdvertisingSet( + ble::advertising_handle_t *handle, + const ble::AdvertisingParameters ¶meters + ); + + /** Remove the advertising set (resets its set parameters). The advertising set must not + * be active. + * + * @note ble::LEGACY_ADVERTISING_HANDLE may not be destroyed. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t destroyAdvertisingSet(ble::advertising_handle_t handle); + + /** Set advertising parameters of an existing set. + * + * @param handle Advertising set handle. + * @param params New advertising parameters. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingParameters( + ble::advertising_handle_t handle, + const ble::AdvertisingParameters ¶ms + ); + + /** Set new advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingPayload( + ble::advertising_handle_t handle, + mbed::Span payload, + bool minimiseFragmentation = false + ); + + /** Set new advertising scan response for a given advertising set. This will be sent to + * device who perform active scanning. + * + * @param handle Advertising set handle. + * @param response Advertising scan response. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingScanResponse( + ble::advertising_handle_t handle, + mbed::Span response, + bool minimiseFragmentation = false + ); + + /** Start advertising using the given advertising set. + * + * @param handle Advertising set handle. + * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. + * @param maxEvents Max number of events produced during advertising - 0 means no limit. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startAdvertising( + ble::advertising_handle_t handle, + ble::adv_duration_t maxDuration = ble::adv_duration_t(0), + uint8_t maxEvents = 0 + ); + + /** Stop advertising given advertising set. This is separate from periodic advertising + * which will not be affected. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t stopAdvertising(ble::advertising_handle_t handle); + + /** Check if advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if advertising is active on this set. + */ + virtual bool isAdvertisingActive(ble::advertising_handle_t handle); + + /** Set periodic advertising parameters for a given advertising set. + * + * @param handle Advertising set handle. + * @param periodicAdvertisingIntervalMin Minimum interval for periodic advertising. + * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. + * @param advertiseTxPower Include transmission power in the advertisements. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setPeriodicAdvertisingParameters( + ble::advertising_handle_t handle, + ble::periodic_interval_t periodicAdvertisingIntervalMin, + ble::periodic_interval_t periodicAdvertisingIntervalMax, + bool advertiseTxPower = true + ); + + /** Set new periodic advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setPeriodicAdvertisingPayload( + ble::advertising_handle_t handle, + mbed::Span payload + ); + + /** Start periodic advertising for a given set. Periodic advertising will not start until + * normal advertising is running but will continue to run after normal advertising has stopped. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startPeriodicAdvertising(ble::advertising_handle_t handle); + + /** Stop periodic advertising for a given set. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t stopPeriodicAdvertising(ble::advertising_handle_t handle); + + /** Check if periodic advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if periodic advertising is active on this set. + */ + virtual bool isPeriodicAdvertisingActive(ble::advertising_handle_t handle); + + /* scanning */ + + /** Set new scan parameters. + * + * @param params Scan parameters, @see GapScanParameters for details. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setScanParameters(const ble::ScanParameters& params); + + /** Start scanning. + * + * @param filtering Filtering policy. + * @param duration How long to scan for. Special value 0 means scan forever. + * @param period How long to scan for in single period. If the period is 0 and duration + * is nonzero the scan will last for single duration. + * + * @note When the duration and period parameters are non-zero scanning will last for + * the duration within the period. After the scan period has expired a new scan period + * will begin and scanning. This will repeat until stopScan() is called. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startScan( + ble::duplicates_filter_t filtering = ble::duplicates_filter_t::DISABLE, + ble::scan_duration_t duration = ble::scan_duration_t(0), + ble::scan_period_t period = ble::scan_period_t(0) + ); + + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receptions. If this time is + * exceeded, synchronisation is lost. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createSync( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + uint8_t sid, + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout + ); + + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. Use periodic advertising sync list to determine who to sync with. + * + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receives. + * If this time is exceeded, synchronisation is lost. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createSync( + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout + ); + + /** Cancel sync attempt. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t cancelCreateSync(); + + /** Stop reception of the periodic advertising identified by the handle. + * + * @param handle Periodic advertising synchronisation handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t terminateSync(ble::periodic_sync_handle_t handle); + + /** Add device to the periodic advertiser list. Cannot be called when sync is ongoing. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t addDeviceToPeriodicAdvertiserList( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + ble::advertising_sid_t sid + ); + + /** Remove device from the periodic advertiser list. Cannot be called when sync is ongoing. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + ble::advertising_sid_t sid + ); + + /** Remove all devices from periodic advertiser list. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t clearPeriodicAdvertiserList(); + + /** Get number of devices that can be added to the periodic advertiser list. + * @return Number of devices that can be added to the periodic advertiser list. + */ + virtual uint8_t getMaxPeriodicAdvertiserListSize(); + + /** + * Initiate a connection to a peer. + * + * Once the connection is established an onConnectionComplete in the event handler + * will be called. + * + * @param peerAddressType + * @param peerAddress + * @param connectionParams + * + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. + */ + virtual ble_error_t connect( + ble::target_peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + const ble::ConnectionParameters &connectionParams + ); + + /** Cancel the connection attempt. This is not guaranteed to succeed. As a result + * onConnectionComplete in the event handler will be called. Check the success parameter + * to see if the connection was created. + * + * @return BLE_ERROR_NONE if the connection attempt has been requested to be cancelled. + */ + virtual ble_error_t cancelConnect(); + + /** + * Read the PHY used by the transmitter and the receiver on a connection. + * + * Once the PHY has been read, it is reported back via the function onPhyRead + * of the event handler registered by the application. + * + * @param connection Handle of the connection for which the PHY being used is + * queried. + * + * @return BLE_ERROR_NONE if the read PHY procedure has been started or an + * appropriate error code. + */ + virtual ble_error_t readPhy(ble::connection_handle_t connection); + + /** + * Set the preferred PHYs to use in a connection. + * + * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no + * preferred PHYs are set and the default value of the subsystem is used. + * + * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no + * preferred PHYs are set and the default value of the subsystem is used. + * + * @return BLE_ERROR_NONE if the preferences have been set or an appropriate + * error code. + */ + virtual ble_error_t setPreferredPhys( + const ble::phy_set_t *txPhys, + const ble::phy_set_t *rxPhys + ); + + /** + * Update the PHY used by a connection. + * + * Once the update process has been completed, it is reported back to the + * application via the function onPhyUpdateComplete of the event handler + * registered by the application. + * + * @param connection Handle of the connection to update. + * + * @param txPhys Set of PHYs preferred for tx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param codedSymbol Number of symbols used to code a bit when le coded is + * used. If the value is UNDEFINED then the choice is up to the Bluetooth + * subsystem. + * + * @return BLE_ERROR_NONE if the update PHY procedure has been successfully + * started or an error code. + */ + virtual ble_error_t setPhy( + ble::connection_handle_t connection, + const ble::phy_set_t *txPhys, + const ble::phy_set_t *rxPhys, + ble::coded_symbol_per_bit_t codedSymbol + ); + + /** + * Get the maximum size of the whitelist. + * + * @return Maximum size of the whitelist. + * + * @note If using Mbed OS, you can configure the size of the whitelist by + * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. + */ + virtual uint8_t getMaxWhitelistSize(void) const; + + /** + * Get the Link Layer to use the internal whitelist when scanning, + * advertising or initiating a connection depending on the filter policies. + * + * @param[in,out] whitelist Define the whitelist instance which is used + * to store the whitelist requested. In input, the caller provisions memory. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * copied into the supplied reference. + */ + virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const; + + /** + * Set the value of the whitelist to be used during GAP procedures. + * + * @param[in] whitelist A reference to a whitelist containing the addresses + * to be copied to the internal whitelist. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * populated with the addresses in the given whitelist. + * + * @note The whitelist must not contain addresses of type @ref + * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This + * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might + * change its private address at any time, and it is not possible to resolve + * it. + * + * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), + * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. + */ + virtual ble_error_t setWhitelist(const Whitelist_t &whitelist); + +protected: + /* Override the following in the underlying adaptation layer to provide the + * functionality of scanning. */ + + /** Can only be called if use_non_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionOneAPI() const { } + + /** Can only be called if use_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionTwoAPI() const { } + /* * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated. * They have been relocated to the class BLEProtocol. @@ -460,26 +1015,6 @@ public: INIT_POLICY_FILTER_ALL_ADV = 1, }; - /** - * Representation of a whitelist of addresses. - */ - struct Whitelist_t { - /** - * Pointer to the array of the addresses composing the whitelist. - */ - BLEProtocol::Address_t *addresses; - - /** - * Number addresses in this whitelist. - */ - uint8_t size; - - /** - * Capacity of the array holding the addresses. - */ - uint8_t capacity; - }; - /** * Description of the states of the device. */ @@ -1068,142 +1603,6 @@ public: typedef CallChainOfFunctionPointersWithContext GapShutdownCallbackChain_t; - /** - * Definition of the general handler of Gap related events. - */ - struct EventHandler { - /** Called when scanning reads an advertising packet during passive scan or receives - * a scan response during an active scan. - * - * @param event Advertising report @see AdvertisingReportEvent_t for details. - */ - void onAdvertisingReport(const ble::AdvertisingReportEvent &event) { - (void) event; - } - - /** Called when connection attempt ends. - * - * @param event Connection event @see ConnectionCompleteEvent_t for details. - */ - void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { - (void)event; - } - - /** Called when first advertising packet in periodic advertising is received. - * - * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. - */ - virtual void onPeriodicAdvertisingSyncEstablished( - const ble::PeriodicAdvertisingSyncEstablishedEvent &event - ) { - (void) event; - } - - /** Called when a periodic advertising packet is received. - * - * @param event Periodic advertisement event. - */ - virtual void onPeriodicAdvertisingReportEvent( - const ble::PeriodicAdvertisingReportEvent & event - ) { - (void) event; - } - - virtual void onPeriodicAdvertisingSyncLoss( - const ble::PeriodicAdvertisingSyncLoss &event - ) { - (void) event; - } - - /** Called when scan times out. - */ - virtual void onScanTimeout(const ble::ScanTimeoutEvent &) { } - - /** Called when advertising ends. - * - * @param event Advertising end event: @see AdvertisingEndEvent_t for details. - */ - virtual void onAdvertisingEnd(const ble::AdvertisingEndEvent_t& event) - { - (void) event; - } - - /** Called when a scanning device request a scan response. - * - * @param event Scan request event: @see ScanRequestEvent_t for details. - */ - virtual void onScanRequest(const ble::ScanRequestEvent_t& event) - { - (void) event; - } - - /** - * Function invoked when the current transmitter and receiver PHY have - * been read for a given connection. - * - * @param status Status of the operation: BLE_ERROR_NONE in case of - * success or an appropriate error code. - * - * @param connectionHandle: The handle of the connection for which the - * PHYs have been read. - * - * @param txPhy PHY used by the transmitter. - * - * @param rxPhy PHY used by the receiver. - */ - virtual void onReadPhy( - ble_error_t status, - Handle_t connectionHandle, - Phy_t txPhy, - Phy_t rxPhy - ) { - (void)status; - (void)connectionHandle; - (void)txPhy; - (void)rxPhy; - } - - /** - * Function invoked when the update process of the PHY has been completed. - * - * The process can be initiated by a call to the function setPhy, the - * local bluetooth subsystem or the peer. - * - * @param status Status of the operation: BLE_ERROR_NONE in case of - * success or an appropriate error code. - * - * @param connectionHandle: The handle of the connection on which the - * operation was made. - * - * @param txPhy PHY used by the transmitter. - * - * @param rxPhy PHY used by the receiver. - * - * @note Success doesn't mean the PHY has been updated it means both - * ends have negotiated the best PHY according to their configuration and - * capabilities. The PHY currently used are present in the txPhy and - * rxPhy parameters. - */ - virtual void onPhyUpdateComplete( - ble_error_t status, - Handle_t connectionHandle, - Phy_t txPhy, - Phy_t rxPhy - ) { - (void)status; - (void)connectionHandle; - (void)txPhy; - (void)rxPhy; - } - - protected: - /** - * Prevent polymorphic deletion and avoid unnecessary virtual destructor - * as the Gap class will never delete the instance it contains. - */ - ~EventHandler() { } - }; - /* * The following functions are meant to be overridden in the platform-specific subclass. */ @@ -1409,44 +1808,6 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** - * Initiate a connection to a peer. - * - * Once the connection is established an onConnectionComplete in the event handler - * will be called. - * - * @param peerAddressType - * @param peerAddress - * @param connectionParams - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallChain (if set) is invoked upon - * a connection event. - */ - virtual ble_error_t connect( - ble::target_peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - const ble::ConnectionParameters &connectionParams - ) { - (void)peerAddressType; - (void)peerAddress; - (void)connectionParams; - - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Cancel the connection attempt. This is not guaranteed to succeed. As a result - * onConnectionComplete in the event handler will be called. Check the success parameter - * to see if the connection was created. - * - * @return BLE_ERROR_NONE if the connection attempt has been requested to be cancelled. - */ - virtual ble_error_t cancelConnect() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - /** * Initiate a connection to a peer. * @@ -1510,72 +1871,6 @@ public: const GapScanningParams *scanParams ); - /** - * Read the PHY used by the transmitter and the receiver on a connection. - * - * Once the PHY has been read, it is reported back via the function onPhyRead - * of the event handler registered by the application. - * - * @param connection Handle of the connection for which the PHY being used is - * queried. - * - * @return BLE_ERROR_NONE if the read PHY procedure has been started or an - * appropriate error code. - */ - virtual ble_error_t readPhy(Handle_t connection) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the preferred PHYs to use in a connection. - * - * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no - * preferred PHYs are set and the default value of the subsystem is used. - * - * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no - * preferred PHYs are set and the default value of the subsystem is used. - * - * @return BLE_ERROR_NONE if the preferences have been set or an appropriate - * error code. - */ - virtual ble_error_t setPreferredPhys( - const PhySet_t* txPhys, - const PhySet_t* rxPhys - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Update the PHY used by a connection. - * - * Once the update process has been completed, it is reported back to the - * application via the function onPhyUpdateComplete of the event handler - * registered by the application. - * - * @param connection Handle of the connection to update. - * - * @param txPhys Set of PHYs preferred for tx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param codedSymbol Number of symbols used to code a bit when le coded is - * used. If the value is UNDEFINED then the choice is up to the Bluetooth - * subsystem. - * - * @return BLE_ERROR_NONE if the update PHY procedure has been successfully - * started or an error code. - */ - virtual ble_error_t setPhy( - Handle_t connection, - const PhySet_t* txPhys, - const PhySet_t* rxPhys, - CodedSymbolPerBit_t codedSymbol - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - /** * Initiate a disconnection procedure. * @@ -1623,402 +1918,6 @@ public: return BLE_ERROR_NOT_IMPLEMENTED; } - /** Check controller support for a specific feature. - * - * @param feature Feature to check. - * @return True if feature is supported. - */ - bool isFeatureSupported(ble::controller_supported_features_t feature); - - /* advertising */ - - /** Return currently available number of supported advertising sets. - * This may change at runtime. - * - * @return Number of advertising sets that may be created at the same time. - */ - virtual uint8_t getMaxAdvertisingSetNumber() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 1; - } - - /** Return maximum advertising data length supported. - * - * @return Maximum advertising data length supported. - */ - virtual uint8_t getMaxAdvertisingDataLength() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0x1F; - } - - /** Create an advertising set and apply the passed in parameters. The handle returned - * by this function must be used for all other calls that accept an advertising handle. - * When done with advertising, remove from the system using destroyAdvertisingSet(). - * - * @note The exception is the ble::LEGACY_ADVERTISING_HANDLE which may be used at any time. - * - * @param[out] handle Advertising handle returned, valid only if function returned success. - * @param parameters Advertising parameters for the newly created set. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createAdvertisingSet( - ble::advertising_handle_t *handle, - const ble::AdvertisingParameters ¶meters - ) - { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Remove the advertising set (resets its set parameters). The advertising set must not - * be active. - * - * @note ble::LEGACY_ADVERTISING_HANDLE may not be destroyed. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t destroyAdvertisingSet(ble::advertising_handle_t handle) { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Set advertising parameters of an existing set. - * - * @param handle Advertising set handle. - * @param params New advertising parameters. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingParameters( - ble::advertising_handle_t handle, - const ble::AdvertisingParameters ¶ms - ) { - (void) handle; - (void) params; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Set new advertising payload for a given advertising set. - * - * @param handle Advertising set handle. - * @param payload Advertising payload. - * @param minimiseFragmentation Preference for fragmentation. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation = false - ) - { - (void) handle; - (void) payload; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Set new advertising scan response for a given advertising set. This will be sent to - * device who perform active scanning. - * - * @param handle Advertising set handle. - * @param response Advertising scan response. - * @param minimiseFragmentation Preference for fragmentation. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingScanResponse( - ble::advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation = false - ) - { - (void) handle; - (void) response; - (void) minimiseFragmentation; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Start advertising using the given advertising set. - * - * @param handle Advertising set handle. - * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. - * @param maxEvents Max number of events produced during advertising - 0 means no limit. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startAdvertising( - ble::advertising_handle_t handle, - ble::adv_duration_t maxDuration = ble::adv_duration_t(0), - uint8_t maxEvents = 0 - ) - { - (void) maxEvents; - (void) maxDuration; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Stop advertising given advertising set. This is separate from periodic advertising - * which will not be affected. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t stopAdvertising(ble::advertising_handle_t handle) { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Check if advertising is active for a given advertising set. - * - * @param handle Advertising set handle. - * @return True if advertising is active on this set. - */ - virtual bool isAdvertisingActive(ble::advertising_handle_t handle) { - return false; - } - - /** Set periodic advertising parameters for a given advertising set. - * - * @param handle Advertising set handle. - * @param periodicAdvertisingIntervalMin Minimum interval for periodic advertising. - * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. - * @param advertiseTxPower Include transmission power in the advertisements. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setPeriodicAdvertisingParameters( - ble::advertising_handle_t handle, - ble::periodic_interval_t periodicAdvertisingIntervalMin, - ble::periodic_interval_t periodicAdvertisingIntervalMax, - bool advertiseTxPower = true - ) { - (void) handle; - (void) periodicAdvertisingIntervalMin; - (void) periodicAdvertisingIntervalMax; - (void) advertiseTxPower; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Set new periodic advertising payload for a given advertising set. - * - * @param handle Advertising set handle. - * @param payload Advertising payload. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setPeriodicAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload - ) { - (void) handle; - (void) payload; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Start periodic advertising for a given set. Periodic advertising will not start until - * normal advertising is running but will continue to run after normal advertising has stopped. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startPeriodicAdvertising(ble::advertising_handle_t handle) - { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Stop periodic advertising for a given set. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t stopPeriodicAdvertising(ble::advertising_handle_t handle) - { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Check if periodic advertising is active for a given advertising set. - * - * @param handle Advertising set handle. - * @return True if periodic advertising is active on this set. - */ - virtual bool isPeriodicAdvertisingActive(ble::advertising_handle_t handle) - { - (void) handle; - /* Requesting action from porter(s): override this API if this capability is supported. */ - return false; - } - - /* scanning */ - - /** Set new scan parameters. - * - * @param params Scan parameters, @see GapScanParameters for details. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setScanParameters( - const ble::ScanParameters& params - ) { - useVersionTwoAPI(); - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - }; - - /** Start scanning. - * - * @param filtering Filtering policy. - * @param duration How long to scan for. Special value 0 means scan forever. - * @param period How long to scan for in single period. If the period is 0 and duration - * is nonzero the scan will last for single duration. - * - * @note When the duration and period parameters are non-zero scanning will last for - * the duration within the period. After the scan period has expired a new scan period - * will begin and scanning. This will repeat until stopScan() is called. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startScan( - ble::duplicates_filter_t filtering = ble::duplicates_filter_t::DISABLE, - ble::scan_duration_t duration = ble::scan_duration_t(0), - ble::scan_period_t period = ble::scan_period_t(0) - ) { - useVersionTwoAPI(); - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - }; - - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic - * advertising packets. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver - * may skip after successfully receiving a periodic advertising packet. - * @param timeout Maximum permitted time between successful receptions. If this time is - * exceeded, synchronisation is lost. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createSync( - PeerAddressType_t peerAddressType, - Address_t peerAddress, - uint8_t sid, - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout - ) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic - * advertising packets. Use periodic advertising sync list to determine who to sync with. - * - * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver - * may skip after successfully receiving a periodic advertising packet. - * @param timeout Maximum permitted time between successful receives. - * If this time is exceeded, synchronisation is lost. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createSync( - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout - ) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Cancel sync attempt. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t cancelCreateSync() - { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Stop reception of the periodic advertising identified by the handle. - * - * @param handle Periodic advertising synchronisation handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t terminateSync( - ble::periodic_sync_handle_t handle - ) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Add device to the periodic advertiser list. Cannot be called when sync is ongoing. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t addDeviceToPeriodicAdvertiserList( - PeerAddressType_t peerAddressType, - Address_t peerAddress, - uint8_t sid - ) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Remove device from the periodic advertiser list. Cannot be called when sync is ongoing. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( - PeerAddressType_t peerAddressType, - Address_t peerAddress, - uint8_t sid - ) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Remove all devices from periodic advertiser list. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t clearPeriodicAdvertiserList() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** Get number of devices that can be added to the periodic advertiser list. - * @return Number of devices that can be added to the periodic advertiser list. - */ - virtual uint8_t getMaxPeriodicAdvertiserListSize() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0; - } - -protected: - /* Override the following in the underlying adaptation layer to provide the - * functionality of scanning. */ - - /** Can only be called if use_non_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionOneAPI() const { } - - /** Can only be called if use_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionTwoAPI() const { } - public: /** @@ -2219,59 +2118,6 @@ public: *countP = 0; } - /** - * Get the maximum size of the whitelist. - * - * @return Maximum size of the whitelist. - * - * @note If using Mbed OS, you can configure the size of the whitelist by - * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. - */ - virtual uint8_t getMaxWhitelistSize(void) const - { - return 0; - } - - /** - * Get the Link Layer to use the internal whitelist when scanning, - * advertising or initiating a connection depending on the filter policies. - * - * @param[in,out] whitelist Define the whitelist instance which is used - * to store the whitelist requested. In input, the caller provisions memory. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * copied into the supplied reference. - */ - virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the value of the whitelist to be used during GAP procedures. - * - * @param[in] whitelist A reference to a whitelist containing the addresses - * to be copied to the internal whitelist. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * populated with the addresses in the given whitelist. - * - * @note The whitelist must not contain addresses of type @ref - * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This - * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might - * change its private address at any time, and it is not possible to resolve - * it. - * - * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), - * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. - */ - virtual ble_error_t setWhitelist(const Whitelist_t &whitelist) - { - (void) whitelist; - return BLE_ERROR_NOT_IMPLEMENTED; - } - /** * Set the advertising policy filter mode to be used during the next * advertising procedure. diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 9193ca4b95..103bf26c8e 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -183,9 +183,9 @@ public: /** @copydoc Gap::createSync */ virtual ble_error_t createSync( - PeerAddressType_t peerAddressType, - uint8_t *peerAddress, - uint8_t sid, + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout ); @@ -208,17 +208,17 @@ public: /** @copydoc Gap::addDeviceToPeriodicAdvertiserList */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( - PeerAddressType_t peerAddressType, - Address_t peerAddress, - uint8_t sid + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid ); /** @copydoc Gap::removeDeviceFromPeriodicAdvertiserList */ virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( - PeerAddressType_t peerAddressType, - uint8_t *peerAddress, - uint8_t sid + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid ); /** @copydoc Gap::clearPeriodicAdvertiserList diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index 5da3f8fe83..db90cd536a 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -72,6 +72,243 @@ Gap::PeerAddressType_t convert_legacy_address_type( } +uint8_t Gap::getMaxAdvertisingSetNumber() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 1; +} + +uint8_t Gap::getMaxAdvertisingDataLength() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0x1F; +} + +ble_error_t Gap::createAdvertisingSet( + ble::advertising_handle_t *handle, + const ble::AdvertisingParameters ¶meters +) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::destroyAdvertisingSet(ble::advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingParameters( + ble::advertising_handle_t handle, + const ble::AdvertisingParameters ¶ms +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingPayload( + ble::advertising_handle_t handle, + mbed::Span payload, + bool minimiseFragmentation +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingScanResponse( + ble::advertising_handle_t handle, + mbed::Span response, + bool minimiseFragmentation +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::startAdvertising( + ble::advertising_handle_t handle, + ble::adv_duration_t maxDuration, + uint8_t maxEvents +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::stopAdvertising(ble::advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +bool Gap::isAdvertisingActive(ble::advertising_handle_t handle) { + return false; +} + +ble_error_t Gap::setPeriodicAdvertisingParameters( + ble::advertising_handle_t handle, + ble::periodic_interval_t periodicAdvertisingIntervalMin, + ble::periodic_interval_t periodicAdvertisingIntervalMax, + bool advertiseTxPower +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPeriodicAdvertisingPayload( + ble::advertising_handle_t handle, + mbed::Span payload +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::startPeriodicAdvertising(ble::advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::stopPeriodicAdvertising(ble::advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +bool Gap::isPeriodicAdvertisingActive(ble::advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return false; +} + +ble_error_t Gap::setScanParameters(const ble::ScanParameters& params) +{ + useVersionTwoAPI(); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +}; + +ble_error_t Gap::startScan( + ble::duplicates_filter_t filtering, + ble::scan_duration_t duration, + ble::scan_period_t period +) { + useVersionTwoAPI(); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +}; + +ble_error_t Gap::createSync( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + uint8_t sid, + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::createSync( + ble::slave_latency_t maxPacketSkip, + ble::sync_timeout_t timeout +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::cancelCreateSync() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::terminateSync(ble::periodic_sync_handle_t handle) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::addDeviceToPeriodicAdvertiserList( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + ble::advertising_sid_t sid +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::removeDeviceFromPeriodicAdvertiserList( + ble::peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + ble::advertising_sid_t sid +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::clearPeriodicAdvertiserList() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +uint8_t Gap::getMaxPeriodicAdvertiserListSize() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0; +} + +ble_error_t Gap::connect( + ble::target_peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, + const ble::ConnectionParameters &connectionParams +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::cancelConnect() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::readPhy(ble::connection_handle_t connection) +{ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPreferredPhys( + const ble::phy_set_t *txPhys, + const ble::phy_set_t *rxPhys +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPhy( + ble::connection_handle_t connection, + const ble::phy_set_t *txPhys, + const ble::phy_set_t *rxPhys, + ble::coded_symbol_per_bit_t codedSymbol +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +uint8_t Gap::getMaxWhitelistSize(void) const +{ + return 0; +} + +ble_error_t Gap::getWhitelist(Whitelist_t &whitelist) const +{ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setWhitelist(const Whitelist_t &whitelist) +{ + return BLE_ERROR_NOT_IMPLEMENTED; +} + + + const Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = { /* use_non_resolvable_random_address */ false, /* resolution_strategy */ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 302a2d0376..e99bbed9c8 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2458,9 +2458,9 @@ ble_error_t GenericGap::startScan( } ble_error_t GenericGap::createSync( - Gap::PeerAddressType_t peerAddressType, - uint8_t *peerAddress, - uint8_t sid, + ble::peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout ) @@ -2469,8 +2469,8 @@ ble_error_t GenericGap::createSync( return BLE_ERROR_NOT_IMPLEMENTED; } - if (peerAddressType != PeerAddressType_t::PUBLIC || - peerAddressType != PeerAddressType_t::RANDOM + if (peerAddressType != peer_address_type_t::PUBLIC || + peerAddressType != peer_address_type_t::RANDOM ) { return BLE_ERROR_INVALID_PARAM; } @@ -2526,9 +2526,9 @@ ble_error_t GenericGap::terminateSync(periodic_sync_handle_t handle) } ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( - Gap::PeerAddressType_t peerAddressType, - Address_t peerAddress, - uint8_t sid + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid ) { if (is_extended_advertising_available() == false) { @@ -2553,9 +2553,9 @@ ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( } ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( - Gap::PeerAddressType_t peerAddressType, - uint8_t *peerAddress, - uint8_t sid + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid ) { if (is_extended_advertising_available() == false) { From da7d4a0c12dfad619e94da6c4b0f59cb48c832aa Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 16 Nov 2018 10:10:34 +0000 Subject: [PATCH 213/361] BLE: Introduce new disconnection API. --- features/FEATURE_BLE/ble/Gap.h | 20 ++++ features/FEATURE_BLE/ble/gap/Events.h | 22 ++++ features/FEATURE_BLE/ble/gap/Types.h | 104 ++++++++++++++++++ features/FEATURE_BLE/ble/pal/GapTypes.h | 21 +--- features/FEATURE_BLE/source/Gap.cpp | 8 ++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 9 ++ 6 files changed, 164 insertions(+), 20 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 0816c82b81..4b2cb950d4 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -326,6 +326,8 @@ public: */ void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { } + void onDisconnection(const ble::DisconnectionEvent &event) { } + /** * Function invoked when the current transmitter and receiver PHY have * been read for a given connection. @@ -708,6 +710,24 @@ public: */ virtual ble_error_t cancelConnect(); + /** + * Initiate a disconnection procedure. + * + * Once the disconnection procedure has completed a + * DisconnectionCallbackParams_t, the event is emitted to handlers that + * have been registered with onDisconnection(). + * + * @param[in] reason Reason of the disconnection transmitted to the peer. + * @param[in] connectionHandle Handle of the connection to end. + * + * @return BLE_ERROR_NONE if the disconnection procedure successfully + * started. + */ + virtual ble_error_t disconnect( + ble::connection_handle_t connectionHandle, + ble::local_disconnection_reason_t reason + ); + /** * Read the PHY used by the transmitter and the receiver on a connection. * diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 6bd4b87b8f..845439427a 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -552,6 +552,28 @@ private: const address_t &peerAddress; }; + +struct DisconnectionEvent { + DisconnectionEvent( + connection_handle_t connectionHandle, + const disconnection_reason_t &reason + ) : connectionHandle(connectionHandle), reason(reason) { } + + connection_handle_t getConnectionHandle() const + { + return connectionHandle; + } + + const disconnection_reason_t &getReason() const + { + return reason; + } + +private: + ble::connection_handle_t connectionHandle; + ble::disconnection_reason_t reason; +}; + } // namespace ble #endif //BLE_GAP_EVENTS_H diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 872a9f16ee..bbe2e39890 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -555,6 +555,110 @@ struct connection_role_t :SafeEnum { explicit connection_role_t(uint8_t raw_value) : SafeEnum(raw_value) { } }; +/** + * Enumeration of disconnection reasons that should be transmited to the peer. + */ +struct local_disconnection_reason_t : SafeEnum { + enum type { + /** + * GAP or GATT failed to authenticate the peer. + */ + AUTHENTICATION_FAILURE = 0x05, + AUTHENTICATION_FAILLURE = 0x05, + + /** + * Connection terminated by the user. + */ + USER_TERMINATION = 0x13, + REMOTE_USER_TERMINATED_CONNECTION = 0x13, + + /** + * Connection termination due to low resources. + */ + LOW_RESOURCES = 0x14, + REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES = 0x14, + + /** + * Connection termination due to power off. + */ + POWER_OFF = 0x15, + REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_POWER_OFF = 0x15, + + /** + * Remote feature not supported + */ + UNSUPPORTED_REMOTE_FEATURE = 0x1A, + + /** + * Not possible to pai with a unit key. + */ + PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED = 0x29, + + /** + * Connection parameters were unacceptable. + */ + CONN_INTERVAL_UNACCEPTABLE = 0x3B, + UNACCEPTABLE_CONNECTION_PARAMETERS = 0x3B + }; + + /** + * Construct a new instance of disconnection_reason_t. + */ + local_disconnection_reason_t(type value) : SafeEnum(value) { } +}; + + +/** + * Enumeration of disconnection reasons received in a disconnection event. + */ +struct disconnection_reason_t : SafeEnum { + enum type { + /** + * GAP or GATT failed to authenticate the peer. + */ + AUTHENTICATION_FAILURE = 0x05, + + /** + * The connection timed out. + */ + CONNECTION_TIMEOUT = 0x08, + + /** + * Connection terminated by the user. + */ + REMOTE_USER_TERMINATED_CONNECTION = 0x13, + + /** + * Remote device terminated connection due to low resources. + */ + REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES = 0x14, + + /** + * Remote device terminated connection due to power off. + */ + REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF = 0x15, + + /** + * Indicate that the local user or the internal + * Bluetooth subsystem terminated the connection. + */ + LOCAL_HOST_TERMINATED_CONNECTION = 0x16, + + /** + * Connection parameters were unacceptable. + */ + CONN_INTERVAL_UNACCEPTABLE = 0x3B + }; + + /** + * Construct a new instance of disconnection_reason_t. + */ + disconnection_reason_t(type value) : SafeEnum(value) { } +}; + + + + } // namespace ble #endif //BLE_GAP_TYPES_H diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 68f754c9e3..7a59a53b17 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -216,26 +216,7 @@ struct hci_error_code_t : SafeEnum { }; -/** - * Reasons which can be used to end a connection. - */ -struct disconnection_reason_t : SafeEnum { - enum type { - AUTHENTICATION_FAILLURE = 0x05, - REMOTE_USER_TERMINATED_CONNECTION = 0x13, - REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_LOW_RESOURCES = 0x14, - REMOTE_DEVICE_TERMINATED_CONNECTION_DUE_TO_POWER_OFF = 0x15, - UNSUPPORTED_REMOTE_FEATURE = 0x1A, - PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED = 0x29, - UNACCEPTABLE_CONNECTION_PARAMETERS = 0x3B - }; - - /** - * Construct a new disconnection_reason_t instance. - */ - disconnection_reason_t(type value) : - SafeEnum(value) { } -}; +typedef ble::local_disconnection_reason_t disconnection_reason_t; typedef ble::advertising_filter_policy_t advertising_filter_policy_t; diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index db90cd536a..ba95146bed 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -271,6 +271,14 @@ ble_error_t Gap::cancelConnect() { return BLE_ERROR_NOT_IMPLEMENTED; } +ble_error_t Gap::disconnect( + ble::connection_handle_t connectionHandle, + ble::local_disconnection_reason_t reason +) { + // Forward to the old implementation for now. + return disconnect(connectionHandle, (Gap::DisconnectionReason_t) reason.value()); +} + ble_error_t Gap::readPhy(ble::connection_handle_t connection) { return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index e99bbed9c8..df0b10225d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1228,6 +1228,15 @@ void GenericGap::processDisconnectionEvent( ); } + if (_eventHandler) { + _eventHandler->onDisconnection( + DisconnectionEvent( + handle, + (ble::disconnection_reason_t::type) reason + ) + ); + } + ::Gap::processDisconnectionEvent( handle, reason From 862775d3df4e146e90cbd8e66bab6198279e941b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 11:07:28 +0000 Subject: [PATCH 214/361] extra data builder funcs --- features/FEATURE_BLE/ble/Gap.h | 2 +- .../ble/gap/AdvertisingDataBuilder.h | 293 ++++++++++++++++-- 2 files changed, 267 insertions(+), 28 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 4b2cb950d4..022b07a28b 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -48,7 +48,7 @@ /** * Define device discovery, connection and link management procedures. * - * - Device discovery: A device can advertise nearby peers of its existence, + * - Device discovery: A device can advertise to nearby peers its existence, * identity and capabilities. Similarly, a device can scan its environment to * find advertising peers. The information acquired during the scan helps to * identify peers and understand their use. A scanner may acquire more information diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 33ce2ac048..56b93184e1 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -145,9 +145,9 @@ struct adv_data_type_t :SafeEnum { /** - * Enumeration of allowed flags for DataType_t::FLAGS. + * Enumeration of allowed flags for adv_data_type_t::FLAGS. * - * @note DataType_t::FLAGS may contain several flags that the bitwise + * @note adv_data_type_t::FLAGS may contain several flags that the bitwise * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. * * @par Source @@ -193,7 +193,7 @@ struct adv_data_flags_t :SafeEnum { /** - * Enumeration of values for the DataType_t::APPEARANCE. + * Enumeration of values for the adv_data_type_t::APPEARANCE. * * These values describe the physical shape or appearance of the device. * @@ -470,7 +470,7 @@ public: */ AdvertisingDataBuilder(mbed::Span buffer) : _buffer(buffer), - _payloadLen(0) { + _payload_length(0) { } /** Advertising data needs a user provided buffer to store the data. @@ -481,7 +481,7 @@ public: */ AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size) : _buffer(buffer, buffer_size), - _payloadLen(0) { + _payload_length(0) { } /** @@ -490,7 +490,7 @@ public: * @return A Span containing the payload. */ mbed::Span getAdvertisingData() const { - return _buffer.first(_payloadLen); + return _buffer.first(_payload_length); } /** @@ -500,8 +500,7 @@ public: * advertising payload, then the value is updated. * * @param[in] advDataType The type of the field to add. - * @param[in] payload Pointer to the value of the field to add. - * @param[in] len Size in bytes of the value to add. + * @param[in] fieldData Span of data to add. * * @return BLE_ERROR_NONE on success. * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the advertising @@ -516,9 +515,28 @@ public: ble_error_t addData( adv_data_type_t advDataType, mbed::Span fieldData - ) - { - return appendField(advDataType, fieldData); + ) { + uint8_t* field = findField(advDataType); + + if (field) { + switch(advDataType.value()) { + /* These types are append to existing field */ + case adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS: + case adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS: + case adv_data_type_t::INCOMPLETE_LIST_32BIT_SERVICE_IDS: + case adv_data_type_t::COMPLETE_LIST_32BIT_SERVICE_IDS: + case adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS: + case adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS: + case adv_data_type_t::LIST_128BIT_SOLICITATION_IDS: + return appendToField(fieldData, field); + default: + /* All other types have their field contents replaced */ + return replaceField(advDataType, fieldData, field); + } + } else { + /* field doesn't exist, add it */ + return addField(advDataType, fieldData); + } } /** @@ -526,46 +544,267 @@ public: * * @post getPayloadLen() returns 0. */ - void clear(void) + void clear() { memset(_buffer.data(), 0, _buffer.size()); - _payloadLen = 0; + _payload_length = 0; } + /** + * Replace a specific field in the advertising payload. If the field doesn't + * exist it will be added. + * + * @param[in] advDataType The type of the field to update. + * @param[in] fieldData Span of data to add. + * + * @return BLE_ERROR_NONE returned on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the + * advertising buffer to overflow. + * + * @note Unlike in addData(), even if data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, + * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, + * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, + * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the + * supplied value is will not be appended but replaced completely. + */ + ble_error_t removeData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { + uint8_t* field = findField(advDataType); + + if (field) { + /* Field type already exists, replace field contents */ + return replaceField(advDataType, fieldData, field); + } else { + /* field doesn't exist, add it */ + return addField(advDataType, fieldData); + } + } + + /** + * Add device appearance in the advertising payload. + * + * @param[in] appearance The appearance to advertise. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * adv_data_type_t::APPEARANCE as the field type. + */ + ble_error_t setAppearance( + adv_data_appearance_t appearance = adv_data_appearance_t::GENERIC_TAG + ) { + uint8_t appearence_byte = appearance.value(); + mbed::Span appearance_span((const uint8_t*)&appearence_byte, 2); + return addData(adv_data_type_t::APPEARANCE, appearance_span); + } + + /** + * Add BLE flags in the advertising payload. + * + * @param[in] flags Bitfield describing the capability of the device. See + * allowed flags in Flags_t. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * adv_data_type_t::FLAGS as the field type. + */ + ble_error_t setFlags( + adv_data_flags_t flags = adv_data_flags_t::LE_GENERAL_DISCOVERABLE + ) { + uint8_t flags_byte = flags.value(); + mbed::Span flags_span((const uint8_t*)&flags_byte, 1); + return addData(adv_data_type_t::FLAGS, flags_span); + } + + /** + * Add the advertising TX in the advertising payload. + * + * @param[in] txPower Transmission power level in dB. + * + * @return BLE_ERROR_NONE on success. + * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the + * advertising buffer to overflow. + * + * @note This call is equivalent to calling addData() with + * adv_data_type_t::TX_POWER_LEVEL as the field type. + */ + ble_error_t setTxPowerAdvertised( + advertising_power_t txPower + ) { + mbed::Span power_span((const uint8_t*)&txPower, 1); + return addData(adv_data_type_t::TX_POWER_LEVEL, power_span); + } + private: + /** + * Search advertisement data for a specific field. + * + * @param[in] type The type of the field to find. + * + * @return A pointer to the first element in the field if found. The first + * element being the length of the field followed by the value of the field. + * @return NULL if the field is not present in the payload. + */ + uint8_t* findField(adv_data_type_t type) + { + /* Scan through advertisement data */ + for (uint8_t idx = 0; idx < _payload_length; ) { + uint8_t fieldType = _buffer[idx + 1]; + + if (fieldType == type) { + return _buffer.data() + idx; + } + + /* Advance to next field */ + idx += _buffer[idx] + 1; + } + + return NULL; + } + /** * Append advertising data based on the specified type. * * @param[in] advDataType Type of the new data. - * @param[in] payload Pointer to the data to be appended to the advertising - * payload. - * @param[in] len Length of the data pointed to by @p payload. + * @param[in] fieldData Span of data to add. * * @return BLE_ERROR_NONE on success. * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the * advertising buffer to overflow. */ - ble_error_t appendField( + ble_error_t addField( adv_data_type_t advDataType, mbed::Span fieldData - ) - { + ) { + /* Make sure we don't exceed the buffer size */ - if (_payloadLen + fieldData.size() + 2 > _buffer.size()) { + if (_payload_length + fieldData.size() + 2 > _buffer.size()) { return BLE_ERROR_BUFFER_OVERFLOW; } /* Field length. */ - _buffer[_payloadLen] = fieldData.size() + 1; - ++_payloadLen; + _buffer[_payload_length] = fieldData.size() + 1; + ++_payload_length; /* Field ID. */ - _buffer[_payloadLen] = advDataType.value(); - ++_payloadLen; + _buffer[_payload_length] = advDataType.value(); + ++_payload_length; /* Payload. */ - memcpy(&_buffer[_payloadLen], fieldData.data(), fieldData.size()); - _payloadLen += fieldData.size(); + memcpy(&_buffer[_payload_length], fieldData.data(), fieldData.size()); + _payload_length += fieldData.size(); + + return BLE_ERROR_NONE; + } + + /** + * Append data to a field in the advertising payload. + * + * @param[in] fieldData Span of data to add. + * @param[in] field Pointer to the field of type @p advDataType in the + * advertising buffer. + * + * @return BLE_ERROR_NONE on success. + */ + ble_error_t appendToField( + mbed::Span fieldData, + uint8_t* field + ) { + /* Check if data fits */ + if ((_payload_length + fieldData.size()) <= _buffer.size()) { + /* + * Make room for new field by moving the remainder of the + * advertisement payload "to the right" starting after the + * TYPE field. + */ + uint8_t* end = _buffer.data() + _payload_length; + + while (&field[1] < end) { + end[fieldData.size()] = *end; + end--; + } + + /* Insert new data */ + for (uint8_t idx = 0; idx < fieldData.size(); idx++) { + field[2 + idx] = fieldData[idx]; + } + + /* Increment lengths */ + field[0] += fieldData.size(); + _payload_length += fieldData.size(); + + return BLE_ERROR_NONE; + } else { + return BLE_ERROR_BUFFER_OVERFLOW; + } + } + + /** + * Update in place the value of a field in the advertising payload. + * + * @param[in] advDataType Type of the new data. + * @param[in] fieldData Span of data to add. + * @param[in] field Pointer to the field of type @p advDataType in the + * advertising buffer. + * + * @return BLE_ERROR_NONE on success. + */ + ble_error_t replaceField( + adv_data_type_t advDataType, + mbed::Span fieldData, + uint8_t* field + ) { + ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; + uint8_t old_data_length = field[0] - 1; + + /* New data has same length, do in-order replacement */ + if (fieldData.size() == old_data_length) { + for (uint8_t idx = 0; idx < old_data_length; idx++) { + field[2 + idx] = fieldData[idx]; + } + + result = BLE_ERROR_NONE; + } else { + /* Check if data fits */ + if ((_payload_length - old_data_length + fieldData.size()) <= _buffer.size()) { + removeField(field); + + /* Add new field */ + result = addField(advDataType, fieldData); + } + } + + return result; + } + + /** + * Remove the field. + * + * @param[in] field Pointer to the field of type @p advDataType in the + * advertising buffer. + * + * @return BLE_ERROR_NONE on success. + */ + ble_error_t removeField( + uint8_t* field + ) { + uint8_t old_data_length = field[0] - 1; + + /* Remove old field */ + while ((field + old_data_length + 2) < _buffer.data() + _payload_length) { + *field = field[old_data_length + 2]; + field++; + } + + /* Reduce length */ + _payload_length -= old_data_length + 2; return BLE_ERROR_NONE; } @@ -575,7 +814,7 @@ protected: mbed::Span _buffer; /** Length of the data added to the advertising buffer. */ - uint8_t _payloadLen; + uint8_t _payload_length; }; } // namespace ble From 6ef90b5ca7a0b5e30f86143104d316f0f9564d37 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 12:28:19 +0000 Subject: [PATCH 215/361] remove data instead of replace data --- .../ble/gap/AdvertisingDataBuilder.h | 25 +++++-------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 56b93184e1..f0edfe146f 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -551,34 +551,21 @@ public: } /** - * Replace a specific field in the advertising payload. If the field doesn't - * exist it will be added. + * Remove existing date of given type * - * @param[in] advDataType The type of the field to update. - * @param[in] fieldData Span of data to add. + * @param[in] advDataType The type of the field to remove. * - * @return BLE_ERROR_NONE returned on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the - * advertising buffer to overflow. - * - * @note Unlike in addData(), even if data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the - * supplied value is will not be appended but replaced completely. + * @return BLE_ERROR_NONE returned on success, BLE_ERROR_INVALID_PARAM if field doesn't exist */ ble_error_t removeData( - adv_data_type_t advDataType, - mbed::Span fieldData + adv_data_type_t advDataType ) { uint8_t* field = findField(advDataType); if (field) { - /* Field type already exists, replace field contents */ - return replaceField(advDataType, fieldData, field); + return removeField(field); } else { - /* field doesn't exist, add it */ - return addField(advDataType, fieldData); + return BLE_ERROR_INVALID_PARAM; } } From 838de80fbfa2a93c0d810db659f00a96a9a778b4 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 14:50:14 +0000 Subject: [PATCH 216/361] flags no longer a safenum --- .../ble/gap/AdvertisingDataBuilder.h | 161 +++++++++++------- 1 file changed, 103 insertions(+), 58 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index f0edfe146f..5867960508 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -47,7 +47,7 @@ namespace ble { * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. */ -struct adv_data_type_t :SafeEnum { +struct adv_data_type_t : SafeEnum { /** struct scoped enum wrapped by the class */ enum type { /** @@ -145,50 +145,97 @@ struct adv_data_type_t :SafeEnum { /** - * Enumeration of allowed flags for adv_data_type_t::FLAGS. + * Set of advertising flags. * - * @note adv_data_type_t::FLAGS may contain several flags that the bitwise - * and operator (ex.LE_GENERAL_DISCOVERABLE & BREDR_NOT_SUPPORTED) assembled. - * - * @par Source + * @note LE_LIMITED_DISCOVERABLE and LE_GENERAL_DISCOVERABLE are mutually + * exclusive * * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. */ -struct adv_data_flags_t :SafeEnum { - /** struct scoped enum wrapped by the class */ - enum type { - /** - * Peripheral device is discoverable for a limited period of time. - */ - LE_LIMITED_DISCOVERABLE = 0x01, - - /** - * Peripheral device is discoverable at any moment. - */ - LE_GENERAL_DISCOVERABLE = 0x02, - - /** - * Peripheral device is LE only and does not support Bluetooth Enhanced - * DataRate. - */ - BREDR_NOT_SUPPORTED = 0x04, - - /** - * Not relevant - dual mode only. - */ - SIMULTANEOUS_LE_BREDR_C = 0x08, - - /** - * Not relevant - dual mode only. - */ - SIMULTANEOUS_LE_BREDR_H = 0x10 +struct adv_data_flags_t { + enum { + LE_LIMITED_DISCOVERABLE = 0x01, /**< Discoverable for a limited period of time.*/ + LE_GENERAL_DISCOVERABLE = 0x02, /**< Discoverable at any moment. */ + BREDR_NOT_SUPPORTED = 0x04, /**< LE only and does not support Bluetooth Enhanced DataRate. */ + SIMULTANEOUS_LE_BREDR_C = 0x08, /**< Not relevant - dual mode only. */ + SIMULTANEOUS_LE_BREDR_H = 0x10 /**< Not relevant - dual mode only. */ }; - /** - * Construct a new instance of adv_data_flags_t. - */ - adv_data_flags_t(type value) : - SafeEnum(value) { } + static const uint8_t default_flags = BREDR_NOT_SUPPORTED | LE_GENERAL_DISCOVERABLE; + + /** Create from raw value */ + adv_data_flags_t(uint8_t value = 0) : _value(value) {}; + + adv_data_flags_t& setGeneralDiscoverable(bool enable = true) { + _value &= ~0x03; + if (enable) { + _value |= LE_GENERAL_DISCOVERABLE; + } + return *this; + } + + adv_data_flags_t& setLimitedDiscoverable(bool enable = true) { + _value &= ~0x03; + if (enable) { + _value |= LE_GENERAL_DISCOVERABLE; + } + return *this; + } + + adv_data_flags_t& setBredrNotSupported(bool enable = true) { + _value &= ~BREDR_NOT_SUPPORTED; + if (enable) { + _value |= BREDR_NOT_SUPPORTED; + } + return *this; + } + + adv_data_flags_t& setSimultaneousLeBredrC(bool enable = true) { + _value &= ~SIMULTANEOUS_LE_BREDR_C; + if (enable) { + _value |= SIMULTANEOUS_LE_BREDR_C; + } + return *this; + } + + adv_data_flags_t& setSimultaneousLeBredrH(bool enable = true) { + _value &= ~SIMULTANEOUS_LE_BREDR_H; + if (enable) { + _value |= SIMULTANEOUS_LE_BREDR_H; + } + return *this; + } + + bool getGeneralDiscoverable() { + return _value& LE_GENERAL_DISCOVERABLE; + } + + bool getlimitedDiscoverable() { + return _value& LE_GENERAL_DISCOVERABLE; + } + + bool getBrEdrNotSupported() { + return _value& LE_GENERAL_DISCOVERABLE; + } + + bool getSimultaneousLeBredrC() { + return _value& SIMULTANEOUS_LE_BREDR_C; + } + + bool getSimultaneousLeBredrH() { + return _value& SIMULTANEOUS_LE_BREDR_H; + } + + void clear() { + _value = 0; + } + + uint8_t value() { + return _value; + } + +private: + uint8_t _value; }; @@ -203,7 +250,7 @@ struct adv_data_flags_t :SafeEnum { * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. */ -struct adv_data_appearance_t :SafeEnum { +struct adv_data_appearance_t : SafeEnum { /** struct scoped enum wrapped by the class */ enum type { /** @@ -520,7 +567,7 @@ public: if (field) { switch(advDataType.value()) { - /* These types are append to existing field */ + /* These types are appended to the existing field */ case adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS: case adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS: case adv_data_type_t::INCOMPLETE_LIST_32BIT_SERVICE_IDS: @@ -539,17 +586,6 @@ public: } } - /** - * Clears the advertising data payload. - * - * @post getPayloadLen() returns 0. - */ - void clear() - { - memset(_buffer.data(), 0, _buffer.size()); - _payload_length = 0; - } - /** * Remove existing date of given type * @@ -569,6 +605,17 @@ public: } } + /** + * Clears the advertising data payload. + * + * @post getPayloadLen() returns 0. + */ + void clear() + { + memset(_buffer.data(), 0, _buffer.size()); + _payload_length = 0; + } + /** * Add device appearance in the advertising payload. * @@ -582,7 +629,7 @@ public: * adv_data_type_t::APPEARANCE as the field type. */ ble_error_t setAppearance( - adv_data_appearance_t appearance = adv_data_appearance_t::GENERIC_TAG + adv_data_appearance_t appearance ) { uint8_t appearence_byte = appearance.value(); mbed::Span appearance_span((const uint8_t*)&appearence_byte, 2); @@ -603,7 +650,7 @@ public: * adv_data_type_t::FLAGS as the field type. */ ble_error_t setFlags( - adv_data_flags_t flags = adv_data_flags_t::LE_GENERAL_DISCOVERABLE + adv_data_flags_t flags = adv_data_flags_t::default_flags ) { uint8_t flags_byte = flags.value(); mbed::Span flags_span((const uint8_t*)&flags_byte, 1); @@ -695,8 +742,7 @@ private: * Append data to a field in the advertising payload. * * @param[in] fieldData Span of data to add. - * @param[in] field Pointer to the field of type @p advDataType in the - * advertising buffer. + * @param[in] field Pointer to the field in the advertising buffer. * * @return BLE_ERROR_NONE on success. */ @@ -774,8 +820,7 @@ private: /** * Remove the field. * - * @param[in] field Pointer to the field of type @p advDataType in the - * advertising buffer. + * @param[in] field Pointer to the field in the advertising buffer. * * @return BLE_ERROR_NONE on success. */ From 0d95ccb4ba47605eabc01a1a93fb56bc17613fa6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 14:52:20 +0000 Subject: [PATCH 217/361] fix enum values --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 5867960508..e7c104d898 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -177,7 +177,7 @@ struct adv_data_flags_t { adv_data_flags_t& setLimitedDiscoverable(bool enable = true) { _value &= ~0x03; if (enable) { - _value |= LE_GENERAL_DISCOVERABLE; + _value |= LE_LIMITED_DISCOVERABLE; } return *this; } @@ -211,11 +211,11 @@ struct adv_data_flags_t { } bool getlimitedDiscoverable() { - return _value& LE_GENERAL_DISCOVERABLE; + return _value& LE_LIMITED_DISCOVERABLE; } bool getBrEdrNotSupported() { - return _value& LE_GENERAL_DISCOVERABLE; + return _value& BREDR_NOT_SUPPORTED; } bool getSimultaneousLeBredrC() { From b6a0c8aea5e4126f63d900ae66c13181e1fdc4cf Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 15:35:12 +0000 Subject: [PATCH 218/361] helper functinos --- .../ble/gap/AdvertisingDataBuilder.h | 134 +++++++++++------- 1 file changed, 83 insertions(+), 51 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index e7c104d898..1a58ecffb4 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -26,6 +26,7 @@ #include "ble/blecommon.h" #include "ble/SafeEnum.h" +#include "UUID.h" /** * @addtogroup ble @@ -549,9 +550,8 @@ public: * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the new value causes the advertising - * buffer to overflow. + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * * @note When the specified data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, @@ -610,8 +610,7 @@ public: * * @post getPayloadLen() returns 0. */ - void clear() - { + void clear() { memset(_buffer.data(), 0, _buffer.size()); _payload_length = 0; } @@ -621,9 +620,8 @@ public: * * @param[in] appearance The appearance to advertise. * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * * @note This call is equivalent to calling addData() with * adv_data_type_t::APPEARANCE as the field type. @@ -632,49 +630,83 @@ public: adv_data_appearance_t appearance ) { uint8_t appearence_byte = appearance.value(); - mbed::Span appearance_span((const uint8_t*)&appearence_byte, 2); + mbed::Span appearance_span((const uint8_t*) &appearence_byte, 2); return addData(adv_data_type_t::APPEARANCE, appearance_span); } /** - * Add BLE flags in the advertising payload. - * - * @param[in] flags Bitfield describing the capability of the device. See - * allowed flags in Flags_t. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - * - * @note This call is equivalent to calling addData() with - * adv_data_type_t::FLAGS as the field type. - */ - ble_error_t setFlags( - adv_data_flags_t flags = adv_data_flags_t::default_flags - ) { - uint8_t flags_byte = flags.value(); - mbed::Span flags_span((const uint8_t*)&flags_byte, 1); - return addData(adv_data_type_t::FLAGS, flags_span); - } + * Add BLE flags in the advertising payload. + * + * @param[in] flags Bitfield describing the capability of the device. See + * allowed flags in Flags_t. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * + * @note This call is equivalent to calling addData() with + * adv_data_type_t::FLAGS as the field type. + */ + ble_error_t setFlags( + adv_data_flags_t flags = adv_data_flags_t::default_flags + ) { + uint8_t flags_byte = flags.value(); + mbed::Span flags_span((const uint8_t*) &flags_byte, 1); + return addData(adv_data_type_t::FLAGS, flags_span); + } - /** - * Add the advertising TX in the advertising payload. - * - * @param[in] txPower Transmission power level in dB. - * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. - * - * @note This call is equivalent to calling addData() with - * adv_data_type_t::TX_POWER_LEVEL as the field type. - */ - ble_error_t setTxPowerAdvertised( - advertising_power_t txPower - ) { - mbed::Span power_span((const uint8_t*)&txPower, 1); - return addData(adv_data_type_t::TX_POWER_LEVEL, power_span); - } + /** + * Add the advertising TX in the advertising payload. + * + * @param[in] txPower Transmission power level in dB. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * + * @note This call is equivalent to calling addData() with + * adv_data_type_t::TX_POWER_LEVEL as the field type. + */ + ble_error_t setTxPowerAdvertised( + advertising_power_t txPower + ) { + mbed::Span power_span((const uint8_t*) &txPower, 1); + return addData(adv_data_type_t::TX_POWER_LEVEL, power_span); + } + + /** + * Add device name to the advertising payload. + * + * @param[in] name Null terminated string containing the name. + * @param[in] complete Complete local name if true, otherwise + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t setName( + const char* name, + bool complete = true + ) { + mbed::Span power_span((const uint8_t*)name, strlen(name)); + + if (complete) { + return addData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); + } else { + return addData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); + } + } + + /** + * Add manufacturer specific data to the advertising payload. + * + * @param[in] data New data to be added. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t setManufacturerSpecificData( + mbed::Span data + ) { + return addData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); + } private: /** @@ -684,7 +716,7 @@ private: * * @return A pointer to the first element in the field if found. The first * element being the length of the field followed by the value of the field. - * @return NULL if the field is not present in the payload. + * NULL if the field is not present in the payload. */ uint8_t* findField(adv_data_type_t type) { @@ -709,9 +741,8 @@ private: * @param[in] advDataType Type of the new data. * @param[in] fieldData Span of data to add. * - * @return BLE_ERROR_NONE on success. - * @return BLE_ERROR_BUFFER_OVERFLOW if the specified data would cause the - * advertising buffer to overflow. + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. */ ble_error_t addField( adv_data_type_t advDataType, @@ -787,7 +818,8 @@ private: * @param[in] field Pointer to the field of type @p advDataType in the * advertising buffer. * - * @return BLE_ERROR_NONE on success. + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. */ ble_error_t replaceField( adv_data_type_t advDataType, From 869bb308c5e546836228b54eb887845683df295f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 16 Nov 2018 16:34:57 +0000 Subject: [PATCH 219/361] BLE: Add API to manage GAP connection parameter updates. --- features/FEATURE_BLE/ble/Gap.h | 40 +++++- features/FEATURE_BLE/ble/gap/Events.h | 99 +++++++++++++- features/FEATURE_BLE/ble/generic/GenericGap.h | 45 +++++++ features/FEATURE_BLE/ble/pal/PalGap.h | 16 +++ features/FEATURE_BLE/source/Gap.cpp | 36 ++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 121 +++++++++++++++++- .../TARGET_CORDIO/source/CordioPalGap.cpp | 30 +++++ 7 files changed, 383 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 022b07a28b..0f5f4e87ce 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -324,9 +324,17 @@ public: * * @param event Connection event @see ConnectionCompleteEvent_t for details. */ - void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { } + virtual void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { } - void onDisconnection(const ble::DisconnectionEvent &event) { } + virtual void onUpdateConnectionParametersRequest( + const ble::UpdateConnectionParametersRequestEvent &event + ) { } + + virtual void onConnectionParametersUpdateComplete( + const ble::ConnectionParametersUpdateCompleteEvent &event + ) { } + + virtual void onDisconnection(const ble::DisconnectionEvent &event) { } /** * Function invoked when the current transmitter and receiver PHY have @@ -710,6 +718,34 @@ public: */ virtual ble_error_t cancelConnect(); + virtual ble_error_t updateConnectionParameters( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervision_timeout, + ble::conn_event_length_t minConnectionEventLength = ble::conn_event_length_t(0), + ble::conn_event_length_t maxConnectionEventLength = ble::conn_event_length_t(0) + ); + + virtual ble_error_t manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest + ); + + virtual ble_error_t acceptConnectionParametersUpdate( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervision_timeout, + ble::conn_event_length_t minConnectionEventLength = ble::conn_event_length_t(0), + ble::conn_event_length_t maxConnectionEventLength = ble::conn_event_length_t(0) + ); + + virtual ble_error_t rejectConnectionParametersUpdate( + ble::connection_handle_t connectionHandle + ); + /** * Initiate a disconnection procedure. * diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 845439427a..2b7a8cfbc2 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -552,7 +552,6 @@ private: const address_t &peerAddress; }; - struct DisconnectionEvent { DisconnectionEvent( connection_handle_t connectionHandle, @@ -574,6 +573,104 @@ private: ble::disconnection_reason_t reason; }; +struct UpdateConnectionParametersRequestEvent { + UpdateConnectionParametersRequestEvent( + connection_handle_t connectionHandle, + const conn_interval_t &minConnectionInterval, + const conn_interval_t &maxConnectionInterval, + const slave_latency_t &slaveLatency, + const supervision_timeout_t &supervision_timeout + ) : + connectionHandle(connectionHandle), + minConnectionInterval(minConnectionInterval), + maxConnectionInterval(maxConnectionInterval), + slaveLatency(slaveLatency), + supervisionTimeout(supervision_timeout) + { } + + connection_handle_t getConnectionHandle() const + { + return connectionHandle; + } + + const conn_interval_t &getMinConnectionInterval() const + { + return minConnectionInterval; + } + + const conn_interval_t &getMaxConnectionInterval() const + { + return maxConnectionInterval; + } + + const slave_latency_t &getSlaveLatency() const + { + return slaveLatency; + } + + const supervision_timeout_t &getSupervisionTimeout() const + { + return supervisionTimeout; + } + +private: + ble::connection_handle_t connectionHandle; + ble::conn_interval_t minConnectionInterval; + ble::conn_interval_t maxConnectionInterval; + ble::slave_latency_t slaveLatency; + ble::supervision_timeout_t supervisionTimeout; +}; + +struct ConnectionParametersUpdateCompleteEvent { + ConnectionParametersUpdateCompleteEvent( + ble_error_t status, + connection_handle_t connectionHandle, + const conn_interval_t &connectionInterval, + const slave_latency_t &slaveLatency, + const supervision_timeout_t &supervisionTimeout + ) : + status(status), + connectionHandle(connectionHandle), + connectionInterval(connectionInterval), + slaveLatency(slaveLatency), + supervisionTimeout(supervisionTimeout) + { } + + ble_error_t getStatus() const + { + return status; + } + + connection_handle_t getConnectionHandle() const + { + return connectionHandle; + } + + const conn_interval_t &getConnectionInterval() const + { + return connectionInterval; + } + + const slave_latency_t &getSlaveLatency() const + { + return slaveLatency; + } + + const supervision_timeout_t &getSupervisionTimeout() const + { + return supervisionTimeout; + } + +private: + ble_error_t status; + ble::connection_handle_t connectionHandle; + ble::conn_interval_t connectionInterval; + ble::slave_latency_t slaveLatency; + ble::supervision_timeout_t supervisionTimeout; + +}; + + } // namespace ble #endif //BLE_GAP_EVENTS_H diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 103bf26c8e..bcee4c6857 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -304,6 +304,34 @@ public: */ virtual ble_error_t cancelConnect(); + virtual ble_error_t manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest + ); + + virtual ble_error_t updateConnectionParameters( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervisionTimeout, + ble::conn_event_length_t minConnectionEventLength, + ble::conn_event_length_t maxConnectionEventLength + ); + + virtual ble_error_t acceptConnectionParametersUpdate( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervisionTimeout, + ble::conn_event_length_t minConnectionEventLength, + ble::conn_event_length_t maxConnectionEventLength + ); + + virtual ble_error_t rejectConnectionParametersUpdate( + ble::connection_handle_t connectionHandle + ); + /** * @see Gap::readPhy */ @@ -659,6 +687,22 @@ private: const ble::address_t &address ); + virtual void on_connection_update_complete( + pal::hci_error_code_t status, + connection_handle_t connection_handle, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout + ); + + virtual void on_remote_connection_parameter( + connection_handle_t connection_handle, + uint16_t connection_interval_min, + uint16_t connection_interval_max, + uint16_t connection_latency, + uint16_t supervision_timeout + ); + private: pal::EventQueue& _event_queue; pal::Gap &_pal_gap; @@ -722,6 +766,7 @@ private: // deprecation flags mutable bool _deprecated_scan_api_used : 1; mutable bool _non_deprecated_scan_api_used : 1; + bool _user_manage_connection_parameter_requests : 1; private: ble_error_t setExtendedAdvertisingParameters( diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index f04329e58b..391ef0a959 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -219,6 +219,22 @@ struct Gap { connection_peer_address_type_t scanner_address_type, const address_t &address ) = 0; + + virtual void on_connection_update_complete( + hci_error_code_t status, + connection_handle_t connection_handle, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout + ) = 0; + + virtual void on_remote_connection_parameter( + connection_handle_t connection_handle, + uint16_t connection_interval_min, + uint16_t connection_interval_max, + uint16_t connection_latency, + uint16_t supervision_timeout + ) = 0; }; /** diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index ba95146bed..98800da628 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -271,6 +271,42 @@ ble_error_t Gap::cancelConnect() { return BLE_ERROR_NOT_IMPLEMENTED; } +ble_error_t Gap::updateConnectionParameters( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervision_timeout, + ble::conn_event_length_t minConnectionEventLength, + ble::conn_event_length_t maxConnectionEventLength +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::acceptConnectionParametersUpdate( + ble::connection_handle_t connectionHandle, + ble::conn_interval_t minConnectionInterval, + ble::conn_interval_t maxConnectionInterval, + ble::slave_latency_t slaveLatency, + ble::supervision_timeout_t supervision_timeout, + ble::conn_event_length_t minConnectionEventLength, + ble::conn_event_length_t maxConnectionEventLength +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::rejectConnectionParametersUpdate( + ble::connection_handle_t connectionHandle +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + ble_error_t Gap::disconnect( ble::connection_handle_t connectionHandle, ble::local_disconnection_reason_t reason diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index df0b10225d..970448d04d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -419,7 +419,8 @@ GenericGap::GenericGap( _random_address_rotating(false), _advertising_timeout(), _scan_timeout(), - _connection_event_handler(NULL) + _connection_event_handler(NULL), + _user_manage_connection_parameter_requests(false) { _pal_gap.initialize(); @@ -646,6 +647,67 @@ ble_error_t GenericGap::connect( ); } +ble_error_t GenericGap::manageConnectionParametersUpdateRequest(bool flag) { + _user_manage_connection_parameter_requests = flag; +} + +ble_error_t GenericGap::updateConnectionParameters( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervisionTimeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength +) { + if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.connection_parameters_update( + connectionHandle, + minConnectionInterval.value(), + maxConnectionInterval.value(), + slaveLatency.value(), + supervisionTimeout.value(), + minConnectionEventLength.value(), + maxConnectionEventLength.value() + ); +} + +ble_error_t GenericGap::acceptConnectionParametersUpdate( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervisionTimeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength +) { + if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { + return BLE_ERROR_INVALID_PARAM; + } + + return _pal_gap.accept_connection_parameter_request( + connectionHandle, + minConnectionInterval.value(), + maxConnectionInterval.value(), + slaveLatency.value(), + supervisionTimeout.value(), + minConnectionEventLength.value(), + maxConnectionEventLength.value() + ); +} + +ble_error_t GenericGap::rejectConnectionParametersUpdate( + ble::connection_handle_t connectionHandle +) { + return _pal_gap.reject_connection_parameter_request( + connectionHandle, + pal::hci_error_code_t::UNACCEPTABLE_CONNECTION_PARAMETERS + ); +} + ble_error_t GenericGap::cancelConnect() { return _pal_gap.cancel_connection_creation(); @@ -2374,6 +2436,63 @@ void GenericGap::on_scan_request_received( ); } +void GenericGap::on_connection_update_complete( + pal::hci_error_code_t status, + connection_handle_t connection_handle, + uint16_t connection_interval, + uint16_t connection_latency, + uint16_t supervision_timeout +) { + if (!_eventHandler) { + return; + } + + _eventHandler->onConnectionParametersUpdateComplete( + ConnectionParametersUpdateCompleteEvent( + status == pal::hci_error_code_t::SUCCESS ? BLE_ERROR_NONE : BLE_ERROR_UNSPECIFIED, + connection_handle, + conn_interval_t(connection_interval), + slave_latency_t(connection_latency), + supervision_timeout_t(supervision_timeout) + ) + ); +} + +void GenericGap::on_remote_connection_parameter( + connection_handle_t connection_handle, + uint16_t connection_interval_min, + uint16_t connection_interval_max, + uint16_t connection_latency, + uint16_t supervision_timeout +) { + if (_user_manage_connection_parameter_requests) { + // ignore for now as it is + _pal_gap.accept_connection_parameter_request( + connection_handle, + connection_interval_min, + connection_interval_max, + connection_latency, + supervision_timeout, + /* connection event length min */ 0, + /* connection event length max */ 0 + ); + } else { + if (!_eventHandler) { + return; + } + + _eventHandler->onUpdateConnectionParametersRequest( + UpdateConnectionParametersRequestEvent( + connection_handle, + conn_interval_t(connection_interval_min), + conn_interval_t(connection_interval_max), + connection_latency, + supervision_timeout_t(supervision_timeout) + ) + ); + } +} + ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) { useVersionTwoAPI(); diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index cc867679f6..d2034d4fd0 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -560,6 +560,36 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->pData ); } break; + + case DM_CONN_UPDATE_IND: { + if (!handler) { + break; + } + + const hciLeConnUpdateCmplEvt_t* evt = (const hciLeConnUpdateCmplEvt_t*) msg; + handler->on_connection_update_complete( + (hci_error_code_t::type) evt->status, + evt->hdr.param, + evt->connInterval, + evt->connLatency, + evt->supTimeout + ); + } break; + + case DM_REM_CONN_PARAM_REQ_IND: { + if (!handler) { + break; + } + + const hciLeRemConnParamReqEvt_t* evt = (const hciLeRemConnParamReqEvt_t*) msg; + handler->on_remote_connection_parameter( + evt->hdr.param, + evt->intervalMin, + evt->intervalMax, + evt->latency, + evt->timeout + ); + } break; } // all handlers are stored in a static array From 4b6eede76b08f0e2ac66f4454ea55efdd58c7e60 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 18:31:15 +0000 Subject: [PATCH 220/361] UUID handling --- features/FEATURE_BLE/ble/blecommon.h | 5 + .../ble/gap/AdvertisingDataBuilder.h | 132 +++++++++++++++++- 2 files changed, 136 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/blecommon.h b/features/FEATURE_BLE/ble/blecommon.h index 971f10c6aa..c390d7f867 100644 --- a/features/FEATURE_BLE/ble/blecommon.h +++ b/features/FEATURE_BLE/ble/blecommon.h @@ -210,6 +210,11 @@ enum ble_error_t { * The platform-specific stack failed. */ BLE_ERROR_INTERNAL_STACK_FAILURE = 12, + + /** + * Data not found or there is nothing to return. + */ + BLE_ERROR_NOT_FOUND = 13 }; /** diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 1a58ecffb4..3f238de0c0 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -601,7 +601,7 @@ public: if (field) { return removeField(field); } else { - return BLE_ERROR_INVALID_PARAM; + return BLE_ERROR_NOT_FOUND; } } @@ -708,6 +708,136 @@ public: return addData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); } + /** + * Add manufacturer specific data to the advertising payload. + * + * @param[in] data New data to be added. + * @param[in] complete True if this is a complete list. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t setLocalServiceList( + mbed::Span data, + bool complete = true + ) { + ble_error_t status = BLE_ERROR_NONE; + + /* first count all the bytes we need to store all the UUIDs */ + size_t size_incomplete_16 = 0; + size_t size_complete_16 = 0; + size_t size_incomplete_128 = 0; + size_t size_complete_128 = 0; + for (size_t i = 0; i < data.size(); ++i) { + if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { + if (complete) { + size_incomplete_16++; + } else { + size_complete_16++; + } + } else { + if (complete) { + size_incomplete_128++; + } else { + size_complete_128++; + } + } + } + + /* calculate total size including headers for types */ + size_t total_size = size_incomplete_16 + (!!size_incomplete_16) * 2 + + size_complete_16 + (!!size_complete_16) * 2 + + size_incomplete_128 + (!!size_incomplete_128) * 2 + + size_complete_128 + (!!size_complete_128) * 2; + + /* count all the bytes of existing data */ + size_t old_size = 0; + mbed::Span existing_data; + if (getData(existing_data, adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS) == BLE_ERROR_NONE) { + old_size += existing_data.size() + 2; + } + if (getData(existing_data, adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS) == BLE_ERROR_NONE) { + old_size += existing_data.size() + 2; + } + if (getData(existing_data, adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS) == BLE_ERROR_NONE) { + old_size += existing_data.size() + 2; + } + if (getData(existing_data, adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS) == BLE_ERROR_NONE) { + old_size += existing_data.size() + 2; + } + + /* if we can't fit the new data do not proceed */ + if (total_size - old_size > data.size() - _payload_length) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* otherwise wipe old data */ + removeData(adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS); + removeData(adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS); + removeData(adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS); + removeData(adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS); + + /* and insert individual UUIDs into appropriate fields */ + for (size_t i = 0; i < data.size(); ++i) { + adv_data_type_t field_type(adv_data_type_t::FLAGS); + if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { + if (complete) { + field_type = adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; + } else { + field_type = adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS; + } + } else { + if (complete) { + field_type = adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; + } else { + field_type = adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS; + } + } + + mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); + + uint8_t *field = findField(field_type); + + if (field) { + status = appendToField(span, field); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } else { + status = addField(field_type, span); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } + } + + return status; + } + + /** + * Return a span of data containing the the type of data requested. + * + * @param[out] data Span used to return the requested data. + * @param[in] advDataType Data type to return. + * + * @return BLE_ERROR_NONE if data was found and BLE_ERROR_NOT_FOUND if not. + */ + ble_error_t getData( + mbed::Span &data, + adv_data_type_t advDataType + ) { + uint8_t *field = findField(advDataType); + if (field) { + uint8_t data_length = field[0] - 1 /* skip type */; + data = mbed::make_Span((const uint8_t*)(field + 2 /* skip type and length */), data_length); + return BLE_ERROR_NONE; + } else { + return BLE_ERROR_NOT_FOUND; + } + } + private: /** * Search advertisement data for a specific field. From 4a850207fa81420b1330544f4c99ff78fa6626b8 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 18:41:43 +0000 Subject: [PATCH 221/361] remove redundant calulations --- .../ble/gap/AdvertisingDataBuilder.h | 46 +++++++------------ 1 file changed, 17 insertions(+), 29 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 3f238de0c0..57dd08f7c0 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -724,31 +724,19 @@ public: ble_error_t status = BLE_ERROR_NONE; /* first count all the bytes we need to store all the UUIDs */ - size_t size_incomplete_16 = 0; - size_t size_complete_16 = 0; - size_t size_incomplete_128 = 0; - size_t size_complete_128 = 0; + size_t size_long = 0; + size_t size_short = 0; for (size_t i = 0; i < data.size(); ++i) { if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - if (complete) { - size_incomplete_16++; - } else { - size_complete_16++; - } + size_short++; } else { - if (complete) { - size_incomplete_128++; - } else { - size_complete_128++; - } + size_long++; } } /* calculate total size including headers for types */ - size_t total_size = size_incomplete_16 + (!!size_incomplete_16) * 2 + - size_complete_16 + (!!size_complete_16) * 2 + - size_incomplete_128 + (!!size_incomplete_128) * 2 + - size_complete_128 + (!!size_complete_128) * 2; + size_t total_size = size_long + (!!size_long) * 2 + + size_short + (!!size_short) * 2; /* count all the bytes of existing data */ size_t old_size = 0; @@ -767,7 +755,7 @@ public: } /* if we can't fit the new data do not proceed */ - if (total_size - old_size > data.size() - _payload_length) { + if (total_size > data.size() - (_payload_length - old_size)) { return BLE_ERROR_BUFFER_OVERFLOW; } @@ -777,21 +765,21 @@ public: removeData(adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS); removeData(adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS); + const adv_data_type_t short_type = complete ? + adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS : + adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; + + const adv_data_type_t long_type = complete ? + adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS : + adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; + /* and insert individual UUIDs into appropriate fields */ for (size_t i = 0; i < data.size(); ++i) { adv_data_type_t field_type(adv_data_type_t::FLAGS); if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - if (complete) { - field_type = adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; - } else { - field_type = adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS; - } + field_type = short_type; } else { - if (complete) { - field_type = adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; - } else { - field_type = adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS; - } + field_type = long_type; } mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); From 0b1b07f9f166f9961194bb028ff437a5441b2f37 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 19:32:20 +0000 Subject: [PATCH 222/361] service data --- .../ble/gap/AdvertisingDataBuilder.h | 70 +++++++++++++++---- 1 file changed, 55 insertions(+), 15 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 57dd08f7c0..b28d2b702a 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -709,7 +709,48 @@ public: } /** - * Add manufacturer specific data to the advertising payload. + * Add service data data to the advertising payload. + * + * @param[in] service UUID of the service. + * @param[in] data New data to be added. + * @param[in] complete True if this is a complete list. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t setServiceData( + UUID service, + mbed::Span data + ) { + size_t total_size = data.size() + service.getLen() + 2; + size_t old_size = getFieldSize(adv_data_type_t::SERVICE_DATA); + + /* if we can't fit the new data do not proceed */ + if (total_size > data.size() - (_payload_length - old_size)) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + if (old_size) { + removeData(adv_data_type_t::SERVICE_DATA); + } + + ble_error_t status1 = addData( + adv_data_type_t::SERVICE_DATA, + mbed::make_Span(service.getBaseUUID(), service.getLen()) + ); + + ble_error_t status2 = addData(adv_data_type_t::SERVICE_DATA, data); + + if (status1 != BLE_ERROR_NONE || status2 != BLE_ERROR_NONE) { + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + return BLE_ERROR_NONE; + } + + /** + * Add local service IDs to the advertising payload. If they data can't fit + * no modification will take place. * * @param[in] data New data to be added. * @param[in] complete True if this is a complete list. @@ -739,20 +780,10 @@ public: size_short + (!!size_short) * 2; /* count all the bytes of existing data */ - size_t old_size = 0; - mbed::Span existing_data; - if (getData(existing_data, adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS) == BLE_ERROR_NONE) { - old_size += existing_data.size() + 2; - } - if (getData(existing_data, adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS) == BLE_ERROR_NONE) { - old_size += existing_data.size() + 2; - } - if (getData(existing_data, adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS) == BLE_ERROR_NONE) { - old_size += existing_data.size() + 2; - } - if (getData(existing_data, adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS) == BLE_ERROR_NONE) { - old_size += existing_data.size() + 2; - } + size_t old_size = getFieldSize(adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS) + + getFieldSize(adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS) + + getFieldSize(adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS) + + getFieldSize(adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS); /* if we can't fit the new data do not proceed */ if (total_size > data.size() - (_payload_length - old_size)) { @@ -853,6 +884,15 @@ private: return NULL; } + size_t getFieldSize(adv_data_type_t type) { + uint8_t *field = findField(type); + if (field) { + return field[0] + 1; + } else { + return 0; + } + } + /** * Append advertising data based on the specified type. * From 7ab45e4c095a1cc4b51934d4f3f0542e36996927 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 19:56:11 +0000 Subject: [PATCH 223/361] individual operations --- .../ble/gap/AdvertisingDataBuilder.h | 152 +++++++++++++----- 1 file changed, 115 insertions(+), 37 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index b28d2b702a..d75ca13a2f 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -542,52 +542,75 @@ public: } /** - * Adds a new field into the payload. - * - * If the supplied advertising data type is already present in the - * advertising payload, then the value is updated. + * Add a new field into the payload. Will return an error if type is already present. * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. - * - * @note When the specified data type is INCOMPLETE_LIST_16BIT_SERVICE_IDS, - * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS, - * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS, - * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS, the - * supplied value is appended to the values present in the payload. + * @retval BLE_ERROR_OPERATION_NOT_PERMITTED if data type already present. */ ble_error_t addData( adv_data_type_t advDataType, mbed::Span fieldData + ) { + if (findField(advDataType)) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } else { + return addField(advDataType, fieldData); + } + } + + /** + * Replace a new field into the payload. Will fail if type is not already present. + * + * @param[in] advDataType The type of the field to add. + * @param[in] fieldData Span of data to add. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_NOT_FOUND if data type not present. + */ + ble_error_t replaceData( + adv_data_type_t advDataType, + mbed::Span fieldData ) { uint8_t* field = findField(advDataType); if (field) { - switch(advDataType.value()) { - /* These types are appended to the existing field */ - case adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS: - case adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS: - case adv_data_type_t::INCOMPLETE_LIST_32BIT_SERVICE_IDS: - case adv_data_type_t::COMPLETE_LIST_32BIT_SERVICE_IDS: - case adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS: - case adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS: - case adv_data_type_t::LIST_128BIT_SOLICITATION_IDS: - return appendToField(fieldData, field); - default: - /* All other types have their field contents replaced */ - return replaceField(advDataType, fieldData, field); - } + return replaceField(advDataType, fieldData, field); } else { - /* field doesn't exist, add it */ - return addField(advDataType, fieldData); + return BLE_ERROR_NOT_FOUND; } } /** - * Remove existing date of given type + * Append data to an existing field in the payload. Will fail if type is not already + * present. + * + * @param[in] advDataType The type of the field to add. + * @param[in] fieldData Span of data to add. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_NOT_FOUND if data type not present. + */ + ble_error_t appendData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { + uint8_t* field = findField(advDataType); + + if (field) { + return appendToField(fieldData, field); + } else { + return BLE_ERROR_NOT_FOUND; + } + } + + /** + * Remove existing date of given type. Will return an error if type is not present. * * @param[in] advDataType The type of the field to remove. * @@ -605,6 +628,53 @@ public: } } + + /** + * Adds a new field into the payload. If the supplied advertising data type is + * already present in the advertising payload, then the value is replaced. + * + * @param[in] advDataType The type of the field to add. + * @param[in] fieldData Span of data to add. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t addOrReplaceData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { + uint8_t* field = findField(advDataType); + + if (field) { + return replaceField(advDataType, fieldData, field); + } else { + return addField(advDataType, fieldData); + } + } + + /** + * Adds a new field into the payload. If the supplied advertising data type is + * already present in the advertising payload, then the value is replaced. + * + * @param[in] advDataType The type of the field to add. + * @param[in] fieldData Span of data to add. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ + ble_error_t addOrAppendData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) { + uint8_t* field = findField(advDataType); + + if (field) { + return appendToField(fieldData, field); + } else { + return addField(advDataType, fieldData); + } + } + /** * Clears the advertising data payload. * @@ -623,7 +693,7 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * - * @note This call is equivalent to calling addData() with + * @note This call is equivalent to calling addOrReplaceData() with * adv_data_type_t::APPEARANCE as the field type. */ ble_error_t setAppearance( @@ -631,7 +701,7 @@ public: ) { uint8_t appearence_byte = appearance.value(); mbed::Span appearance_span((const uint8_t*) &appearence_byte, 2); - return addData(adv_data_type_t::APPEARANCE, appearance_span); + return addOrReplaceData(adv_data_type_t::APPEARANCE, appearance_span); } /** @@ -643,7 +713,7 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * - * @note This call is equivalent to calling addData() with + * @note This call is equivalent to calling addOrReplaceData() with * adv_data_type_t::FLAGS as the field type. */ ble_error_t setFlags( @@ -651,7 +721,7 @@ public: ) { uint8_t flags_byte = flags.value(); mbed::Span flags_span((const uint8_t*) &flags_byte, 1); - return addData(adv_data_type_t::FLAGS, flags_span); + return addOrReplaceData(adv_data_type_t::FLAGS, flags_span); } /** @@ -662,14 +732,14 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * - * @note This call is equivalent to calling addData() with + * @note This call is equivalent to calling addOrReplaceData() with * adv_data_type_t::TX_POWER_LEVEL as the field type. */ ble_error_t setTxPowerAdvertised( advertising_power_t txPower ) { mbed::Span power_span((const uint8_t*) &txPower, 1); - return addData(adv_data_type_t::TX_POWER_LEVEL, power_span); + return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, power_span); } /** @@ -688,9 +758,9 @@ public: mbed::Span power_span((const uint8_t*)name, strlen(name)); if (complete) { - return addData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); + return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); } else { - return addData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); + return addOrReplaceData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); } } @@ -705,7 +775,15 @@ public: ble_error_t setManufacturerSpecificData( mbed::Span data ) { - return addData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); + return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); + } + + + ble_error_t setAdvertisingInterval(adv_interval_t interval) { + return addOrReplaceData( + adv_data_type_t::ADVERTISING_INTERVAL, + mbed::make_Span((const uint8_t*)interval.storage(), 2) + ); } /** @@ -739,7 +817,7 @@ public: mbed::make_Span(service.getBaseUUID(), service.getLen()) ); - ble_error_t status2 = addData(adv_data_type_t::SERVICE_DATA, data); + ble_error_t status2 = appendData(adv_data_type_t::SERVICE_DATA, data); if (status1 != BLE_ERROR_NONE || status2 != BLE_ERROR_NONE) { return BLE_ERROR_INTERNAL_STACK_FAILURE; From 656aa4fa4c00e65b822fba047852f3825d6291f1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 20:17:45 +0000 Subject: [PATCH 224/361] CONNECTION INTERVAL HELPER --- .../ble/gap/AdvertisingDataBuilder.h | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index d75ca13a2f..96a9a8f7c0 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -778,14 +778,28 @@ public: return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); } - - ble_error_t setAdvertisingInterval(adv_interval_t interval) { + ble_error_t setAdvertisingInterval( + adv_interval_t interval + ) { return addOrReplaceData( adv_data_type_t::ADVERTISING_INTERVAL, mbed::make_Span((const uint8_t*)interval.storage(), 2) ); } + ble_error_t setConnectionIntervalPreference( + conn_interval_t min, + conn_interval_t max + ) { + uint32_t interval = max.value(); + interval = interval << 16; + interval |= min.value(); + return addOrReplaceData( + adv_data_type_t::SLAVE_CONNECTION_INTERVAL_RANGE, + mbed::make_Span((const uint8_t*)&interval, 4) + ); + } + /** * Add service data data to the advertising payload. * From aefd92a8385c16ff3e477c892abbe6d033168c4c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Fri, 16 Nov 2018 20:21:41 +0000 Subject: [PATCH 225/361] docs --- .../ble/gap/AdvertisingDataBuilder.h | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 96a9a8f7c0..0f2c998a08 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -778,6 +778,14 @@ public: return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); } + /** + * Add advertising interval to the payload + * + * @param interval Interval to advertise. + + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ ble_error_t setAdvertisingInterval( adv_interval_t interval ) { @@ -787,6 +795,15 @@ public: ); } + /** + * Add connection interval preferences to the payload + * + * @param min Minimum connection interval to advertise. + * @param max Maximum connection interval to advertise. + + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + */ ble_error_t setConnectionIntervalPreference( conn_interval_t min, conn_interval_t max @@ -976,6 +993,13 @@ private: return NULL; } + /** + * Get field size (includes type and size bytes) + * + * @param type The field type. + * + * @return Size of the whole field including type and size bytes. + */ size_t getFieldSize(adv_data_type_t type) { uint8_t *field = findField(type); if (field) { From 91fa548953af8be6cf6a139010b6064798d1b477 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 09:31:55 +0000 Subject: [PATCH 226/361] verify parameters --- .../ble/gap/AdvertisingDataBuilder.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 0f2c998a08..76826c0b88 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -779,16 +779,21 @@ public: } /** - * Add advertising interval to the payload + * Add advertising interval to the payload. This field can only carry 2 bytes. * - * @param interval Interval to advertise. + * @param interval Interval to advertise. Cannot be larger than 0xFFFF. * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if interval value outside of valid range. */ ble_error_t setAdvertisingInterval( adv_interval_t interval ) { + if (interval.value() > 0xFFFF) { + return BLE_ERROR_INVALID_PARAM; + } + return addOrReplaceData( adv_data_type_t::ADVERTISING_INTERVAL, mbed::make_Span((const uint8_t*)interval.storage(), 2) @@ -820,7 +825,7 @@ public: /** * Add service data data to the advertising payload. * - * @param[in] service UUID of the service. + * @param[in] service UUID of the service. Must be a 16bit UUID. * @param[in] data New data to be added. * @param[in] complete True if this is a complete list. * @@ -831,6 +836,10 @@ public: UUID service, mbed::Span data ) { + if (service.getLen() != 2) { + return BLE_ERROR_INVALID_PARAM; + } + size_t total_size = data.size() + service.getLen() + 2; size_t old_size = getFieldSize(adv_data_type_t::SERVICE_DATA); @@ -845,7 +854,7 @@ public: ble_error_t status1 = addData( adv_data_type_t::SERVICE_DATA, - mbed::make_Span(service.getBaseUUID(), service.getLen()) + mbed::make_Span(service.getBaseUUID(), 2) ); ble_error_t status2 = appendData(adv_data_type_t::SERVICE_DATA, data); From 92cbec3e410f6c6d9a0443bb30ecc3a8af02614f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 09:54:09 +0000 Subject: [PATCH 227/361] requested services --- .../ble/gap/AdvertisingDataBuilder.h | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 76826c0b88..41a636dff6 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -953,6 +953,73 @@ public: return status; } + /** + * Add a list of UUIDs of solicited services. + * + * @param[in] data List of 128 bit service UUIDs. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if list contains short 16 bit IDs. + */ + ble_error_t setRequestedServiceList( + mbed::Span data + ) { + ble_error_t status = BLE_ERROR_NONE; + + /* first count all the bytes we need to store all the UUIDs */ + size_t size_long = 0; + for (size_t i = 0; i < data.size(); ++i) { + if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { + return BLE_ERROR_INVALID_PARAM; + } else { + size_long++; + } + } + + /* calculate total size including headers for types */ + size_t total_size = size_long + (!!size_long) * 2; + + /* count all the bytes of existing data */ + size_t old_size = getFieldSize(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); + + /* if we can't fit the new data do not proceed */ + if (total_size > data.size() - (_payload_length - old_size)) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* otherwise wipe old data */ + removeData(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); + + if (!size_long) { + /* the list is empty, we removed the old one, nothing to add */ + return BLE_ERROR_NONE; + } + + mbed::Span span; + status = addField(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS, span); + + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + uint8_t *field = findField(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); + + /* and insert individual UUIDs into appropriate fields */ + for (size_t i = 0; i < data.size(); ++i) { + span = mbed::make_Span(data[i].getBaseUUID(), data[i].getLen()); + + status = appendToField(span, field); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } + + return status; + } + /** * Return a span of data containing the the type of data requested. * From acd7ec3572f25917bc993a4d5e3a402b707a8733 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 12:00:40 +0000 Subject: [PATCH 228/361] check sizes, use memcpy --- .../ble/gap/AdvertisingDataBuilder.h | 111 ++++++++++++------ 1 file changed, 77 insertions(+), 34 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 41a636dff6..2017e4e5e1 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -111,6 +111,11 @@ struct adv_data_type_t : SafeEnum { */ SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, + /** + * List of 128-bit service UUIDs the device is looking for. + */ + LIST_16BIT_SOLICITATION_IDS = 0x14, + /** * List of 128-bit service UUIDs the device is looking for. */ @@ -544,6 +549,8 @@ public: /** * Add a new field into the payload. Will return an error if type is already present. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * @@ -565,6 +572,8 @@ public: /** * Replace a new field into the payload. Will fail if type is not already present. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * @@ -589,6 +598,8 @@ public: * Append data to an existing field in the payload. Will fail if type is not already * present. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * @@ -628,11 +639,12 @@ public: } } - /** * Adds a new field into the payload. If the supplied advertising data type is * already present in the advertising payload, then the value is replaced. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * @@ -656,6 +668,8 @@ public: * Adds a new field into the payload. If the supplied advertising data type is * already present in the advertising payload, then the value is replaced. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType The type of the field to add. * @param[in] fieldData Span of data to add. * @@ -745,6 +759,8 @@ public: /** * Add device name to the advertising payload. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] name Null terminated string containing the name. * @param[in] complete Complete local name if true, otherwise * @@ -767,6 +783,8 @@ public: /** * Add manufacturer specific data to the advertising payload. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] data New data to be added. * * @retval BLE_ERROR_NONE on success. @@ -825,6 +843,8 @@ public: /** * Add service data data to the advertising payload. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] service UUID of the service. Must be a 16bit UUID. * @param[in] data New data to be added. * @param[in] complete True if this is a complete list. @@ -836,6 +856,10 @@ public: UUID service, mbed::Span data ) { + if (data.size() > 0xFF) { + return BLE_ERROR_INVALID_PARAM; + } + if (service.getLen() != 2) { return BLE_ERROR_INVALID_PARAM; } @@ -870,6 +894,8 @@ public: * Add local service IDs to the advertising payload. If they data can't fit * no modification will take place. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] data New data to be added. * @param[in] complete True if this is a complete list. * @@ -893,6 +919,10 @@ public: } } + if ((size_long > 0xFF) || (size_short > 0xFF)) { + return BLE_ERROR_INVALID_PARAM; + } + /* calculate total size including headers for types */ size_t total_size = size_long + (!!size_long) * 2 + size_short + (!!size_short) * 2; @@ -956,11 +986,12 @@ public: /** * Add a list of UUIDs of solicited services. * - * @param[in] data List of 128 bit service UUIDs. + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data List of 128 or 16 bit service UUIDs. * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. - * @retval BLE_ERROR_INVALID_PARAM if list contains short 16 bit IDs. */ ble_error_t setRequestedServiceList( mbed::Span data @@ -1076,7 +1107,7 @@ private: * * @return Size of the whole field including type and size bytes. */ - size_t getFieldSize(adv_data_type_t type) { + uint8_t getFieldSize(adv_data_type_t type) { uint8_t *field = findField(type); if (field) { return field[0] + 1; @@ -1088,6 +1119,8 @@ private: /** * Append advertising data based on the specified type. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType Type of the new data. * @param[in] fieldData Span of data to add. * @@ -1098,13 +1131,16 @@ private: adv_data_type_t advDataType, mbed::Span fieldData ) { + if (fieldData.size() > 0xFF) { + return BLE_ERROR_INVALID_PARAM; + } /* Make sure we don't exceed the buffer size */ if (_payload_length + fieldData.size() + 2 > _buffer.size()) { return BLE_ERROR_BUFFER_OVERFLOW; } - /* Field length. */ + /* Field length (includes field ID byte) */ _buffer[_payload_length] = fieldData.size() + 1; ++_payload_length; @@ -1122,6 +1158,8 @@ private: /** * Append data to a field in the advertising payload. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] fieldData Span of data to add. * @param[in] field Pointer to the field in the advertising buffer. * @@ -1131,24 +1169,30 @@ private: mbed::Span fieldData, uint8_t* field ) { + if (fieldData.size() + field[0] > 0xFF) { + return BLE_ERROR_INVALID_PARAM; + } + /* Check if data fits */ if ((_payload_length + fieldData.size()) <= _buffer.size()) { - /* - * Make room for new field by moving the remainder of the - * advertisement payload "to the right" starting after the - * TYPE field. - */ - uint8_t* end = _buffer.data() + _payload_length; + uint8_t old_data_length = field[0]; - while (&field[1] < end) { - end[fieldData.size()] = *end; - end--; + /* get the size of bytes in the payload after the field */ + size_t remainder_size = _payload_length - + (field - _buffer.data()) - /* length of all data before the field */ + (old_data_length + 1) /* length of the old field */; + + /* move data after the field to fit new data */ + if (remainder_size) { + memmove( + field + old_data_length + 1 + fieldData.size(), + field + old_data_length + 1, + remainder_size + ); } - /* Insert new data */ - for (uint8_t idx = 0; idx < fieldData.size(); idx++) { - field[2 + idx] = fieldData[idx]; - } + /* append new data */ + memcpy(field + old_data_length + 1, fieldData.data(), fieldData.size()); /* Increment lengths */ field[0] += fieldData.size(); @@ -1163,6 +1207,8 @@ private: /** * Update in place the value of a field in the advertising payload. * + * @note Data size for individual types cannot exceed 255 bytes. + * * @param[in] advDataType Type of the new data. * @param[in] fieldData Span of data to add. * @param[in] field Pointer to the field of type @p advDataType in the @@ -1176,27 +1222,28 @@ private: mbed::Span fieldData, uint8_t* field ) { - ble_error_t result = BLE_ERROR_BUFFER_OVERFLOW; + if (fieldData.size() > 0xFF) { + return BLE_ERROR_INVALID_PARAM; + } + uint8_t old_data_length = field[0] - 1; /* New data has same length, do in-order replacement */ if (fieldData.size() == old_data_length) { - for (uint8_t idx = 0; idx < old_data_length; idx++) { - field[2 + idx] = fieldData[idx]; - } + memcpy(field + 2, fieldData.data(), old_data_length); - result = BLE_ERROR_NONE; + return BLE_ERROR_NONE; } else { /* Check if data fits */ if ((_payload_length - old_data_length + fieldData.size()) <= _buffer.size()) { removeField(field); /* Add new field */ - result = addField(advDataType, fieldData); + return addField(advDataType, fieldData); + } else { + return BLE_ERROR_BUFFER_OVERFLOW; } } - - return result; } /** @@ -1209,16 +1256,12 @@ private: ble_error_t removeField( uint8_t* field ) { - uint8_t old_data_length = field[0] - 1; + /* stored length + the byte containing length */ + uint8_t old_field_length = field[0] + 1; - /* Remove old field */ - while ((field + old_data_length + 2) < _buffer.data() + _payload_length) { - *field = field[old_data_length + 2]; - field++; - } + memmove(field, field + old_field_length, old_field_length); - /* Reduce length */ - _payload_length -= old_data_length + 2; + _payload_length -= old_field_length; return BLE_ERROR_NONE; } From e54c0ed1de7b6711901839c23e14e7183d3d049d Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 13:13:58 +0000 Subject: [PATCH 229/361] simplify UUID funcs --- .../ble/gap/AdvertisingDataBuilder.h | 215 ++++++++---------- 1 file changed, 94 insertions(+), 121 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 2017e4e5e1..dbd84f0fc4 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -557,6 +557,7 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_OPERATION_NOT_PERMITTED if data type already present. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t addData( adv_data_type_t advDataType, @@ -580,6 +581,7 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_NOT_FOUND if data type not present. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t replaceData( adv_data_type_t advDataType, @@ -606,6 +608,7 @@ public: * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_NOT_FOUND if data type not present. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t appendData( adv_data_type_t advDataType, @@ -650,6 +653,7 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t addOrReplaceData( adv_data_type_t advDataType, @@ -675,6 +679,7 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t addOrAppendData( adv_data_type_t advDataType, @@ -766,6 +771,7 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t setName( const char* name, @@ -789,6 +795,7 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t setManufacturerSpecificData( mbed::Span data @@ -851,6 +858,7 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ ble_error_t setServiceData( UUID service, @@ -901,86 +909,21 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if number of UUIDs of any one type is too high. */ ble_error_t setLocalServiceList( mbed::Span data, bool complete = true ) { - ble_error_t status = BLE_ERROR_NONE; - - /* first count all the bytes we need to store all the UUIDs */ - size_t size_long = 0; - size_t size_short = 0; - for (size_t i = 0; i < data.size(); ++i) { - if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - size_short++; - } else { - size_long++; - } - } - - if ((size_long > 0xFF) || (size_short > 0xFF)) { - return BLE_ERROR_INVALID_PARAM; - } - - /* calculate total size including headers for types */ - size_t total_size = size_long + (!!size_long) * 2 + - size_short + (!!size_short) * 2; - - /* count all the bytes of existing data */ - size_t old_size = getFieldSize(adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS) + - getFieldSize(adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS) + - getFieldSize(adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS) + - getFieldSize(adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS); - - /* if we can't fit the new data do not proceed */ - if (total_size > data.size() - (_payload_length - old_size)) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* otherwise wipe old data */ - removeData(adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS); - removeData(adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS); - removeData(adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS); - removeData(adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS); - - const adv_data_type_t short_type = complete ? + adv_data_type_t short_type = complete ? adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS : adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; - const adv_data_type_t long_type = complete ? + adv_data_type_t long_type = complete ? adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS : adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; - /* and insert individual UUIDs into appropriate fields */ - for (size_t i = 0; i < data.size(); ++i) { - adv_data_type_t field_type(adv_data_type_t::FLAGS); - if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - field_type = short_type; - } else { - field_type = long_type; - } - - mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); - - uint8_t *field = findField(field_type); - - if (field) { - status = appendToField(span, field); - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - } else { - status = addField(field_type, span); - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - } - } - - return status; + return setUUIDData(data, short_type, long_type); } /** @@ -992,63 +935,15 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if number of UUIDs of any one type is too high. */ ble_error_t setRequestedServiceList( mbed::Span data ) { - ble_error_t status = BLE_ERROR_NONE; + adv_data_type_t short_type = adv_data_type_t::LIST_16BIT_SOLICITATION_IDS; + adv_data_type_t long_type = adv_data_type_t::LIST_128BIT_SOLICITATION_IDS; - /* first count all the bytes we need to store all the UUIDs */ - size_t size_long = 0; - for (size_t i = 0; i < data.size(); ++i) { - if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - return BLE_ERROR_INVALID_PARAM; - } else { - size_long++; - } - } - - /* calculate total size including headers for types */ - size_t total_size = size_long + (!!size_long) * 2; - - /* count all the bytes of existing data */ - size_t old_size = getFieldSize(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); - - /* if we can't fit the new data do not proceed */ - if (total_size > data.size() - (_payload_length - old_size)) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* otherwise wipe old data */ - removeData(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); - - if (!size_long) { - /* the list is empty, we removed the old one, nothing to add */ - return BLE_ERROR_NONE; - } - - mbed::Span span; - status = addField(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS, span); - - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - - uint8_t *field = findField(adv_data_type_t::LIST_128BIT_SOLICITATION_IDS); - - /* and insert individual UUIDs into appropriate fields */ - for (size_t i = 0; i < data.size(); ++i) { - span = mbed::make_Span(data[i].getBaseUUID(), data[i].getLen()); - - status = appendToField(span, field); - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - } - - return status; + return setUUIDData(data, short_type, long_type); } /** @@ -1266,6 +1161,84 @@ private: return BLE_ERROR_NONE; } + /** + * Add a list of UUIDs to given types. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data List of 128 or 16 bit service UUIDs. + * @param[in] shortType Type of field to add the short UUIDs to. + * @param[in] longType Type of field to add the long UUIDs to. + * + * @retval BLE_ERROR_NONE on success. + * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. + * @retval BLE_ERROR_INVALID_PARAM if number of UUIDs of any one type is too high. + */ + ble_error_t setUUIDData( + mbed::Span data, + adv_data_type_t shortType, + adv_data_type_t longType + ) { + ble_error_t status = BLE_ERROR_NONE; + + /* first count all the bytes we need to store all the UUIDs */ + size_t size_long = 0; + size_t size_short = 0; + + for (size_t i = 0; i < data.size(); ++i) { + if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { + size_short++; + } else { + size_long++; + } + } + + if ((size_long * 8 > 0xFF) || (size_short * 2 > 0xFF)) { + return BLE_ERROR_INVALID_PARAM; + } + + /* calculate total size including headers for types */ + size_t total_size = size_long + (!!size_long) * 2 + + size_short + (!!size_short) * 2; + + /* count all the bytes of existing data */ + size_t old_size = getFieldSize(shortType) + getFieldSize(longType); + + /* if we can't fit the new data do not proceed */ + if (total_size > data.size() - (_payload_length - old_size)) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* otherwise wipe old data */ + removeData(shortType); + removeData(longType); + + /* and insert individual UUIDs into appropriate fields */ + for (size_t i = 0; i < data.size(); ++i) { + adv_data_type_t field_type = (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) ? shortType : longType; + + mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); + + uint8_t *field = findField(field_type); + + if (field) { + status = appendToField(span, field); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } else { + status = addField(field_type, span); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } + } + + return status; + } + protected: /** The memory backing the the data provided by the user. */ mbed::Span _buffer; From 062c301a967c002705d9615f17bc7366210a34cb Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 14:01:26 +0000 Subject: [PATCH 230/361] check min size for custom data --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index dbd84f0fc4..9deffa990e 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -795,11 +795,17 @@ public: * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. - * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. + * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual + * data field or the data is too small (must contain + * 2 bytes of manufacturer ID) */ ble_error_t setManufacturerSpecificData( mbed::Span data ) { + if (data.size() < 2) { + return BLE_ERROR_INVALID_PARAM; + } + return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); } From 181ce00902f7ebfe9ed363ea7dee5c7ab7072ce1 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 14:13:40 +0000 Subject: [PATCH 231/361] fix size checks --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 9deffa990e..fc31528fa0 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -1032,7 +1032,7 @@ private: adv_data_type_t advDataType, mbed::Span fieldData ) { - if (fieldData.size() > 0xFF) { + if (fieldData.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -1070,7 +1070,7 @@ private: mbed::Span fieldData, uint8_t* field ) { - if (fieldData.size() + field[0] > 0xFF) { + if (fieldData.size() + field[0] > 0xFF /* field[0] already includes the type byte */) { return BLE_ERROR_INVALID_PARAM; } @@ -1123,7 +1123,7 @@ private: mbed::Span fieldData, uint8_t* field ) { - if (fieldData.size() > 0xFF) { + if (fieldData.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -1199,7 +1199,7 @@ private: } } - if ((size_long * 8 > 0xFF) || (size_short * 2 > 0xFF)) { + if ((size_long * 8 > 0xFE) || (size_short * 2 > 0xFE)) { return BLE_ERROR_INVALID_PARAM; } From 84dd169d1416e1fed74692c7ac37f4919f9144e3 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 14:13:59 +0000 Subject: [PATCH 232/361] allow long uuids in service data --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index fc31528fa0..6bdb196c85 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -858,7 +858,7 @@ public: * * @note Data size for individual types cannot exceed 255 bytes. * - * @param[in] service UUID of the service. Must be a 16bit UUID. + * @param[in] service UUID of the service. * @param[in] data New data to be added. * @param[in] complete True if this is a complete list. * @@ -870,11 +870,7 @@ public: UUID service, mbed::Span data ) { - if (data.size() > 0xFF) { - return BLE_ERROR_INVALID_PARAM; - } - - if (service.getLen() != 2) { + if (service.getLen() + data.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -892,7 +888,7 @@ public: ble_error_t status1 = addData( adv_data_type_t::SERVICE_DATA, - mbed::make_Span(service.getBaseUUID(), 2) + mbed::make_Span(service.getBaseUUID(), service.getLen()) ); ble_error_t status2 = appendData(adv_data_type_t::SERVICE_DATA, data); From 02d61cfe24535ee72ce61f400b6629fc127a550b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 19 Nov 2018 15:05:52 +0000 Subject: [PATCH 233/361] BLE: Move new version of ::GAP in a new class ::ble::Gap . --- features/FEATURE_BLE/ble/Gap.h | 708 ++---------------- features/FEATURE_BLE/ble/gap/Gap.h | 602 +++++++++++++++ features/FEATURE_BLE/ble/generic/GenericGap.h | 54 +- .../ble/generic/GenericGattClient.h | 14 +- .../ble/generic/GenericSecurityManager.h | 8 +- features/FEATURE_BLE/source/Gap.cpp | 266 +------ features/FEATURE_BLE/source/gap/Gap.cpp | 286 +++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 89 ++- .../source/generic/GenericGattClient.cpp | 30 +- .../source/generic/GenericSecurityManager.cpp | 10 +- .../targets/TARGET_CORDIO/CordioGattServer.h | 8 +- .../TARGET_CORDIO/source/CordioGattServer.cpp | 8 +- 12 files changed, 1071 insertions(+), 1012 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/Gap.h create mode 100644 features/FEATURE_BLE/source/gap/Gap.cpp diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 0f5f4e87ce..20af0404c0 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -19,15 +19,6 @@ #include "BLETypes.h" #include "BLEProtocol.h" - -// gap headers -#include "ble/gap/AdvertisingDataBuilder.h" -#include "ble/gap/ConnectionParameters.h" -#include "ble/gap/ScanParameters.h" -#include "ble/gap/AdvertisingParameters.h" -#include "ble/gap/Events.h" - -// leagacy gap headers #include "ble/GapAdvertisingData.h" #include "ble/GapAdvertisingParams.h" #include "ble/GapScanningParams.h" @@ -37,6 +28,7 @@ #include "FunctionPointerWithContext.h" #include "platform/mbed_toolchain.h" +#include "ble/gap/Gap.h" /** * @addtogroup ble @@ -268,622 +260,8 @@ * PHY and of any changes to PHYs which may be triggered autonomously by the * controller or by the peer. */ -class Gap { +class Gap : public ble::Gap { -public: - - /** - * Definition of the general handler of Gap related events. - */ - struct EventHandler { - /** Called when a scanning device request a scan response. - * - * @param event Scan request event: @see ScanRequestEvent_t for details. - */ - virtual void onScanRequest(const ble::ScanRequestEvent_t& event) { } - - /** Called when advertising ends. - * - * @param event Advertising end event: @see AdvertisingEndEvent_t for details. - */ - virtual void onAdvertisingEnd(const ble::AdvertisingEndEvent_t& event) - { } - - /** Called when scanning reads an advertising packet during passive scan or receives - * a scan response during an active scan. - * - * @param event Advertising report @see AdvertisingReportEvent_t for details. - */ - void onAdvertisingReport(const ble::AdvertisingReportEvent &event) { } - - /** Called when scan times out. - */ - virtual void onScanTimeout(const ble::ScanTimeoutEvent &) { } - - /** Called when first advertising packet in periodic advertising is received. - * - * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. - */ - virtual void onPeriodicAdvertisingSyncEstablished( - const ble::PeriodicAdvertisingSyncEstablishedEvent &event - ) { } - - /** Called when a periodic advertising packet is received. - * - * @param event Periodic advertisement event. - */ - virtual void onPeriodicAdvertisingReportEvent( - const ble::PeriodicAdvertisingReportEvent & event - ) { } - - virtual void onPeriodicAdvertisingSyncLoss( - const ble::PeriodicAdvertisingSyncLoss &event - ) { } - - /** Called when connection attempt ends. - * - * @param event Connection event @see ConnectionCompleteEvent_t for details. - */ - virtual void onConnectionComplete(const ble::ConnectionCompleteEvent &event) { } - - virtual void onUpdateConnectionParametersRequest( - const ble::UpdateConnectionParametersRequestEvent &event - ) { } - - virtual void onConnectionParametersUpdateComplete( - const ble::ConnectionParametersUpdateCompleteEvent &event - ) { } - - virtual void onDisconnection(const ble::DisconnectionEvent &event) { } - - /** - * Function invoked when the current transmitter and receiver PHY have - * been read for a given connection. - * - * @param status Status of the operation: BLE_ERROR_NONE in case of - * success or an appropriate error code. - * - * @param connectionHandle: The handle of the connection for which the - * PHYs have been read. - * - * @param txPhy PHY used by the transmitter. - * - * @param rxPhy PHY used by the receiver. - */ - virtual void onReadPhy( - ble_error_t status, - ble::connection_handle_t connectionHandle, - ble::phy_t txPhy, - ble::phy_t rxPhy - ) { } - - /** - * Function invoked when the update process of the PHY has been completed. - * - * The process can be initiated by a call to the function setPhy, the - * local bluetooth subsystem or the peer. - * - * @param status Status of the operation: BLE_ERROR_NONE in case of - * success or an appropriate error code. - * - * @param connectionHandle: The handle of the connection on which the - * operation was made. - * - * @param txPhy PHY used by the transmitter. - * - * @param rxPhy PHY used by the receiver. - * - * @note Success doesn't mean the PHY has been updated it means both - * ends have negotiated the best PHY according to their configuration and - * capabilities. The PHY currently used are present in the txPhy and - * rxPhy parameters. - */ - virtual void onPhyUpdateComplete( - ble_error_t status, - ble::connection_handle_t connectionHandle, - ble::phy_t txPhy, - ble::phy_t rxPhy - ) { } - - protected: - /** - * Prevent polymorphic deletion and avoid unnecessary virtual destructor - * as the Gap class will never delete the instance it contains. - */ - ~EventHandler() { } - }; - - /** - * Representation of a whitelist of addresses. - */ - struct Whitelist_t { - /** - * Pointer to the array of the addresses composing the whitelist. - */ - BLEProtocol::Address_t *addresses; - - /** - * Number addresses in this whitelist. - */ - uint8_t size; - - /** - * Capacity of the array holding the addresses. - */ - uint8_t capacity; - }; - - - /** Check controller support for a specific feature. - * - * @param feature Feature to check. - * @return True if feature is supported. - */ - virtual bool isFeatureSupported(ble::controller_supported_features_t feature) - { - // TODO: deal with legacy implementation - } - - /* advertising */ - - /** Return currently available number of supported advertising sets. - * This may change at runtime. - * - * @return Number of advertising sets that may be created at the same time. - */ - virtual uint8_t getMaxAdvertisingSetNumber(); - - /** Return maximum advertising data length supported. - * - * @return Maximum advertising data length supported. - */ - virtual uint8_t getMaxAdvertisingDataLength(); - - /** Create an advertising set and apply the passed in parameters. The handle returned - * by this function must be used for all other calls that accept an advertising handle. - * When done with advertising, remove from the system using destroyAdvertisingSet(). - * - * @note The exception is the ble::LEGACY_ADVERTISING_HANDLE which may be used at any time. - * - * @param[out] handle Advertising handle returned, valid only if function returned success. - * @param parameters Advertising parameters for the newly created set. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createAdvertisingSet( - ble::advertising_handle_t *handle, - const ble::AdvertisingParameters ¶meters - ); - - /** Remove the advertising set (resets its set parameters). The advertising set must not - * be active. - * - * @note ble::LEGACY_ADVERTISING_HANDLE may not be destroyed. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t destroyAdvertisingSet(ble::advertising_handle_t handle); - - /** Set advertising parameters of an existing set. - * - * @param handle Advertising set handle. - * @param params New advertising parameters. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingParameters( - ble::advertising_handle_t handle, - const ble::AdvertisingParameters ¶ms - ); - - /** Set new advertising payload for a given advertising set. - * - * @param handle Advertising set handle. - * @param payload Advertising payload. - * @param minimiseFragmentation Preference for fragmentation. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation = false - ); - - /** Set new advertising scan response for a given advertising set. This will be sent to - * device who perform active scanning. - * - * @param handle Advertising set handle. - * @param response Advertising scan response. - * @param minimiseFragmentation Preference for fragmentation. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setAdvertisingScanResponse( - ble::advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation = false - ); - - /** Start advertising using the given advertising set. - * - * @param handle Advertising set handle. - * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. - * @param maxEvents Max number of events produced during advertising - 0 means no limit. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startAdvertising( - ble::advertising_handle_t handle, - ble::adv_duration_t maxDuration = ble::adv_duration_t(0), - uint8_t maxEvents = 0 - ); - - /** Stop advertising given advertising set. This is separate from periodic advertising - * which will not be affected. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t stopAdvertising(ble::advertising_handle_t handle); - - /** Check if advertising is active for a given advertising set. - * - * @param handle Advertising set handle. - * @return True if advertising is active on this set. - */ - virtual bool isAdvertisingActive(ble::advertising_handle_t handle); - - /** Set periodic advertising parameters for a given advertising set. - * - * @param handle Advertising set handle. - * @param periodicAdvertisingIntervalMin Minimum interval for periodic advertising. - * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. - * @param advertiseTxPower Include transmission power in the advertisements. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setPeriodicAdvertisingParameters( - ble::advertising_handle_t handle, - ble::periodic_interval_t periodicAdvertisingIntervalMin, - ble::periodic_interval_t periodicAdvertisingIntervalMax, - bool advertiseTxPower = true - ); - - /** Set new periodic advertising payload for a given advertising set. - * - * @param handle Advertising set handle. - * @param payload Advertising payload. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setPeriodicAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload - ); - - /** Start periodic advertising for a given set. Periodic advertising will not start until - * normal advertising is running but will continue to run after normal advertising has stopped. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startPeriodicAdvertising(ble::advertising_handle_t handle); - - /** Stop periodic advertising for a given set. - * - * @param handle Advertising set handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t stopPeriodicAdvertising(ble::advertising_handle_t handle); - - /** Check if periodic advertising is active for a given advertising set. - * - * @param handle Advertising set handle. - * @return True if periodic advertising is active on this set. - */ - virtual bool isPeriodicAdvertisingActive(ble::advertising_handle_t handle); - - /* scanning */ - - /** Set new scan parameters. - * - * @param params Scan parameters, @see GapScanParameters for details. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t setScanParameters(const ble::ScanParameters& params); - - /** Start scanning. - * - * @param filtering Filtering policy. - * @param duration How long to scan for. Special value 0 means scan forever. - * @param period How long to scan for in single period. If the period is 0 and duration - * is nonzero the scan will last for single duration. - * - * @note When the duration and period parameters are non-zero scanning will last for - * the duration within the period. After the scan period has expired a new scan period - * will begin and scanning. This will repeat until stopScan() is called. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t startScan( - ble::duplicates_filter_t filtering = ble::duplicates_filter_t::DISABLE, - ble::scan_duration_t duration = ble::scan_duration_t(0), - ble::scan_period_t period = ble::scan_period_t(0) - ); - - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic - * advertising packets. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver - * may skip after successfully receiving a periodic advertising packet. - * @param timeout Maximum permitted time between successful receptions. If this time is - * exceeded, synchronisation is lost. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createSync( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - uint8_t sid, - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout - ); - - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic - * advertising packets. Use periodic advertising sync list to determine who to sync with. - * - * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver - * may skip after successfully receiving a periodic advertising packet. - * @param timeout Maximum permitted time between successful receives. - * If this time is exceeded, synchronisation is lost. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t createSync( - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout - ); - - /** Cancel sync attempt. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t cancelCreateSync(); - - /** Stop reception of the periodic advertising identified by the handle. - * - * @param handle Periodic advertising synchronisation handle. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t terminateSync(ble::periodic_sync_handle_t handle); - - /** Add device to the periodic advertiser list. Cannot be called when sync is ongoing. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t addDeviceToPeriodicAdvertiserList( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - ble::advertising_sid_t sid - ); - - /** Remove device from the periodic advertiser list. Cannot be called when sync is ongoing. - * - * @param peerAddressType Peer address type. - * @param peerAddress Peer address. - * @param sid Advertiser set identifier. - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - ble::advertising_sid_t sid - ); - - /** Remove all devices from periodic advertiser list. - * - * @return BLE_ERROR_NONE on success. - */ - virtual ble_error_t clearPeriodicAdvertiserList(); - - /** Get number of devices that can be added to the periodic advertiser list. - * @return Number of devices that can be added to the periodic advertiser list. - */ - virtual uint8_t getMaxPeriodicAdvertiserListSize(); - - /** - * Initiate a connection to a peer. - * - * Once the connection is established an onConnectionComplete in the event handler - * will be called. - * - * @param peerAddressType - * @param peerAddress - * @param connectionParams - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallChain (if set) is invoked upon - * a connection event. - */ - virtual ble_error_t connect( - ble::target_peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - const ble::ConnectionParameters &connectionParams - ); - - /** Cancel the connection attempt. This is not guaranteed to succeed. As a result - * onConnectionComplete in the event handler will be called. Check the success parameter - * to see if the connection was created. - * - * @return BLE_ERROR_NONE if the connection attempt has been requested to be cancelled. - */ - virtual ble_error_t cancelConnect(); - - virtual ble_error_t updateConnectionParameters( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervision_timeout, - ble::conn_event_length_t minConnectionEventLength = ble::conn_event_length_t(0), - ble::conn_event_length_t maxConnectionEventLength = ble::conn_event_length_t(0) - ); - - virtual ble_error_t manageConnectionParametersUpdateRequest( - bool userManageConnectionUpdateRequest - ); - - virtual ble_error_t acceptConnectionParametersUpdate( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervision_timeout, - ble::conn_event_length_t minConnectionEventLength = ble::conn_event_length_t(0), - ble::conn_event_length_t maxConnectionEventLength = ble::conn_event_length_t(0) - ); - - virtual ble_error_t rejectConnectionParametersUpdate( - ble::connection_handle_t connectionHandle - ); - - /** - * Initiate a disconnection procedure. - * - * Once the disconnection procedure has completed a - * DisconnectionCallbackParams_t, the event is emitted to handlers that - * have been registered with onDisconnection(). - * - * @param[in] reason Reason of the disconnection transmitted to the peer. - * @param[in] connectionHandle Handle of the connection to end. - * - * @return BLE_ERROR_NONE if the disconnection procedure successfully - * started. - */ - virtual ble_error_t disconnect( - ble::connection_handle_t connectionHandle, - ble::local_disconnection_reason_t reason - ); - - /** - * Read the PHY used by the transmitter and the receiver on a connection. - * - * Once the PHY has been read, it is reported back via the function onPhyRead - * of the event handler registered by the application. - * - * @param connection Handle of the connection for which the PHY being used is - * queried. - * - * @return BLE_ERROR_NONE if the read PHY procedure has been started or an - * appropriate error code. - */ - virtual ble_error_t readPhy(ble::connection_handle_t connection); - - /** - * Set the preferred PHYs to use in a connection. - * - * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no - * preferred PHYs are set and the default value of the subsystem is used. - * - * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no - * preferred PHYs are set and the default value of the subsystem is used. - * - * @return BLE_ERROR_NONE if the preferences have been set or an appropriate - * error code. - */ - virtual ble_error_t setPreferredPhys( - const ble::phy_set_t *txPhys, - const ble::phy_set_t *rxPhys - ); - - /** - * Update the PHY used by a connection. - * - * Once the update process has been completed, it is reported back to the - * application via the function onPhyUpdateComplete of the event handler - * registered by the application. - * - * @param connection Handle of the connection to update. - * - * @param txPhys Set of PHYs preferred for tx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the - * choice is up to the Bluetooth subsystem. - * - * @param codedSymbol Number of symbols used to code a bit when le coded is - * used. If the value is UNDEFINED then the choice is up to the Bluetooth - * subsystem. - * - * @return BLE_ERROR_NONE if the update PHY procedure has been successfully - * started or an error code. - */ - virtual ble_error_t setPhy( - ble::connection_handle_t connection, - const ble::phy_set_t *txPhys, - const ble::phy_set_t *rxPhys, - ble::coded_symbol_per_bit_t codedSymbol - ); - - /** - * Get the maximum size of the whitelist. - * - * @return Maximum size of the whitelist. - * - * @note If using Mbed OS, you can configure the size of the whitelist by - * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. - */ - virtual uint8_t getMaxWhitelistSize(void) const; - - /** - * Get the Link Layer to use the internal whitelist when scanning, - * advertising or initiating a connection depending on the filter policies. - * - * @param[in,out] whitelist Define the whitelist instance which is used - * to store the whitelist requested. In input, the caller provisions memory. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * copied into the supplied reference. - */ - virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const; - - /** - * Set the value of the whitelist to be used during GAP procedures. - * - * @param[in] whitelist A reference to a whitelist containing the addresses - * to be copied to the internal whitelist. - * - * @return BLE_ERROR_NONE if the implementation's whitelist was successfully - * populated with the addresses in the given whitelist. - * - * @note The whitelist must not contain addresses of type @ref - * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This - * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might - * change its private address at any time, and it is not possible to resolve - * it. - * - * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), - * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. - */ - virtual ble_error_t setWhitelist(const Whitelist_t &whitelist); - -protected: - /* Override the following in the underlying adaptation layer to provide the - * functionality of scanning. */ - - /** Can only be called if use_non_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionOneAPI() const { } - - /** Can only be called if use_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionTwoAPI() const { } - - /* - * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated. - * They have been relocated to the class BLEProtocol. - */ public: /** * Address-type for BLEProtocol addresses. @@ -1071,6 +449,26 @@ public: INIT_POLICY_FILTER_ALL_ADV = 1, }; + /** + * Representation of a whitelist of addresses. + */ + struct Whitelist_t { + /** + * Pointer to the array of the addresses composing the whitelist. + */ + BLEProtocol::Address_t *addresses; + + /** + * Number addresses in this whitelist. + */ + uint8_t size; + + /** + * Capacity of the array holding the addresses. + */ + uint8_t capacity; + }; + /** * Description of the states of the device. */ @@ -2174,6 +1572,48 @@ public: *countP = 0; } + /** + * Get the maximum size of the whitelist. + * + * @return Maximum size of the whitelist. + * + * @note If using Mbed OS, you can configure the size of the whitelist by + * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file. + */ + virtual uint8_t getMaxWhitelistSize(void) const; + + /** + * Get the Link Layer to use the internal whitelist when scanning, + * advertising or initiating a connection depending on the filter policies. + * + * @param[in,out] whitelist Define the whitelist instance which is used + * to store the whitelist requested. In input, the caller provisions memory. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * copied into the supplied reference. + */ + virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const; + + /** + * Set the value of the whitelist to be used during GAP procedures. + * + * @param[in] whitelist A reference to a whitelist containing the addresses + * to be copied to the internal whitelist. + * + * @return BLE_ERROR_NONE if the implementation's whitelist was successfully + * populated with the addresses in the given whitelist. + * + * @note The whitelist must not contain addresses of type @ref + * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This + * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might + * change its private address at any time, and it is not possible to resolve + * it. + * + * @note If the input whitelist is larger than @ref getMaxWhitelistSize(), + * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned. + */ + virtual ble_error_t setWhitelist(const Whitelist_t &whitelist); + /** * Set the advertising policy filter mode to be used during the next * advertising procedure. @@ -3192,16 +2632,6 @@ public: /* Event handlers. */ public: - /** - * Assign the event handler implementation that will be used by the gap - * module to signal events back to the application. - * - * @param handler Application implementation of an Eventhandler. - */ - void setEventHandler(EventHandler* handler) { - _eventHandler = handler; - } - /** * Register a callback handling timeout events. * @@ -3451,8 +2881,7 @@ protected: radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), - disconnectionCallChain(), - _eventHandler(NULL) { + disconnectionCallChain() { _advPayload.clear(); _scanResponse.clear(); } @@ -3608,7 +3037,7 @@ public: uint8_t advertisingDataLen, const uint8_t *advertisingData, BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC - ); + ); /** * Notify the occurrence of a timeout event to all registered timeout events @@ -3696,11 +3125,6 @@ protected: */ DisconnectionEventCallbackChain_t disconnectionCallChain; - /** - * Event handler provided by the application. - */ - EventHandler* _eventHandler; - private: /** * Callchain containing all registered callback handlers for shutdown diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h new file mode 100644 index 0000000000..512e9b30fe --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -0,0 +1,602 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018-2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#ifndef BLE_GAP_GAP_H +#define BLE_GAP_GAP_H + + +#include "ble/BLETypes.h" +#include "ble/BLEProtocol.h" +#include "ble/gap/AdvertisingDataBuilder.h" +#include "ble/gap/ConnectionParameters.h" +#include "ble/gap/ScanParameters.h" +#include "ble/gap/AdvertisingParameters.h" +#include "ble/gap/Events.h" + +namespace ble { + +class Gap { +public: + + /** + * Definition of the general handler of Gap related events. + */ + struct EventHandler { + /** Called when a scanning device request a scan response. + * + * @param event Scan request event: @see ScanRequestEvent_t for details. + */ + virtual void onScanRequest(const ScanRequestEvent_t &event) { } + + /** Called when advertising ends. + * + * @param event Advertising end event: @see AdvertisingEndEvent_t for details. + */ + virtual void onAdvertisingEnd(const AdvertisingEndEvent_t &event) { } + + /** Called when scanning reads an advertising packet during passive scan or receives + * a scan response during an active scan. + * + * @param event Advertising report @see AdvertisingReportEvent_t for details. + */ + void onAdvertisingReport(const AdvertisingReportEvent &event) { } + + /** Called when scan times out. + */ + virtual void onScanTimeout(const ScanTimeoutEvent &) { } + + /** Called when first advertising packet in periodic advertising is received. + * + * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. + */ + virtual void onPeriodicAdvertisingSyncEstablished( + const PeriodicAdvertisingSyncEstablishedEvent &event + ) { } + + /** Called when a periodic advertising packet is received. + * + * @param event Periodic advertisement event. + */ + virtual void onPeriodicAdvertisingReportEvent( + const PeriodicAdvertisingReportEvent &event + ) { } + + virtual void onPeriodicAdvertisingSyncLoss( + const PeriodicAdvertisingSyncLoss &event + ) { } + + /** Called when connection attempt ends. + * + * @param event Connection event @see ConnectionCompleteEvent_t for details. + */ + virtual void onConnectionComplete(const ConnectionCompleteEvent &event) { } + + virtual void onUpdateConnectionParametersRequest( + const UpdateConnectionParametersRequestEvent &event + ) { } + + virtual void onConnectionParametersUpdateComplete( + const ConnectionParametersUpdateCompleteEvent &event + ) { } + + virtual void onDisconnection(const DisconnectionEvent &event) { } + + /** + * Function invoked when the current transmitter and receiver PHY have + * been read for a given connection. + * + * @param status Status of the operation: BLE_ERROR_NONE in case of + * success or an appropriate error code. + * + * @param connectionHandle: The handle of the connection for which the + * PHYs have been read. + * + * @param txPhy PHY used by the transmitter. + * + * @param rxPhy PHY used by the receiver. + */ + virtual void onReadPhy( + ble_error_t status, + connection_handle_t connectionHandle, + phy_t txPhy, + phy_t rxPhy + ) { } + + /** + * Function invoked when the update process of the PHY has been completed. + * + * The process can be initiated by a call to the function setPhy, the + * local bluetooth subsystem or the peer. + * + * @param status Status of the operation: BLE_ERROR_NONE in case of + * success or an appropriate error code. + * + * @param connectionHandle: The handle of the connection on which the + * operation was made. + * + * @param txPhy PHY used by the transmitter. + * + * @param rxPhy PHY used by the receiver. + * + * @note Success doesn't mean the PHY has been updated it means both + * ends have negotiated the best PHY according to their configuration and + * capabilities. The PHY currently used are present in the txPhy and + * rxPhy parameters. + */ + virtual void onPhyUpdateComplete( + ble_error_t status, + connection_handle_t connectionHandle, + phy_t txPhy, + phy_t rxPhy + ) { } + + protected: + /** + * Prevent polymorphic deletion and avoid unnecessary virtual destructor + * as the Gap class will never delete the instance it contains. + */ + ~EventHandler() { } + }; + + /** + * Assign the event handler implementation that will be used by the gap + * module to signal events back to the application. + * + * @param handler Application implementation of an Eventhandler. + */ + void setEventHandler(EventHandler *handler) + { + _eventHandler = handler; + } + + /** Check controller support for a specific feature. + * + * @param feature Feature to check. + * @return True if feature is supported. + */ + virtual bool isFeatureSupported(controller_supported_features_t feature) + { + // TODO: deal with legacy implementation + } + + /* advertising */ + + /** Return currently available number of supported advertising sets. + * This may change at runtime. + * + * @return Number of advertising sets that may be created at the same time. + */ + virtual uint8_t getMaxAdvertisingSetNumber(); + + /** Return maximum advertising data length supported. + * + * @return Maximum advertising data length supported. + */ + virtual uint8_t getMaxAdvertisingDataLength(); + + /** Create an advertising set and apply the passed in parameters. The handle returned + * by this function must be used for all other calls that accept an advertising handle. + * When done with advertising, remove from the system using destroyAdvertisingSet(). + * + * @note The exception is the LEGACY_ADVERTISING_HANDLE which may be used at any time. + * + * @param[out] handle Advertising handle returned, valid only if function returned success. + * @param parameters Advertising parameters for the newly created set. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createAdvertisingSet( + advertising_handle_t *handle, + const AdvertisingParameters ¶meters + ); + + /** Remove the advertising set (resets its set parameters). The advertising set must not + * be active. + * + * @note LEGACY_ADVERTISING_HANDLE may not be destroyed. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t destroyAdvertisingSet(advertising_handle_t handle); + + /** Set advertising parameters of an existing set. + * + * @param handle Advertising set handle. + * @param params New advertising parameters. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingParameters( + advertising_handle_t handle, + const AdvertisingParameters ¶ms + ); + + /** Set new advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload, + bool minimiseFragmentation = false + ); + + /** Set new advertising scan response for a given advertising set. This will be sent to + * device who perform active scanning. + * + * @param handle Advertising set handle. + * @param response Advertising scan response. + * @param minimiseFragmentation Preference for fragmentation. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setAdvertisingScanResponse( + advertising_handle_t handle, + mbed::Span response, + bool minimiseFragmentation = false + ); + + /** Start advertising using the given advertising set. + * + * @param handle Advertising set handle. + * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. + * @param maxEvents Max number of events produced during advertising - 0 means no limit. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startAdvertising( + advertising_handle_t handle, + adv_duration_t maxDuration = adv_duration_t(0), + uint8_t maxEvents = 0 + ); + + /** Stop advertising given advertising set. This is separate from periodic advertising + * which will not be affected. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t stopAdvertising(advertising_handle_t handle); + + /** Check if advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if advertising is active on this set. + */ + virtual bool isAdvertisingActive(advertising_handle_t handle); + + /** Set periodic advertising parameters for a given advertising set. + * + * @param handle Advertising set handle. + * @param periodicAdvertisingIntervalMin Minimum interval for periodic advertising. + * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. + * @param advertiseTxPower Include transmission power in the advertisements. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setPeriodicAdvertisingParameters( + advertising_handle_t handle, + periodic_interval_t periodicAdvertisingIntervalMin, + periodic_interval_t periodicAdvertisingIntervalMax, + bool advertiseTxPower = true + ); + + /** Set new periodic advertising payload for a given advertising set. + * + * @param handle Advertising set handle. + * @param payload Advertising payload. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setPeriodicAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload + ); + + /** Start periodic advertising for a given set. Periodic advertising will not start until + * normal advertising is running but will continue to run after normal advertising has stopped. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startPeriodicAdvertising(advertising_handle_t handle); + + /** Stop periodic advertising for a given set. + * + * @param handle Advertising set handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t stopPeriodicAdvertising(advertising_handle_t handle); + + /** Check if periodic advertising is active for a given advertising set. + * + * @param handle Advertising set handle. + * @return True if periodic advertising is active on this set. + */ + virtual bool isPeriodicAdvertisingActive(advertising_handle_t handle); + + /* scanning */ + + /** Set new scan parameters. + * + * @param params Scan parameters, @see GapScanParameters for details. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t setScanParameters(const ScanParameters ¶ms); + + /** Start scanning. + * + * @param filtering Filtering policy. + * @param duration How long to scan for. Special value 0 means scan forever. + * @param period How long to scan for in single period. If the period is 0 and duration + * is nonzero the scan will last for single duration. + * + * @note When the duration and period parameters are non-zero scanning will last for + * the duration within the period. After the scan period has expired a new scan period + * will begin and scanning. This will repeat until stopScan() is called. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t startScan( + duplicates_filter_t filtering = duplicates_filter_t::DISABLE, + scan_duration_t duration = scan_duration_t(0), + scan_period_t period = scan_period_t(0) + ); + + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receptions. If this time is + * exceeded, synchronisation is lost. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createSync( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + uint8_t sid, + slave_latency_t maxPacketSkip, + sync_timeout_t timeout + ); + + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + * advertising packets. Use periodic advertising sync list to determine who to sync with. + * + * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver + * may skip after successfully receiving a periodic advertising packet. + * @param timeout Maximum permitted time between successful receives. + * If this time is exceeded, synchronisation is lost. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t createSync( + slave_latency_t maxPacketSkip, + sync_timeout_t timeout + ); + + /** Cancel sync attempt. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t cancelCreateSync(); + + /** Stop reception of the periodic advertising identified by the handle. + * + * @param handle Periodic advertising synchronisation handle. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t terminateSync(periodic_sync_handle_t handle); + + /** Add device to the periodic advertiser list. Cannot be called when sync is ongoing. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t addDeviceToPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid + ); + + /** Remove device from the periodic advertiser list. Cannot be called when sync is ongoing. + * + * @param peerAddressType Peer address type. + * @param peerAddress Peer address. + * @param sid Advertiser set identifier. + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid + ); + + /** Remove all devices from periodic advertiser list. + * + * @return BLE_ERROR_NONE on success. + */ + virtual ble_error_t clearPeriodicAdvertiserList(); + + /** Get number of devices that can be added to the periodic advertiser list. + * @return Number of devices that can be added to the periodic advertiser list. + */ + virtual uint8_t getMaxPeriodicAdvertiserListSize(); + + /** + * Initiate a connection to a peer. + * + * Once the connection is established an onConnectionComplete in the event handler + * will be called. + * + * @param peerAddressType + * @param peerAddress + * @param connectionParams + * + * @return BLE_ERROR_NONE if connection establishment procedure is started + * successfully. The connectionCallChain (if set) is invoked upon + * a connection event. + */ + virtual ble_error_t connect( + target_peer_address_type_t peerAddressType, + const address_t &peerAddress, + const ConnectionParameters &connectionParams + ); + + /** Cancel the connection attempt. This is not guaranteed to succeed. As a result + * onConnectionComplete in the event handler will be called. Check the success parameter + * to see if the connection was created. + * + * @return BLE_ERROR_NONE if the connection attempt has been requested to be cancelled. + */ + virtual ble_error_t cancelConnect(); + + virtual ble_error_t updateConnectionParameters( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength = conn_event_length_t(0), + conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) + ); + + virtual ble_error_t manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest + ); + + virtual ble_error_t acceptConnectionParametersUpdate( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength = conn_event_length_t(0), + conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) + ); + + virtual ble_error_t rejectConnectionParametersUpdate( + connection_handle_t connectionHandle + ); + + /** + * Initiate a disconnection procedure. + * + * Once the disconnection procedure has completed a + * DisconnectionCallbackParams_t, the event is emitted to handlers that + * have been registered with onDisconnection(). + * + * @param[in] reason Reason of the disconnection transmitted to the peer. + * @param[in] connectionHandle Handle of the connection to end. + * + * @return BLE_ERROR_NONE if the disconnection procedure successfully + * started. + */ + virtual ble_error_t disconnect( + connection_handle_t connectionHandle, + local_disconnection_reason_t reason + ); + + /** + * Read the PHY used by the transmitter and the receiver on a connection. + * + * Once the PHY has been read, it is reported back via the function onPhyRead + * of the event handler registered by the application. + * + * @param connection Handle of the connection for which the PHY being used is + * queried. + * + * @return BLE_ERROR_NONE if the read PHY procedure has been started or an + * appropriate error code. + */ + virtual ble_error_t readPhy(connection_handle_t connection); + + /** + * Set the preferred PHYs to use in a connection. + * + * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no + * preferred PHYs are set and the default value of the subsystem is used. + * + * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no + * preferred PHYs are set and the default value of the subsystem is used. + * + * @return BLE_ERROR_NONE if the preferences have been set or an appropriate + * error code. + */ + virtual ble_error_t setPreferredPhys( + const phy_set_t *txPhys, + const phy_set_t *rxPhys + ); + + /** + * Update the PHY used by a connection. + * + * Once the update process has been completed, it is reported back to the + * application via the function onPhyUpdateComplete of the event handler + * registered by the application. + * + * @param connection Handle of the connection to update. + * + * @param txPhys Set of PHYs preferred for tx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the + * choice is up to the Bluetooth subsystem. + * + * @param codedSymbol Number of symbols used to code a bit when le coded is + * used. If the value is UNDEFINED then the choice is up to the Bluetooth + * subsystem. + * + * @return BLE_ERROR_NONE if the update PHY procedure has been successfully + * started or an error code. + */ + virtual ble_error_t setPhy( + connection_handle_t connection, + const phy_set_t *txPhys, + const phy_set_t *rxPhys, + coded_symbol_per_bit_t codedSymbol + ); + +protected: + /* Override the following in the underlying adaptation layer to provide the + * functionality of scanning. */ + + /** Can only be called if use_non_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionOneAPI() const { } + + /** Can only be called if use_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionTwoAPI() const { } + + /** + * Construct a Gap instance. + */ + Gap() : _eventHandler(NULL) { } + + /** + * Event handler provided by the application. + */ + EventHandler *_eventHandler; +}; + +} // namespace ble + +#endif //BLE_GAP_GAP_H diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index bcee4c6857..0b70b4484f 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -79,7 +79,7 @@ public: /** @copydoc Gap::IsFeatureSupported */ bool isFeatureSupported( - ble::controller_supported_features_t feature + controller_supported_features_t feature ); /** @copydoc Gap::getMaxAdvertisingSetNumber @@ -184,7 +184,7 @@ public: */ virtual ble_error_t createSync( peer_address_type_t peerAddressType, - const address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout @@ -209,7 +209,7 @@ public: */ virtual ble_error_t addDeviceToPeriodicAdvertiserList( peer_address_type_t peerAddressType, - const address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid ); @@ -217,7 +217,7 @@ public: */ virtual ble_error_t removeDeviceFromPeriodicAdvertiserList( peer_address_type_t peerAddressType, - const address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid ); @@ -294,7 +294,7 @@ public: * @see Gap::connect */ virtual ble_error_t connect( - ble::target_peer_address_type_t peerAddressType, + target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ConnectionParameters &connectionParams ); @@ -309,27 +309,27 @@ public: ); virtual ble_error_t updateConnectionParameters( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervisionTimeout, - ble::conn_event_length_t minConnectionEventLength, - ble::conn_event_length_t maxConnectionEventLength + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervisionTimeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength ); virtual ble_error_t acceptConnectionParametersUpdate( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervisionTimeout, - ble::conn_event_length_t minConnectionEventLength, - ble::conn_event_length_t maxConnectionEventLength + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervisionTimeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength ); virtual ble_error_t rejectConnectionParametersUpdate( - ble::connection_handle_t connectionHandle + connection_handle_t connectionHandle ); /** @@ -355,6 +355,11 @@ public: CodedSymbolPerBit_t codedSymbol ); + virtual ble_error_t disconnect( + connection_handle_t connectionHandle, + local_disconnection_reason_t reason + ); + /** * @see Gap::disconnect */ @@ -611,15 +616,15 @@ private: virtual void on_read_phy( pal::hci_error_code_t hci_status, Handle_t connection_handle, - ble::phy_t tx_phy, - ble::phy_t rx_phy + phy_t tx_phy, + phy_t rx_phy ); virtual void on_phy_update_complete( pal::hci_error_code_t hci_status, Handle_t connection_handle, - ble::phy_t tx_phy, - ble::phy_t rx_phy + phy_t tx_phy, + phy_t rx_phy ); virtual void on_enhanced_connection_complete( @@ -702,7 +707,6 @@ private: uint16_t connection_latency, uint16_t supervision_timeout ); - private: pal::EventQueue& _event_queue; pal::Gap &_pal_gap; diff --git a/features/FEATURE_BLE/ble/generic/GenericGattClient.h b/features/FEATURE_BLE/ble/generic/GenericGattClient.h index 7dbb0e185d..b135535d93 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGattClient.h +++ b/features/FEATURE_BLE/ble/generic/GenericGattClient.h @@ -44,7 +44,7 @@ public: * @see GattClient::launchServiceDiscovery */ virtual ble_error_t launchServiceDiscovery( - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, ServiceDiscovery::ServiceCallback_t service_callback, ServiceDiscovery::CharacteristicCallback_t characteristic_callback, const UUID& matching_service_uuid, @@ -65,7 +65,7 @@ public: * @see GattClient::read */ virtual ble_error_t read( - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, GattAttribute::Handle_t attribute_handle, uint16_t offset ) const; @@ -75,7 +75,7 @@ public: */ virtual ble_error_t write( GattClient::WriteOp_t cmd, - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, GattAttribute::Handle_t attribute_handle, size_t length, const uint8_t* value @@ -128,18 +128,18 @@ private: struct WriteControlBlock; struct DescriptorDiscoveryControlBlock; - ProcedureControlBlock* get_control_block(Gap::Handle_t connection); - const ProcedureControlBlock* get_control_block(Gap::Handle_t connection) const; + ProcedureControlBlock* get_control_block(connection_handle_t connection); + const ProcedureControlBlock* get_control_block(connection_handle_t connection) const; void insert_control_block(ProcedureControlBlock* cb) const; void remove_control_block(ProcedureControlBlock* cb) const; - void on_termination(Gap::Handle_t connection_handle); + void on_termination(connection_handle_t connection_handle); void on_server_message_received(connection_handle_t, const pal::AttServerMessage&); void on_server_response(connection_handle_t, const pal::AttServerMessage&); void on_server_event(connection_handle_t, const pal::AttServerMessage&); void on_transaction_timeout(connection_handle_t); - uint16_t get_mtu(Gap::Handle_t connection) const; + uint16_t get_mtu(connection_handle_t connection) const; pal::GattClient* const _pal_client; ServiceDiscovery::TerminationCallback_t _termination_callback; diff --git a/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h b/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h index 928ba19d05..18ddda0673 100644 --- a/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h +++ b/features/FEATURE_BLE/ble/generic/GenericSecurityManager.h @@ -68,7 +68,7 @@ public: virtual ble_error_t purgeAllBondingState(); virtual ble_error_t generateWhitelistFromBondTable( - Gap::Whitelist_t *whitelist + ::Gap::Whitelist_t *whitelist ) const; //////////////////////////////////////////////////////////////////////////// @@ -398,12 +398,12 @@ private: */ virtual void on_connected( connection_handle_t connection, - Gap::Role_t role, + ::Gap::Role_t role, peer_address_type_t peer_address_type, const BLEProtocol::AddressBytes_t peer_address, BLEProtocol::AddressType_t local_address_type, const BLEProtocol::AddressBytes_t local_address, - const Gap::ConnectionParams_t *connection_params + const ::Gap::ConnectionParams_t *connection_params ); /** @@ -415,7 +415,7 @@ private: */ virtual void on_disconnected( connection_handle_t connection, - Gap::DisconnectionReason_t reason + ::Gap::DisconnectionReason_t reason ); /** diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index 98800da628..00f29238ee 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -70,271 +70,7 @@ Gap::PeerAddressType_t convert_legacy_address_type( } } -} - -uint8_t Gap::getMaxAdvertisingSetNumber() -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 1; -} - -uint8_t Gap::getMaxAdvertisingDataLength() -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0x1F; -} - -ble_error_t Gap::createAdvertisingSet( - ble::advertising_handle_t *handle, - const ble::AdvertisingParameters ¶meters -) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::destroyAdvertisingSet(ble::advertising_handle_t handle) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setAdvertisingParameters( - ble::advertising_handle_t handle, - const ble::AdvertisingParameters ¶ms -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setAdvertisingScanResponse( - ble::advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::startAdvertising( - ble::advertising_handle_t handle, - ble::adv_duration_t maxDuration, - uint8_t maxEvents -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::stopAdvertising(ble::advertising_handle_t handle) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -bool Gap::isAdvertisingActive(ble::advertising_handle_t handle) { - return false; -} - -ble_error_t Gap::setPeriodicAdvertisingParameters( - ble::advertising_handle_t handle, - ble::periodic_interval_t periodicAdvertisingIntervalMin, - ble::periodic_interval_t periodicAdvertisingIntervalMax, - bool advertiseTxPower -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setPeriodicAdvertisingPayload( - ble::advertising_handle_t handle, - mbed::Span payload -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::startPeriodicAdvertising(ble::advertising_handle_t handle) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::stopPeriodicAdvertising(ble::advertising_handle_t handle) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -bool Gap::isPeriodicAdvertisingActive(ble::advertising_handle_t handle) -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return false; -} - -ble_error_t Gap::setScanParameters(const ble::ScanParameters& params) -{ - useVersionTwoAPI(); - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -}; - -ble_error_t Gap::startScan( - ble::duplicates_filter_t filtering, - ble::scan_duration_t duration, - ble::scan_period_t period -) { - useVersionTwoAPI(); - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -}; - -ble_error_t Gap::createSync( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - uint8_t sid, - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::createSync( - ble::slave_latency_t maxPacketSkip, - ble::sync_timeout_t timeout -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::cancelCreateSync() -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::terminateSync(ble::periodic_sync_handle_t handle) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::addDeviceToPeriodicAdvertiserList( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - ble::advertising_sid_t sid -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::removeDeviceFromPeriodicAdvertiserList( - ble::peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - ble::advertising_sid_t sid -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::clearPeriodicAdvertiserList() -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -uint8_t Gap::getMaxPeriodicAdvertiserListSize() -{ - /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0; -} - -ble_error_t Gap::connect( - ble::target_peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, - const ble::ConnectionParameters &connectionParams -) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::cancelConnect() { - /* Requesting action from porter(s): override this API if this capability is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::updateConnectionParameters( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervision_timeout, - ble::conn_event_length_t minConnectionEventLength, - ble::conn_event_length_t maxConnectionEventLength -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::manageConnectionParametersUpdateRequest( - bool userManageConnectionUpdateRequest -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::acceptConnectionParametersUpdate( - ble::connection_handle_t connectionHandle, - ble::conn_interval_t minConnectionInterval, - ble::conn_interval_t maxConnectionInterval, - ble::slave_latency_t slaveLatency, - ble::supervision_timeout_t supervision_timeout, - ble::conn_event_length_t minConnectionEventLength, - ble::conn_event_length_t maxConnectionEventLength -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::rejectConnectionParametersUpdate( - ble::connection_handle_t connectionHandle -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::disconnect( - ble::connection_handle_t connectionHandle, - ble::local_disconnection_reason_t reason -) { - // Forward to the old implementation for now. - return disconnect(connectionHandle, (Gap::DisconnectionReason_t) reason.value()); -} - -ble_error_t Gap::readPhy(ble::connection_handle_t connection) -{ - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setPreferredPhys( - const ble::phy_set_t *txPhys, - const ble::phy_set_t *rxPhys -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} - -ble_error_t Gap::setPhy( - ble::connection_handle_t connection, - const ble::phy_set_t *txPhys, - const ble::phy_set_t *rxPhys, - ble::coded_symbol_per_bit_t codedSymbol -) { - return BLE_ERROR_NOT_IMPLEMENTED; -} +} // end of anonymous namespace uint8_t Gap::getMaxWhitelistSize(void) const { diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp new file mode 100644 index 0000000000..3907f88040 --- /dev/null +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -0,0 +1,286 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ble/gap/Gap.h" + +namespace ble { + +uint8_t Gap::getMaxAdvertisingSetNumber() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 1; +} + +uint8_t Gap::getMaxAdvertisingDataLength() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0x1F; +} + +ble_error_t Gap::createAdvertisingSet( + advertising_handle_t *handle, + const AdvertisingParameters ¶meters +) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::destroyAdvertisingSet(advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingParameters( + advertising_handle_t handle, + const AdvertisingParameters ¶ms +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload, + bool minimiseFragmentation +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setAdvertisingScanResponse( + advertising_handle_t handle, + mbed::Span response, + bool minimiseFragmentation +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::startAdvertising( + advertising_handle_t handle, + adv_duration_t maxDuration, + uint8_t maxEvents +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::stopAdvertising(advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +bool Gap::isAdvertisingActive(advertising_handle_t handle) { + return false; +} + +ble_error_t Gap::setPeriodicAdvertisingParameters( + advertising_handle_t handle, + periodic_interval_t periodicAdvertisingIntervalMin, + periodic_interval_t periodicAdvertisingIntervalMax, + bool advertiseTxPower +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPeriodicAdvertisingPayload( + advertising_handle_t handle, + mbed::Span payload +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::startPeriodicAdvertising(advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::stopPeriodicAdvertising(advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +bool Gap::isPeriodicAdvertisingActive(advertising_handle_t handle) +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return false; +} + +ble_error_t Gap::setScanParameters(const ScanParameters& params) +{ + useVersionTwoAPI(); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +}; + +ble_error_t Gap::startScan( + duplicates_filter_t filtering, + scan_duration_t duration, + scan_period_t period +) { + useVersionTwoAPI(); + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +}; + +ble_error_t Gap::createSync( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + uint8_t sid, + slave_latency_t maxPacketSkip, + sync_timeout_t timeout +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::createSync( + slave_latency_t maxPacketSkip, + sync_timeout_t timeout +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::cancelCreateSync() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::terminateSync(periodic_sync_handle_t handle) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::addDeviceToPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::removeDeviceFromPeriodicAdvertiserList( + peer_address_type_t peerAddressType, + const address_t &peerAddress, + advertising_sid_t sid +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::clearPeriodicAdvertiserList() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +uint8_t Gap::getMaxPeriodicAdvertiserListSize() +{ + /* Requesting action from porter(s): override this API if this capability is supported. */ + return 0; +} + +ble_error_t Gap::connect( + target_peer_address_type_t peerAddressType, + const address_t &peerAddress, + const ConnectionParameters &connectionParams +) { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::cancelConnect() { + /* Requesting action from porter(s): override this API if this capability is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::updateConnectionParameters( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::manageConnectionParametersUpdateRequest( + bool userManageConnectionUpdateRequest +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::acceptConnectionParametersUpdate( + connection_handle_t connectionHandle, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t supervision_timeout, + conn_event_length_t minConnectionEventLength, + conn_event_length_t maxConnectionEventLength +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::rejectConnectionParametersUpdate( + connection_handle_t connectionHandle +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::disconnect( + connection_handle_t connectionHandle, + local_disconnection_reason_t reason +) { + // Forward to the old implementation for now. + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::readPhy(connection_handle_t connection) +{ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPreferredPhys( + const phy_set_t *txPhys, + const phy_set_t *rxPhys +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPhy( + connection_handle_t connection, + const phy_set_t *txPhys, + const phy_set_t *rxPhys, + coded_symbol_per_bit_t codedSymbol +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +} // namespace ble + diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 970448d04d..0ce8e56e8c 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -50,7 +50,7 @@ static const uint16_t advertising_interval_max = 0x4000; static const uint16_t supervision_timeout_min = 0x000A; static const uint16_t supervision_timeout_max = 0x0C80; -static const Gap::ConnectionParams_t default_connection_params = { +static const ::Gap::ConnectionParams_t default_connection_params = { /* min conn interval */ 50, /* max conn interval */ 100, /* slave latency */ 0, @@ -96,7 +96,7 @@ static bool is_scan_params_valid(const GapScanningParams* params) /* * Return true if the connection parameters are valid or false otherwise. */ -static bool is_connection_params_valid(const Gap::ConnectionParams_t* params) +static bool is_connection_params_valid(const ::Gap::ConnectionParams_t* params) { if (params == NULL) { return false; @@ -139,7 +139,7 @@ static bool is_connection_params_valid(const Gap::ConnectionParams_t* params) * timeout to be equal to 0xFFFF. When it is the case that value can be * interpreted as "non specific". */ -static bool is_preferred_connection_params_valid(const Gap::ConnectionParams_t* params) +static bool is_preferred_connection_params_valid(const ::Gap::ConnectionParams_t* params) { if (params == NULL) { return false; @@ -286,7 +286,7 @@ static bool is_random_address(const BLEProtocol::AddressBytes_t address) /* * Check disconnection reason validity. */ -static bool is_disconnection_reason_valid(Gap::DisconnectionReason_t reason) +static bool is_disconnection_reason_valid(::Gap::DisconnectionReason_t reason) { switch (reason) { /** @@ -302,10 +302,10 @@ static bool is_disconnection_reason_valid(Gap::DisconnectionReason_t reason) */ // TODO Fix Disconnectionreason_t which expose invalid value - case Gap::REMOTE_USER_TERMINATED_CONNECTION: - case Gap::REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES: - case Gap::REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF: - case Gap::CONN_INTERVAL_UNACCEPTABLE: + case ::Gap::REMOTE_USER_TERMINATED_CONNECTION: + case ::Gap::REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES: + case ::Gap::REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF: + case ::Gap::CONN_INTERVAL_UNACCEPTABLE: return true; default: return false; @@ -315,7 +315,7 @@ static bool is_disconnection_reason_valid(Gap::DisconnectionReason_t reason) /* * Return true if the whitelist in input is valid or false otherwise. */ -static bool is_whitelist_valid(const Gap::Whitelist_t& whitelist) +static bool is_whitelist_valid(const ::Gap::Whitelist_t& whitelist) { if (whitelist.size > whitelist.capacity) { return false; @@ -342,7 +342,7 @@ static bool is_whitelist_valid(const Gap::Whitelist_t& whitelist) * Return true if device is present in the whitelist. */ static bool is_in_whitelist( - const BLEProtocol::Address_t& device, const Gap::Whitelist_t& whitelist + const BLEProtocol::Address_t& device, const ::Gap::Whitelist_t& whitelist ) { for (size_t i = 0; i < whitelist.size; ++i) { const BLEProtocol::Address_t& potential_device = whitelist.addresses[i]; @@ -446,7 +446,7 @@ GenericGap::~GenericGap() } bool GenericGap::isFeatureSupported( - ble::controller_supported_features_t feature + controller_supported_features_t feature ) { return _pal_gap.is_feature_supported(feature); } @@ -615,7 +615,7 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( - ble::target_peer_address_type_t peerAddressType, + target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ConnectionParameters &connectionParams ) { @@ -624,7 +624,7 @@ ble_error_t GenericGap::connect( } if (!is_extended_advertising_available()) { - ble::phy_set_t set(connectionParams.getPhySet()); + phy_set_t set(connectionParams.getPhySet()); if (set.count() != 1 || set.get_1m() == false) { return BLE_ERROR_INVALID_PARAM; } @@ -633,9 +633,9 @@ ble_error_t GenericGap::connect( return _pal_gap.extended_create_connection( connectionParams.getFilterPolicy(), connectionParams.getOwnAddressType(), - (ble::peer_address_type_t::type)peerAddressType.value(), + (peer_address_type_t::type)peerAddressType.value(), peerAddress, - (ble::phy_set_t)connectionParams.getPhySet(), + (phy_set_t)connectionParams.getPhySet(), connectionParams.getScanIntervalArray(), connectionParams.getScanWindowArray(), connectionParams.getMinConnectionIntervalArray(), @@ -700,7 +700,7 @@ ble_error_t GenericGap::acceptConnectionParametersUpdate( } ble_error_t GenericGap::rejectConnectionParametersUpdate( - ble::connection_handle_t connectionHandle + connection_handle_t connectionHandle ) { return _pal_gap.reject_connection_parameter_request( connectionHandle, @@ -741,8 +741,8 @@ ble_error_t GenericGap::setPhy( void GenericGap::on_read_phy( pal::hci_error_code_t hci_status, Handle_t connection_handle, - ble::phy_t tx_phy, - ble::phy_t rx_phy + phy_t tx_phy, + phy_t rx_phy ) { ble_error_t status = BLE_ERROR_NONE; if (pal::hci_error_code_t::SUCCESS != hci_status) { @@ -757,8 +757,8 @@ void GenericGap::on_read_phy( void GenericGap::on_phy_update_complete( pal::hci_error_code_t hci_status, Handle_t connection_handle, - ble::phy_t tx_phy, - ble::phy_t rx_phy + phy_t tx_phy, + phy_t rx_phy ) { ble_error_t status = BLE_ERROR_NONE; if (pal::hci_error_code_t::SUCCESS != hci_status) { @@ -770,6 +770,13 @@ void GenericGap::on_phy_update_complete( } } +ble_error_t GenericGap::disconnect( + connection_handle_t connectionHandle, + local_disconnection_reason_t reason +) { + return _pal_gap.disconnect(connectionHandle, reason); +} + ble_error_t GenericGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) { if (is_disconnection_reason_valid(reason) == false) { @@ -994,7 +1001,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) ble_error_t GenericGap::setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) { - if (mode > Gap::ADV_POLICY_FILTER_ALL_REQS) { + if (mode > ::Gap::ADV_POLICY_FILTER_ALL_REQS) { return BLE_ERROR_INVALID_PARAM; } @@ -1006,7 +1013,7 @@ ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) { useVersionOneAPI(); - if (mode > Gap::SCAN_POLICY_FILTER_ALL_ADV) { + if (mode > ::Gap::SCAN_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; } @@ -1016,7 +1023,7 @@ ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) ble_error_t GenericGap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) { - if (mode > Gap::INIT_POLICY_FILTER_ALL_ADV) { + if (mode > ::Gap::INIT_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; } @@ -1024,18 +1031,18 @@ ble_error_t GenericGap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) return BLE_ERROR_NONE; } -Gap::AdvertisingPolicyMode_t GenericGap::getAdvertisingPolicyMode(void) const +::Gap::AdvertisingPolicyMode_t GenericGap::getAdvertisingPolicyMode(void) const { return (AdvertisingPolicyMode_t) _advertising_filter_policy.value(); } -Gap::ScanningPolicyMode_t GenericGap::getScanningPolicyMode(void) const +::Gap::ScanningPolicyMode_t GenericGap::getScanningPolicyMode(void) const { useVersionOneAPI(); return (ScanningPolicyMode_t) _scanning_filter_policy.value(); } -Gap::InitiatorPolicyMode_t GenericGap::getInitiatorPolicyMode(void) const +::Gap::InitiatorPolicyMode_t GenericGap::getInitiatorPolicyMode(void) const { return (InitiatorPolicyMode_t) _initiator_policy_mode.value(); } @@ -1235,7 +1242,7 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams& params) ble_error_t GenericGap::reset(void) { - Gap::reset(); + ::Gap::reset(); _advertising_timeout.detach(); _scan_timeout.detach(); _pal_gap.clear_advertising_sets(); @@ -1294,7 +1301,7 @@ void GenericGap::processDisconnectionEvent( _eventHandler->onDisconnection( DisconnectionEvent( handle, - (ble::disconnection_reason_t::type) reason + (disconnection_reason_t::type) reason ) ); } @@ -1320,7 +1327,7 @@ void GenericGap::process_scan_timeout() if (err) { // TODO: define the mechanism signaling the error } - processTimeoutEvent(Gap::TIMEOUT_SRC_SCAN); + processTimeoutEvent(::Gap::TIMEOUT_SRC_SCAN); } void GenericGap::on_advertising_timeout() @@ -1338,7 +1345,7 @@ void GenericGap::process_advertising_timeout() // Stop address rotation if required set_random_address_rotation(false); - processTimeoutEvent(Gap::TIMEOUT_SRC_ADVERTISING); + processTimeoutEvent(::Gap::TIMEOUT_SRC_ADVERTISING); } void GenericGap::on_gap_event_received(const pal::GapEvent& e) @@ -1412,7 +1419,7 @@ void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent& e // event // TODO: Define events in case of connection faillure - processTimeoutEvent(Gap::TIMEOUT_SRC_CONN); + processTimeoutEvent(::Gap::TIMEOUT_SRC_CONN); return; } @@ -1507,7 +1514,7 @@ void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEv if (e.status == pal::hci_error_code_t::SUCCESS) { processDisconnectionEvent( e.connection_handle, - (Gap::DisconnectionReason_t) e.reason + (::Gap::DisconnectionReason_t) e.reason ); } else { // TODO: define what to do in case of faillure @@ -2275,9 +2282,9 @@ void GenericGap::on_enhanced_connection_complete( _eventHandler->onConnectionComplete( ConnectionCompleteEvent( (status == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, - (ble::connection_handle_t)connection_handle, + (connection_handle_t)connection_handle, own_role, - (ble::peer_address_type_t::type)peer_address_type.value(), + (peer_address_type_t::type)peer_address_type.value(), peer_address, local_resolvable_private_address, peer_resolvable_private_address, @@ -2321,7 +2328,7 @@ void GenericGap::on_extended_advertising_report( advertising_sid, tx_power, rssi, - ble::periodic_interval_t(periodic_advertising_interval), + periodic_interval_t(periodic_advertising_interval), (PeerAddressType_t::type)direct_address_type.value(), (BLEProtocol::AddressBytes_t&)direct_address, mbed::make_Span(data, data_length) @@ -2430,7 +2437,7 @@ void GenericGap::on_scan_request_received( _eventHandler->onScanRequest( ScanRequestEvent_t( advertising_handle, - (ble::peer_address_type_t::type) scanner_address_type.value(), + (peer_address_type_t::type) scanner_address_type.value(), address ) ); @@ -2586,8 +2593,8 @@ ble_error_t GenericGap::startScan( } ble_error_t GenericGap::createSync( - ble::peer_address_type_t peerAddressType, - const address_t &peerAddress, + peer_address_type_t peerAddressType, + const ble::address_t &peerAddress, advertising_sid_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout @@ -2655,7 +2662,7 @@ ble_error_t GenericGap::terminateSync(periodic_sync_handle_t handle) ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( peer_address_type_t peerAddressType, - const address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid ) { @@ -2682,7 +2689,7 @@ ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( peer_address_type_t peerAddressType, - const address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid ) { @@ -2744,7 +2751,7 @@ void GenericGap::useVersionTwoAPI() const bool GenericGap::is_extended_advertising_available() { return isFeatureSupported( - ble::controller_supported_features_t::LE_EXTENDED_ADVERTISING + controller_supported_features_t::LE_EXTENDED_ADVERTISING ); } diff --git a/features/FEATURE_BLE/source/generic/GenericGattClient.cpp b/features/FEATURE_BLE/source/generic/GenericGattClient.cpp index 193f9071d6..c89577d988 100644 --- a/features/FEATURE_BLE/source/generic/GenericGattClient.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGattClient.cpp @@ -66,7 +66,7 @@ struct GenericGattClient::ProcedureControlBlock { /* * Base constructor for procedure control block. */ - ProcedureControlBlock(procedure_type_t type, Gap::Handle_t handle) : + ProcedureControlBlock(procedure_type_t type, connection_handle_t handle) : type(type), connection_handle(handle), next(NULL) { } virtual ~ProcedureControlBlock() { } @@ -87,7 +87,7 @@ struct GenericGattClient::ProcedureControlBlock { virtual void abort(GenericGattClient *client) = 0; procedure_type_t type; - Gap::Handle_t connection_handle; + connection_handle_t connection_handle; ProcedureControlBlock* next; }; @@ -97,7 +97,7 @@ struct GenericGattClient::ProcedureControlBlock { */ struct GenericGattClient::DiscoveryControlBlock : public ProcedureControlBlock { DiscoveryControlBlock( - Gap::Handle_t handle, + connection_handle_t handle, ServiceDiscovery::ServiceCallback_t service_callback, ServiceDiscovery::CharacteristicCallback_t characteristic_callback, UUID matching_service_uuid, @@ -307,7 +307,7 @@ struct GenericGattClient::DiscoveryControlBlock : public ProcedureControlBlock { void terminate(GenericGattClient* client) { // unknown error, terminate the procedure immediately client->remove_control_block(this); - Gap::Handle_t handle = connection_handle; + connection_handle_t handle = connection_handle; delete this; client->on_termination(handle); } @@ -356,7 +356,7 @@ struct GenericGattClient::DiscoveryControlBlock : public ProcedureControlBlock { characteristic_t( GattClient* client, - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, uint16_t decl_handle, const ArrayView value ) : DiscoveredCharacteristic() { @@ -428,7 +428,7 @@ struct GenericGattClient::DiscoveryControlBlock : public ProcedureControlBlock { struct GenericGattClient::ReadControlBlock : public ProcedureControlBlock { ReadControlBlock( - Gap::Handle_t connection_handle, uint16_t attribute_handle, uint16_t offset + connection_handle_t connection_handle, uint16_t attribute_handle, uint16_t offset ) : ProcedureControlBlock(READ_PROCEDURE, connection_handle), attribute_handle(attribute_handle), offset(offset), current_offset(offset), data(NULL) { @@ -625,7 +625,7 @@ struct GenericGattClient::ReadControlBlock : public ProcedureControlBlock { */ struct GenericGattClient::WriteControlBlock : public ProcedureControlBlock { WriteControlBlock( - Gap::Handle_t connection_handle, uint16_t attribute_handle, + connection_handle_t connection_handle, uint16_t attribute_handle, uint8_t* data, uint16_t len ) : ProcedureControlBlock(WRITE_PROCEDURE, connection_handle), attribute_handle(attribute_handle), len(len), offset(0), data(data), @@ -949,7 +949,7 @@ GenericGattClient::GenericGattClient(pal::GattClient* pal_client) : } ble_error_t GenericGattClient::launchServiceDiscovery( - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, ServiceDiscovery::ServiceCallback_t service_callback, ServiceDiscovery::CharacteristicCallback_t characteristic_callback, const UUID& matching_service_uuid, @@ -1030,7 +1030,7 @@ void GenericGattClient::terminateServiceDiscovery() } ble_error_t GenericGattClient::read( - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, GattAttribute::Handle_t attribute_handle, uint16_t offset) const { @@ -1073,7 +1073,7 @@ ble_error_t GenericGattClient::read( ble_error_t GenericGattClient::write( GattClient::WriteOp_t cmd, - Gap::Handle_t connection_handle, + connection_handle_t connection_handle, GattAttribute::Handle_t attribute_handle, size_t length, const uint8_t* value @@ -1279,7 +1279,7 @@ void GenericGattClient::set_signing_event_handler( _signing_event_handler = signing_event_handler; } -void GenericGattClient::on_termination(Gap::Handle_t connection_handle) { +void GenericGattClient::on_termination(connection_handle_t connection_handle) { if (_termination_callback) { _termination_callback(connection_handle); } @@ -1330,7 +1330,7 @@ void GenericGattClient::on_server_response( void GenericGattClient::on_server_event(connection_handle_t connection, const AttServerMessage& message) { GattHVXCallbackParams callbacks_params = { - (Gap::Handle_t) connection, 0 + (connection_handle_t) connection, 0 }; switch (message.opcode) { @@ -1368,7 +1368,7 @@ void GenericGattClient::on_transaction_timeout(connection_handle_t connection) { pcb->handle_timeout_error(this); } -GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(Gap::Handle_t connection) { +GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(connection_handle_t connection) { ProcedureControlBlock* it = control_blocks; while (it && it->connection_handle != connection) { it = it->next; @@ -1376,7 +1376,7 @@ GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(G return it; } -const GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(Gap::Handle_t connection) const { +const GenericGattClient::ProcedureControlBlock* GenericGattClient::get_control_block(connection_handle_t connection) const { ProcedureControlBlock* it = control_blocks; while (it && it->connection_handle != connection) { it = it->next; @@ -1420,7 +1420,7 @@ void GenericGattClient::remove_control_block(ProcedureControlBlock* cb) const { cb->next = NULL; } -uint16_t GenericGattClient::get_mtu(Gap::Handle_t connection) const { +uint16_t GenericGattClient::get_mtu(connection_handle_t connection) const { uint16_t result = 23; if(_pal_client->get_mtu_size((connection_handle_t) connection, result) != BLE_ERROR_NONE) { result = 23; diff --git a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp index a444a573e6..fc6da98b71 100644 --- a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp +++ b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp @@ -139,7 +139,7 @@ ble_error_t GenericSecurityManager::purgeAllBondingState(void) { return BLE_ERROR_NONE; } -ble_error_t GenericSecurityManager::generateWhitelistFromBondTable(Gap::Whitelist_t *whitelist) const { +ble_error_t GenericSecurityManager::generateWhitelistFromBondTable(::Gap::Whitelist_t *whitelist) const { if (!_db) return BLE_ERROR_INITIALIZATION_INCOMPLETE; if (eventHandler) { if (!whitelist) { @@ -1033,12 +1033,12 @@ void GenericSecurityManager::set_mitm_performed(connection_handle_t connection, void GenericSecurityManager::on_connected( connection_handle_t connection, - Gap::Role_t role, + ::Gap::Role_t role, peer_address_type_t peer_address_type, const BLEProtocol::AddressBytes_t peer_address, BLEProtocol::AddressType_t local_address_type, const BLEProtocol::AddressBytes_t local_address, - const Gap::ConnectionParams_t *connection_params + const ::Gap::ConnectionParams_t *connection_params ) { MBED_ASSERT(_db); ControlBlock_t *cb = acquire_control_block(connection); @@ -1048,7 +1048,7 @@ void GenericSecurityManager::on_connected( // setup the control block cb->local_address = local_address; - cb->is_master = (role == Gap::CENTRAL); + cb->is_master = (role == ::Gap::CENTRAL); // get the associated db handle and the distribution flags if any cb->db_entry = _db->open_entry(peer_address_type, peer_address); @@ -1074,7 +1074,7 @@ void GenericSecurityManager::on_connected( void GenericSecurityManager::on_disconnected( connection_handle_t connection, - Gap::DisconnectionReason_t reason + ::Gap::DisconnectionReason_t reason ) { MBED_ASSERT(_db); ControlBlock_t *cb = get_control_block(connection); diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h index 6f102d05d9..bb9da0dbe5 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/CordioGattServer.h @@ -86,7 +86,7 @@ public: * @see ::GattServer::read */ virtual ble_error_t read( - Gap::Handle_t connectionHandle, + connection_handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t buffer[], uint16_t *lengthP ); @@ -104,7 +104,7 @@ public: * @see ::GattServer::write */ virtual ble_error_t write( - Gap::Handle_t connectionHandle, + connection_handle_t connectionHandle, GattAttribute::Handle_t, const uint8_t[], uint16_t, @@ -122,7 +122,7 @@ public: * @see ::GattServer::areUpdatesEnabled */ virtual ble_error_t areUpdatesEnabled( - Gap::Handle_t connectionHandle, + connection_handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabledP ); @@ -224,7 +224,7 @@ private: GattCharacteristic* get_auth_char(uint16_t value_handle); bool get_cccd_index_by_cccd_handle(GattAttribute::Handle_t cccd_handle, uint8_t& idx) const; bool get_cccd_index_by_value_handle(GattAttribute::Handle_t char_handle, uint8_t& idx) const; - bool is_update_authorized(Gap::Handle_t connection, GattAttribute::Handle_t value_handle); + bool is_update_authorized(connection_handle_t connection, GattAttribute::Handle_t value_handle); struct alloc_block_t { alloc_block_t* next; diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp index 4e1b5bad68..57c02f8c3d 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioGattServer.cpp @@ -553,7 +553,7 @@ ble_error_t GattServer::read( } ble_error_t GattServer::read( - Gap::Handle_t connection, + connection_handle_t connection, GattAttribute::Handle_t att_handle, uint8_t buffer[], uint16_t *buffer_length @@ -652,7 +652,7 @@ ble_error_t GattServer::write( } ble_error_t GattServer::write( - Gap::Handle_t connection, + connection_handle_t connection, GattAttribute::Handle_t att_handle, const uint8_t buffer[], uint16_t len, @@ -733,7 +733,7 @@ ble_error_t GattServer::areUpdatesEnabled( } ble_error_t GattServer::areUpdatesEnabled( - Gap::Handle_t connectionHandle, + connection_handle_t connectionHandle, const GattCharacteristic &characteristic, bool *enabled ) { @@ -1232,7 +1232,7 @@ bool GattServer::get_cccd_index_by_value_handle(GattAttribute::Handle_t char_han } bool GattServer::is_update_authorized( - Gap::Handle_t connection, + connection_handle_t connection, GattAttribute::Handle_t value_handle ) { GattCharacteristic* auth_char = get_auth_char(value_handle); From 79518ca0898c67efefc8a9fa1deed55fa31b6dd6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 15:27:29 +0000 Subject: [PATCH 234/361] service data allows both types of UUIDs --- .../ble/gap/AdvertisingDataBuilder.h | 38 ++++++++++++++----- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 6bdb196c85..1b3700cf3a 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -126,6 +126,16 @@ struct adv_data_type_t : SafeEnum { */ SERVICE_DATA = 0x16, + /** + * Service Data. + */ + SERVICE_DATA_16BIT_ID = 0x16, + + /** + * Service Data. + */ + SERVICE_DATA_128BIT_ID = 0x21, + /** * Appearance, refer to AdvertisingData::Appearance_t. */ @@ -874,26 +884,34 @@ public: return BLE_ERROR_INVALID_PARAM; } + adv_data_type_t short_type = adv_data_type_t::SERVICE_DATA_16BIT_ID; + adv_data_type_t long_type = adv_data_type_t::SERVICE_DATA_128BIT_ID; + size_t total_size = data.size() + service.getLen() + 2; - size_t old_size = getFieldSize(adv_data_type_t::SERVICE_DATA); + size_t old_size = getFieldSize( + (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type + ); /* if we can't fit the new data do not proceed */ if (total_size > data.size() - (_payload_length - old_size)) { return BLE_ERROR_BUFFER_OVERFLOW; } - if (old_size) { - removeData(adv_data_type_t::SERVICE_DATA); - } - - ble_error_t status1 = addData( - adv_data_type_t::SERVICE_DATA, - mbed::make_Span(service.getBaseUUID(), service.getLen()) + /* this will insert only the UUID (and remove old data) */ + ble_error_t status = setUUIDData( + mbed::make_Span(&service, 1), + short_type, + long_type ); - ble_error_t status2 = appendData(adv_data_type_t::SERVICE_DATA, data); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } - if (status1 != BLE_ERROR_NONE || status2 != BLE_ERROR_NONE) { + status = appendData(adv_data_type_t::SERVICE_DATA, data); + + if (status != BLE_ERROR_NONE) { return BLE_ERROR_INTERNAL_STACK_FAILURE; } From 935444d128f4bd2f94bf73bac3f0b54adc4f7022 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 19 Nov 2018 15:30:05 +0000 Subject: [PATCH 235/361] use correct type for service data based on uuid length --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 1b3700cf3a..6e12d9a833 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -909,7 +909,10 @@ public: return BLE_ERROR_INTERNAL_STACK_FAILURE; } - status = appendData(adv_data_type_t::SERVICE_DATA, data); + status = appendData( + (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type, + data + ); if (status != BLE_ERROR_NONE) { return BLE_ERROR_INTERNAL_STACK_FAILURE; From e5e7f3edefa9bbcbbcad02cb066ab23b89598e34 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 20 Nov 2018 12:56:47 +0000 Subject: [PATCH 236/361] pull in inherited overloads --- features/FEATURE_BLE/ble/Gap.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 20af0404c0..b58a0a0f66 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -261,8 +261,13 @@ * controller or by the peer. */ class Gap : public ble::Gap { - public: + using ble::Gap::setAdvertisingParameters; + using ble::Gap::setAdvertisingPayload; + using ble::Gap::setAdvertisingScanResponse; + using ble::Gap::startAdvertising; + using ble::Gap::stopAdvertising; + /** * Address-type for BLEProtocol addresses. * From 75e61287760cf839333a953bd00b218c33664368 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 20 Nov 2018 15:33:13 +0000 Subject: [PATCH 237/361] solve link problems --- .../ble/gap/AdvertisingParameters.cpp | 25 +++++++++++++++++++ .../ble/gap/AdvertisingParameters.h | 6 ++--- 2 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp new file mode 100644 index 0000000000..8d0db1db88 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp @@ -0,0 +1,25 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include "ble/gap/AdvertisingParameters.h" + +namespace ble { + +const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; +const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; +const uint32_t AdvertisingParameters::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; + +} // namespace ble diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index ca8ce80216..fa724f72ce 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -48,9 +48,9 @@ namespace ble { */ class AdvertisingParameters { - static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN; - static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX; /** * Minimum Advertising interval for scannable and nonconnectable @@ -58,7 +58,7 @@ class AdvertisingParameters { * * @note Equal to 100ms. */ - static const uint32_t GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; + static const uint32_t GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; public: /** From b0b634605074b261f8d2045d4f99dbbf76d68d49 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 20 Nov 2018 16:16:26 +0000 Subject: [PATCH 238/361] added extra constructor --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 42 ++++++++++++++----- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 3312a47f77..99d89c8c18 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -34,10 +34,11 @@ class ScanParameters { public: struct phy_configuration_t { phy_configuration_t( - scan_window_t scan_interval, - scan_interval_t scan_window, - bool active_scanning - ) : interval(scan_interval), + scan_window_t scan_interval = scan_interval_t::min(), + scan_interval_t scan_window = scan_window_t::min(), + bool active_scanning = false + ) : + interval(scan_interval), window(scan_window), active_scanning(active_scanning) { @@ -55,12 +56,33 @@ public: own_address_type(own_address_type_t::PUBLIC), scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), phys(phy_set_t::PHY_SET_1M), - phy_1m_configuration( - scan_interval_t::min(), scan_window_t::min(), true - ), - phy_coded_configuration( - scan_interval_t::min(), scan_window_t::min(), true - ) + phy_1m_configuration(), + phy_coded_configuration() + { } + + ScanParameters( + phy_configuration_t phy_1m_configuration, + own_address_type_t own_address_type = own_address_type_t::PUBLIC, + scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER + ) : + own_address_type(own_address_type), + scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), + phys(phy_set_t::PHY_SET_1M), + phy_1m_configuration(phy_1m_configuration), + phy_coded_configuration() + { } + + ScanParameters( + phy_configuration_t phy_1m_configuration, + phy_configuration_t phy_coded_configuration, + own_address_type_t own_address_type = own_address_type_t::PUBLIC, + scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER + ) : + own_address_type(own_address_type), + scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), + phys(true, false, true), + phy_1m_configuration(phy_1m_configuration), + phy_coded_configuration(phy_coded_configuration) { } ScanParameters& set_own_address_type(own_address_type_t address) From 376cbd25faaee36eec439aa928af4ad064c9009f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 20 Nov 2018 17:46:56 +0000 Subject: [PATCH 239/361] fixed index and default constructor in conn params --- .../ble/gap/ConnectionParameters.h | 168 +++++++++++------- 1 file changed, 104 insertions(+), 64 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index d85ce867aa..2d7b3b1388 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -31,22 +31,39 @@ namespace ble { class ConnectionParameters { static const uint8_t MAX_PARAM_PHYS = 3; + static const uint8_t LE_1M_INDEX = 0; + static const uint8_t LE_2M_INDEX = 1; + static const uint8_t LE_CODED_INDEX = 2; + public: - ConnectionParameters() : + ConnectionParameters( + scan_interval_t scanInterval = scan_interval_t::min(), + scan_window_t scanWindow = scan_window_t::min(), + conn_interval_t minConnectionInterval = conn_interval_t::min(), + conn_interval_t maxConnectionInterval = conn_interval_t::max(), + slave_latency_t slaveLatency = slave_latency_t::min, + supervision_timeout_t connectionSupervisionTimeout = supervision_timeout_t::max(), + phy_t phy = phy_t::LE_1M + ) : _filterPolicy(initiator_filter_policy_t::NO_FILTER), _ownAddressType(own_address_type_t::PUBLIC) { for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { - _scanInterval[i] = 4; - _scanWindow[i] = 4; - _minConnectionInterval[i] = 6; - _maxConnectionInterval[i] = 0xC80; - _slaveLatency[i] = 0; - _connectionSupervisionTimeout[i] = 0xC80; - _minEventLength[i] = 0; - _maxEventLength[i] = 0xFFFF; _enabledPhy[i] = false; } + if (phy != phy_t::NONE) { + uint8_t phy_index = phyToIndex(phy); + + if (phy_index < MAX_PARAM_PHYS) { + _scanInterval[phy_index] = scanInterval.value(); + _scanWindow[phy_index] = scanWindow.value(); + _minConnectionInterval[phy_index] = minConnectionInterval.value(); + _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); + _slaveLatency[phy_index] = slaveLatency.value(); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); + _enabledPhy[phy_index] = true; + } + } }; /* setters */ @@ -55,12 +72,13 @@ public: scan_interval_t scanInterval, scan_window_t scanWindow, phy_t phy = phy_t::LE_1M - ) - { + ) { uint8_t phy_index = handlePhyToggle(phy, true); - _scanInterval[phy_index] = scanInterval.value(); - _scanWindow[phy_index] = scanWindow.value(); + if (phy_index < MAX_PARAM_PHYS) { + _scanInterval[phy_index] = scanInterval.value(); + _scanWindow[phy_index] = scanWindow.value(); + } return *this; } @@ -71,25 +89,26 @@ public: slave_latency_t slaveLatency, supervision_timeout_t connectionSupervisionTimeout, phy_t phy = phy_t::LE_1M, - conn_event_length_t minEventLength = conn_event_length_t(0), - conn_event_length_t maxEventLength = conn_event_length_t(0xFFFF) - ) - { + conn_event_length_t minEventLength = conn_event_length_t::min(), + conn_event_length_t maxEventLength = conn_event_length_t::max() + ) { uint8_t phy_index = handlePhyToggle(phy, true); - _minConnectionInterval[phy_index] = minConnectionInterval.value(); - _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); - _slaveLatency[phy_index] = slaveLatency.value(); - _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); + if (phy_index < MAX_PARAM_PHYS) { + _minConnectionInterval[phy_index] = minConnectionInterval.value(); + _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); + _slaveLatency[phy_index] = slaveLatency.value(); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); - /* avoid overflows and truncation */ - if (minEventLength.value() > maxEventLength.value()) { - minEventLength = maxEventLength; + /* avoid overflows and truncation */ + if (minEventLength.value() > maxEventLength.value()) { + minEventLength = maxEventLength; + } + + _minEventLength[phy_index] = minEventLength.value(); + _maxEventLength[phy_index] = maxEventLength.value(); } - _minEventLength[phy_index] = minEventLength.value(); - _maxEventLength[phy_index] = maxEventLength.value(); - return *this; } @@ -145,18 +164,18 @@ public: uint8_t getNumberOfEnabledPhys() const { return ( - _enabledPhy[phy_t::LE_1M] * 1 + - _enabledPhy[phy_t::LE_2M] * 1 + - _enabledPhy[phy_t::LE_CODED] * 1 + _enabledPhy[LE_1M_INDEX] * 1 + + _enabledPhy[LE_2M_INDEX] * 1 + + _enabledPhy[LE_CODED_INDEX] * 1 ); } uint8_t getPhySet() const { phy_set_t set( - _enabledPhy[phy_t::LE_1M], - _enabledPhy[phy_t::LE_2M], - _enabledPhy[phy_t::LE_CODED] + _enabledPhy[LE_1M_INDEX], + _enabledPhy[LE_2M_INDEX], + _enabledPhy[LE_CODED_INDEX] ); return set.value(); } @@ -206,11 +225,11 @@ public: private: uint8_t getFirstEnabledIndex() const { - if (_enabledPhy[phy_t::LE_1M]) { + if (_enabledPhy[LE_1M_INDEX]) { return 0; - } else if (_enabledPhy[phy_t::LE_2M]) { + } else if (_enabledPhy[LE_2M_INDEX]) { return 1; - } else if (_enabledPhy[phy_t::LE_CODED]) { + } else if (_enabledPhy[LE_CODED_INDEX]) { return 2; } /* this should never happen, it means you were trying to start a connection with a blank set @@ -227,7 +246,7 @@ private: */ uint8_t handlePhyToggle(phy_t phy, bool enable) { - uint8_t index = phy.value(); + uint8_t index = phyToIndex(phy); bool was_swapped = false; bool is_swapped = false; @@ -253,44 +272,65 @@ private: return index; } + uint8_t phyToIndex(phy_t phy) const + { + uint8_t index; + switch(phy.value()) { + case phy_t::LE_1M: + index = 0; + break; + case phy_t::LE_2M: + index = 1; + break; + case phy_t::LE_CODED: + index = 2; + break; + default: + index = MAX_PARAM_PHYS; + MBED_ASSERT("Illegal PHY"); + break; + } + return index; + } + bool isSwapped() const { return ( - _enabledPhy[phy_t::LE_1M] && - !_enabledPhy[phy_t::LE_2M] && - _enabledPhy[phy_t::LE_CODED] + _enabledPhy[LE_1M_INDEX] && + !_enabledPhy[LE_2M_INDEX] && + _enabledPhy[LE_CODED_INDEX] ); } /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ void swapCodedAnd2M() { - uint16_t scanInterval = _scanInterval[phy_t::LE_2M]; - uint16_t scanWindow = _scanWindow[phy_t::LE_2M]; - uint16_t minConnectionInterval = _minConnectionInterval[phy_t::LE_2M]; - uint16_t maxConnectionInterval = _maxConnectionInterval[phy_t::LE_2M]; - uint16_t slaveLatency = _maxConnectionInterval[phy_t::LE_2M]; - uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[phy_t::LE_2M]; - uint16_t minEventLength = _minEventLength[phy_t::LE_2M]; - uint16_t maxEventLength = _maxEventLength[phy_t::LE_2M]; + uint16_t scanInterval = _scanInterval[LE_2M_INDEX]; + uint16_t scanWindow = _scanWindow[LE_2M_INDEX]; + uint16_t minConnectionInterval = _minConnectionInterval[LE_2M_INDEX]; + uint16_t maxConnectionInterval = _maxConnectionInterval[LE_2M_INDEX]; + uint16_t slaveLatency = _maxConnectionInterval[LE_2M_INDEX]; + uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[LE_2M_INDEX]; + uint16_t minEventLength = _minEventLength[LE_2M_INDEX]; + uint16_t maxEventLength = _maxEventLength[LE_2M_INDEX]; - _scanInterval[phy_t::LE_2M] = _scanInterval[phy_t::LE_CODED]; - _scanWindow[phy_t::LE_2M] = _scanWindow[phy_t::LE_CODED]; - _minConnectionInterval[phy_t::LE_2M] = _minConnectionInterval[phy_t::LE_CODED]; - _maxConnectionInterval[phy_t::LE_2M] = _maxConnectionInterval[phy_t::LE_CODED]; - _slaveLatency[phy_t::LE_2M] = _slaveLatency[phy_t::LE_CODED]; - _connectionSupervisionTimeout[phy_t::LE_2M] = _connectionSupervisionTimeout[phy_t::LE_CODED]; - _minEventLength[phy_t::LE_2M] = _minEventLength[phy_t::LE_CODED]; - _maxEventLength[phy_t::LE_2M] = _maxEventLength[phy_t::LE_CODED]; + _scanInterval[LE_2M_INDEX] = _scanInterval[phy_t::LE_CODED]; + _scanWindow[LE_2M_INDEX] = _scanWindow[LE_CODED_INDEX]; + _minConnectionInterval[LE_2M_INDEX] = _minConnectionInterval[LE_CODED_INDEX]; + _maxConnectionInterval[LE_2M_INDEX] = _maxConnectionInterval[LE_CODED_INDEX]; + _slaveLatency[LE_2M_INDEX] = _slaveLatency[LE_CODED_INDEX]; + _connectionSupervisionTimeout[LE_2M_INDEX] = _connectionSupervisionTimeout[LE_CODED_INDEX]; + _minEventLength[LE_2M_INDEX] = _minEventLength[LE_CODED_INDEX]; + _maxEventLength[LE_2M_INDEX] = _maxEventLength[LE_CODED_INDEX]; - _scanInterval[phy_t::LE_CODED] = scanInterval; - _scanWindow[phy_t::LE_CODED] = scanWindow; - _minConnectionInterval[phy_t::LE_CODED] = minConnectionInterval; - _maxConnectionInterval[phy_t::LE_CODED] = maxConnectionInterval; - _slaveLatency[phy_t::LE_CODED] = slaveLatency; - _connectionSupervisionTimeout[phy_t::LE_CODED] = connectionSupervisionTimeout; - _minEventLength[phy_t::LE_CODED] = minEventLength; - _maxEventLength[phy_t::LE_CODED] = maxEventLength; + _scanInterval[LE_CODED_INDEX] = scanInterval; + _scanWindow[LE_CODED_INDEX] = scanWindow; + _minConnectionInterval[LE_CODED_INDEX] = minConnectionInterval; + _maxConnectionInterval[LE_CODED_INDEX] = maxConnectionInterval; + _slaveLatency[LE_CODED_INDEX] = slaveLatency; + _connectionSupervisionTimeout[LE_CODED_INDEX] = connectionSupervisionTimeout; + _minEventLength[LE_CODED_INDEX] = minEventLength; + _maxEventLength[LE_CODED_INDEX] = maxEventLength; } private: From 2e6fefa289b633aa1602e75aaba67f3f1c4fe807 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Tue, 20 Nov 2018 17:52:44 +0000 Subject: [PATCH 240/361] missing defaults --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 2d7b3b1388..d69122e4f3 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -43,7 +43,9 @@ public: conn_interval_t maxConnectionInterval = conn_interval_t::max(), slave_latency_t slaveLatency = slave_latency_t::min, supervision_timeout_t connectionSupervisionTimeout = supervision_timeout_t::max(), - phy_t phy = phy_t::LE_1M + phy_t phy = phy_t::LE_1M, + conn_event_length_t minEventLength = conn_event_length_t::min(), + conn_event_length_t maxEventLength = conn_event_length_t::max() ) : _filterPolicy(initiator_filter_policy_t::NO_FILTER), _ownAddressType(own_address_type_t::PUBLIC) @@ -62,6 +64,8 @@ public: _slaveLatency[phy_index] = slaveLatency.value(); _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); _enabledPhy[phy_index] = true; + _minEventLength[phy_index] = minEventLength.value(); + _maxEventLength[phy_index] = maxEventLength.value(); } } }; From 0b746a78c824608b81cee24dbc9ebd838144a793 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 12:01:38 +0000 Subject: [PATCH 241/361] BLE: prefix inclusion of Gap header with "ble/" --- features/FEATURE_BLE/ble/BLE.h | 2 +- features/FEATURE_BLE/ble/BLEInstanceBase.h | 2 +- features/FEATURE_BLE/ble/DiscoveredCharacteristic.h | 2 +- features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h | 2 +- features/FEATURE_BLE/ble/GattCharacteristic.h | 2 +- features/FEATURE_BLE/ble/GattClient.h | 2 +- features/FEATURE_BLE/ble/GattServer.h | 2 +- features/FEATURE_BLE/ble/SecurityManager.h | 2 +- features/FEATURE_BLE/ble/ServiceDiscovery.h | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index d117e5614a..5ba835b24a 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -18,7 +18,7 @@ #define MBED_BLE_H__ #include "blecommon.h" -#include "Gap.h" +#include "ble/Gap.h" #include "GattServer.h" #include "GattClient.h" #include "SecurityManager.h" diff --git a/features/FEATURE_BLE/ble/BLEInstanceBase.h b/features/FEATURE_BLE/ble/BLEInstanceBase.h index d7ff34cb71..1ed6745520 100644 --- a/features/FEATURE_BLE/ble/BLEInstanceBase.h +++ b/features/FEATURE_BLE/ble/BLEInstanceBase.h @@ -21,7 +21,7 @@ #ifndef MBED_BLE_DEVICE_INSTANCE_BASE__ #define MBED_BLE_DEVICE_INSTANCE_BASE__ -#include "Gap.h" +#include "ble/Gap.h" #include "ble/SecurityManager.h" #include "ble/BLE.h" diff --git a/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h b/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h index effc887851..68d81801ba 100644 --- a/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h +++ b/features/FEATURE_BLE/ble/DiscoveredCharacteristic.h @@ -18,7 +18,7 @@ #define MBED_DISCOVERED_CHARACTERISTIC_H__ #include "UUID.h" -#include "Gap.h" +#include "ble/Gap.h" #include "GattAttribute.h" #include "GattClient.h" #include "CharacteristicDescriptorDiscovery.h" diff --git a/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h b/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h index bb64c74486..7b333bdda7 100644 --- a/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h +++ b/features/FEATURE_BLE/ble/DiscoveredCharacteristicDescriptor.h @@ -18,7 +18,7 @@ #define MBED_DISCOVERED_CHARACTERISTIC_DESCRIPTOR_H__ #include "UUID.h" -#include "Gap.h" +#include "ble/Gap.h" #include "GattAttribute.h" #include "GattClient.h" #include "CharacteristicDescriptorDiscovery.h" diff --git a/features/FEATURE_BLE/ble/GattCharacteristic.h b/features/FEATURE_BLE/ble/GattCharacteristic.h index 2f0754b051..93400171e9 100644 --- a/features/FEATURE_BLE/ble/GattCharacteristic.h +++ b/features/FEATURE_BLE/ble/GattCharacteristic.h @@ -17,7 +17,7 @@ #ifndef __GATT_CHARACTERISTIC_H__ #define __GATT_CHARACTERISTIC_H__ -#include "Gap.h" +#include "ble/Gap.h" #include "SecurityManager.h" #include "GattAttribute.h" #include "GattCallbackParamTypes.h" diff --git a/features/FEATURE_BLE/ble/GattClient.h b/features/FEATURE_BLE/ble/GattClient.h index cabfaf9a19..fc60e5c840 100644 --- a/features/FEATURE_BLE/ble/GattClient.h +++ b/features/FEATURE_BLE/ble/GattClient.h @@ -17,7 +17,7 @@ #ifndef MBED_GATT_CLIENT_H__ #define MBED_GATT_CLIENT_H__ -#include "Gap.h" +#include "ble/Gap.h" #include "GattAttribute.h" #include "ServiceDiscovery.h" #include "CharacteristicDescriptorDiscovery.h" diff --git a/features/FEATURE_BLE/ble/GattServer.h b/features/FEATURE_BLE/ble/GattServer.h index 6704e6db58..3b0d140392 100644 --- a/features/FEATURE_BLE/ble/GattServer.h +++ b/features/FEATURE_BLE/ble/GattServer.h @@ -17,7 +17,7 @@ #ifndef MBED_GATT_SERVER_H__ #define MBED_GATT_SERVER_H__ -#include "Gap.h" +#include "ble/Gap.h" #include "GattService.h" #include "GattAttribute.h" #include "GattServerEvents.h" diff --git a/features/FEATURE_BLE/ble/SecurityManager.h b/features/FEATURE_BLE/ble/SecurityManager.h index 6f9f4c83ed..43346d4b93 100644 --- a/features/FEATURE_BLE/ble/SecurityManager.h +++ b/features/FEATURE_BLE/ble/SecurityManager.h @@ -19,7 +19,7 @@ #include -#include "Gap.h" +#include "ble/Gap.h" #include "CallChainOfFunctionPointersWithContext.h" #include "ble/BLETypes.h" diff --git a/features/FEATURE_BLE/ble/ServiceDiscovery.h b/features/FEATURE_BLE/ble/ServiceDiscovery.h index c2e7512d1f..3f49ccb1f0 100644 --- a/features/FEATURE_BLE/ble/ServiceDiscovery.h +++ b/features/FEATURE_BLE/ble/ServiceDiscovery.h @@ -18,7 +18,7 @@ #define MBED_BLE_SERVICE_DISOVERY_H__ #include "UUID.h" -#include "Gap.h" +#include "ble/Gap.h" #include "GattAttribute.h" class DiscoveredService; From 1802909272c17e2090e8fa0c1900a0502d2d7bed Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 15:30:45 +0000 Subject: [PATCH 242/361] BLE: Move Gap deprecated implementation in source/Gap.cpp . The implementation has been moved to a block that do not issue deprecation warning as this is an implementation detail. --- features/FEATURE_BLE/ble/Gap.h | 895 +++++++++++++--------------- features/FEATURE_BLE/source/Gap.cpp | 523 +++++++++++++++- 2 files changed, 914 insertions(+), 504 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index b58a0a0f66..8cf6be79ce 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1107,15 +1107,7 @@ public: virtual ble_error_t setAddress( BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address - ) { - /* avoid compiler warnings about unused variables */ - (void)type; - (void)address; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Fetch the current address and its type. @@ -1131,15 +1123,7 @@ public: virtual ble_error_t getAddress( BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address - ) { - /* Avoid compiler warnings about unused variables. */ - (void)typeP; - (void)address; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Return the type of a random address. @@ -1206,19 +1190,14 @@ public: * stopped. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use stopAdvertising(advertising_handle_t). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Use stopAdvertising(advertising_handle_t) instead." ) - virtual ble_error_t stopAdvertising(void) - { - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + virtual ble_error_t stopAdvertising(void); /** * Stop the ongoing scanning procedure. @@ -1249,23 +1228,21 @@ public: * @return BLE_ERROR_NONE if connection establishment procedure is started * successfully. The connectionCallChain (if set) is invoked upon * a connection event. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use connect(target_peer_address_type_t, address_t, ConnectionParameters). */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use connect(target_peer_address_type_t, address_t, ConnectionParameters) instead." + ) virtual ble_error_t connect( const BLEProtocol::AddressBytes_t peerAddr, PeerAddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams - ) { - /* Avoid compiler warnings about unused variables. */ - (void)peerAddr; - (void)peerAddrType; - (void)connectionParams; - (void)scanParams; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Initiate a connection to a peer. @@ -1296,17 +1273,7 @@ public: BLEProtocol::AddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams - ) { - /* Avoid compiler warnings about unused variables. */ - (void)peerAddr; - (void)peerAddrType; - (void)connectionParams; - (void)scanParams; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Initiate a connection to a peer. @@ -1342,18 +1309,18 @@ public: * * @return BLE_ERROR_NONE if the disconnection procedure successfully * started. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use disconnect(connection_handle_t, local_disconnection_reason_t) instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use disconnect(connection_handle_t, local_disconnection_reason_t) instead." + ) virtual ble_error_t disconnect( Handle_t connectionHandle, DisconnectionReason_t reason - ) { - /* avoid compiler warnings about unused variables */ - (void)connectionHandle; - (void)reason; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Initiate a disconnection procedure. @@ -1368,14 +1335,7 @@ public: * @return BLE_ERROR_NONE if disconnection was successful. */ MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.") - virtual ble_error_t disconnect(DisconnectionReason_t reason) { - /* Avoid compiler warnings about unused variables. */ - (void)reason; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + virtual ble_error_t disconnect(DisconnectionReason_t reason); public: @@ -1433,19 +1393,23 @@ public: * @param[in] params Pointer to desired connection parameters. * * @return BLE_ERROR_NONE if the connection parameters were updated correctly. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use updateConnectionParameters(connection_handle_t, conn_interval_t, + * conn_interval_t, slave_latency_t, supervision_timeout_t, + * conn_event_length_t, conn_event_length_t) instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use updateConnectionParameters(connection_handle_t, conn_interval_t, " + "conn_interval_t, slave_latency_t, supervision_timeout_t, " + "conn_event_length_t, conn_event_length_t) instead." + ) virtual ble_error_t updateConnectionParams( Handle_t handle, const ConnectionParams_t *params - ) { - /* avoid compiler warnings about unused variables */ - (void)handle; - (void)params; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + ); /** * Set the value of the device name characteristic in the Generic Access @@ -1542,40 +1506,30 @@ public: * correctly. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * See ble::AdvertisingParameters and setAdvertisingParameters. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "See ble::AdvertisingParameters and setAdvertisingParameters." ) - virtual ble_error_t setTxPower(int8_t txPower) - { - /* Avoid compiler warnings about unused variables. */ - (void)txPower; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + virtual ble_error_t setTxPower(int8_t txPower); /** * Query the underlying stack for allowed Tx power values. * * @param[out] valueArrayPP Receive the immutable array of Tx values. * @param[out] countP Receive the array's size. + * + * @deprecated Deprecated since addition of extended advertising support. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + ) virtual void getPermittedTxPowerValues( const int8_t **valueArrayPP, size_t *countP - ) { - /* Avoid compiler warnings about unused variables. */ - (void)valueArrayPP; - (void)countP; - - /* Requesting action from porter(s): override this API if this capability - is supported. */ - *countP = 0; - } + ); /** * Get the maximum size of the whitelist. @@ -1629,18 +1583,14 @@ public: * successfully. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * This setting is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "This setting is now part of advertising paramters." + "This setting is now part of ble::AdvertisingParameters." ) - virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } + virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode); /** * Set the scan policy filter mode to be used during the next scan procedure. @@ -1649,12 +1599,16 @@ public: * * @return BLE_ERROR_NONE if the specified policy filter mode was set * successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * This setting is now part of ble::ScanParameters. */ - virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "This setting is now part of ble::ScanParameters." + ) + virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode); /** * Set the initiator policy filter mode to be used during the next connection @@ -1664,12 +1618,16 @@ public: * * @return BLE_ERROR_NONE if the specified policy filter mode was set * successfully. + * + * @deprecated Deprecated since addition of extended advertising support. + * This setting is now part of ble::ConnectionParameters. */ - virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode) - { - (void) mode; - return BLE_ERROR_NOT_IMPLEMENTED; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "This setting is now part of ble::ConnectionParameters." + ) + virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode); /** * Get the current advertising policy filter mode. @@ -1677,37 +1635,38 @@ public: * @return The current advertising policy filter mode. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "This setting is now part of advertising paramters." ) - virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const - { - return ADV_POLICY_IGNORE_WHITELIST; - } + virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const; /** * Get the current scan policy filter mode. * * @return The current scan policy filter mode. + * + * @deprecated Deprecated since addition of extended advertising support. */ - virtual ScanningPolicyMode_t getScanningPolicyMode(void) const - { - return SCAN_POLICY_IGNORE_WHITELIST; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + ) + virtual ScanningPolicyMode_t getScanningPolicyMode(void) const; /** * Get the current initiator policy filter mode. * * @return The current scan policy filter mode. + * + * @deprecated Deprecated since addition of extended advertising support. */ - virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const - { - return INIT_POLICY_IGNORE_WHITELIST; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + ) + virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const; protected: /* Override the following in the underlying adaptation layer to provide the @@ -1719,14 +1678,18 @@ protected: * @param[in] scanningParams Parameters of the scan procedure. * * @return BLE_ERROR_NONE if the scan procedure was successfully started. + * + * @deprecated Deprecated since addition of extended advertising support. + * Vendors should use the cordio hci interface or the ble::pal or implement + * startScan(duplicates_filter_t, scan_duration_t, period) */ - virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) - { - (void)scanningParams; - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Vendors should use the cordio hci interface or the ble::pal or " + "implement startScan(duplicates_filter_t, scan_duration_t, period)" + ) + virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams); /* * APIs with nonvirtual implementations. @@ -1743,13 +1706,10 @@ public: */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." + "Deprecated since addition of extended advertising support. " "Use isAdvertisingActive() and getConnectionCount()." ) - GapState_t getState(void) const - { - return state; - } + GapState_t getState(void) const; /** * Set the advertising type to use during the advertising procedure. @@ -1757,17 +1717,15 @@ public: * @param[in] advType New type of advertising to use. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * This option is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "This option is now part of ble::AdvertisingParameters" ) - void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType) - { - _advParams.setAdvertisingType(advType); - } + void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType); + /** * Set the advertising interval. * @@ -1785,22 +1743,14 @@ public: * due to the higher data transmit rate. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * This option is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "This option is now part of ble::AdvertisingParameters" ) - void setAdvertisingInterval(uint16_t interval) - { - if (interval == 0) { - stopAdvertising(); - } else if (interval < getMinAdvertisingInterval()) { - interval = getMinAdvertisingInterval(); - } - _advParams.setInterval(interval); - } + void setAdvertisingInterval(uint16_t interval); /** * Set the advertising duration. @@ -1811,17 +1761,14 @@ public: * The special value 0 may be used to disable the advertising timeout. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * This option is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "This option is now part of ble::AdvertisingParameters" ) - void setAdvertisingTimeout(uint16_t timeout) - { - _advParams.setTimeout(timeout); - } + void setAdvertisingTimeout(uint16_t timeout); /** * Start the advertising procedure. @@ -1829,38 +1776,29 @@ public: * @return BLE_ERROR_NONE if the device started advertising successfully. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) instead." ) - ble_error_t startAdvertising(void) - { - ble_error_t rc; - if ((rc = startAdvertising(_advParams)) == BLE_ERROR_NONE) { - state.advertising = 1; - } - return rc; - } + ble_error_t startAdvertising(void); /** * Reset the value of the advertising payload advertised. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use setAdvertisingPayload(ble::advertising_handle_t, mbed::Span, + * bool). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use setAdvertisingPayload(ble::advertising_handle_t, mbed::Span," + "bool)." ) - void clearAdvertisingPayload(void) - { - _advPayload.clear(); - setAdvertisingData(_advPayload, _scanResponse); - } + void clearAdvertisingPayload(void); /** * Set gap flags in the advertising payload. @@ -1881,28 +1819,14 @@ public: * advertising payload. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Use ble::AdvertisingDataBuilder instead." ) - ble_error_t accumulateAdvertisingPayload(uint8_t flags) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addFlags(flags)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } + ble_error_t accumulateAdvertisingPayload(uint8_t flags); /** * Set the appearance field in the advertising payload. @@ -1923,28 +1847,14 @@ public: * advertising payload. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addAppearance(app)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app); /** * Set the Tx Power field in the advertising payload. @@ -1965,28 +1875,14 @@ public: * advertising payload. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) - { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addTxPower(power)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } + ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power); /** * Add a new field in the advertising payload. @@ -2015,29 +1911,16 @@ public: * supplied value is appended to the values previously added to the payload. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } + ); /** * Update a particular field in the advertising payload. @@ -2064,29 +1947,16 @@ public: * matching AD type; otherwise, an appropriate error. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + " Use ble::AdvertisingDataBuilder instead." ) ble_error_t updateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData advPayloadCopy = _advPayload; - ble_error_t rc; - if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(advPayloadCopy, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = advPayloadCopy; - } - - return rc; - } + ); /** * Set the value of the payload advertised. @@ -2098,22 +1968,14 @@ public: * set. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) - ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) - { - ble_error_t rc = setAdvertisingData(payload, _scanResponse); - if (rc == BLE_ERROR_NONE) { - _advPayload = payload; - } - - return rc; - } + ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload); /** * Get a reference to the current advertising payload. @@ -2121,17 +1983,12 @@ public: * @return A reference to the current advertising payload. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." ) - const GapAdvertisingData &getAdvertisingPayload(void) const - { - return _advPayload; - } + const GapAdvertisingData &getAdvertisingPayload(void) const; /** * Add a new field in the advertising payload. @@ -2149,24 +2006,11 @@ public: MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateScanResponse( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len - ) { - GapAdvertisingData scanResponseCopy = _scanResponse; - ble_error_t rc; - if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) { - return rc; - } - - rc = setAdvertisingData(_advPayload, scanResponseCopy); - if (rc == BLE_ERROR_NONE) { - _scanResponse = scanResponseCopy; - } - - return rc; - } + ); /** * Reset the content of the scan response. @@ -2175,17 +2019,14 @@ public: * or Gap::startAdvertising() before the update takes effect. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use setAdvertisingScanResponse(). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Use setAdvertisingScanResponse() instead." ) - void clearScanResponse(void) { - _scanResponse.clear(); - setAdvertisingData(_advPayload, _scanResponse); - } + void clearScanResponse(void); /** * Set the parameters used during a scan procedure. @@ -2218,23 +2059,21 @@ public: * enabled by using startScan(). * * @note The scan interval and window are recommendations to the BLE stack. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) ble_error_t setScanParams( uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, uint16_t timeout = 0, bool activeScanning = false - ) { - ble_error_t rc; - if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && - ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { - _scanningParams.setActiveScanning(activeScanning); - return BLE_ERROR_NONE; - } - - return rc; - } + ); /** * Set the parameters used during a scan procedure. @@ -2245,15 +2084,16 @@ public: * @return BLE_ERROR_NONE if the scan parameters were correctly set. * * @note All restrictions from setScanParams(uint16_t, uint16_t, uint16_t, bool) apply. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ - ble_error_t setScanParams(const GapScanningParams& scanningParams) { - return setScanParams( - scanningParams.getInterval(), - scanningParams.getWindow(), - scanningParams.getTimeout(), - scanningParams.getActiveScanning() - ); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) + ble_error_t setScanParams(const GapScanningParams& scanningParams); /** * Set the interval parameter used during scanning procedures. @@ -2263,11 +2103,16 @@ public: * The maximum allowed value is 10.24ms. * * @return BLE_ERROR_NONE if the scan interval was correctly set. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ - ble_error_t setScanInterval(uint16_t interval) - { - return _scanningParams.setInterval(interval); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) + ble_error_t setScanInterval(uint16_t interval); /** * Set the window parameter used during scanning procedures. @@ -2279,21 +2124,16 @@ public: * * @note If scanning is already active, the updated value of scanWindow * is propagated to the underlying BLE stack. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ - ble_error_t setScanWindow(uint16_t window) - { - ble_error_t rc; - if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) { - return rc; - } - - /* If scanning is already active, propagate the new setting to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) + ble_error_t setScanWindow(uint16_t window); /** * Set the timeout parameter used during scanning procedures. @@ -2305,21 +2145,16 @@ public: * * @note If scanning is already active, the updated value of scanTimeout * is propagated to the underlying BLE stack. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ - ble_error_t setScanTimeout(uint16_t timeout) - { - ble_error_t rc; - if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) { - return rc; - } - - /* If scanning is already active, propagate the new settings to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) + ble_error_t setScanTimeout(uint16_t timeout); /** * Enable or disable active scanning. @@ -2332,18 +2167,16 @@ public: * * @note If scanning is already in progress, then active scanning is * enabled for the underlying BLE stack. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setScanParameters(const ScanParameters &) instead. */ - ble_error_t setActiveScanning(bool activeScanning) - { - _scanningParams.setActiveScanning(activeScanning); - - /* If scanning is already active, propagate the new settings to the stack. */ - if (scanningActive) { - return startRadioScan(_scanningParams); - } - - return BLE_ERROR_NONE; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setScanParameters(const ScanParameters &) instead." + ) + ble_error_t setActiveScanning(bool activeScanning); /** * Start the scanning procedure. @@ -2360,26 +2193,16 @@ public: * @note The parameters used by the procedure are defined by setScanParams(). * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use startScan(duplicates_filter_t, scan_duration_t, scan_period_t) instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use startScan(duplicates_filter_t, scan_duration_t, scan_period_t) instead." ) ble_error_t startScan( void (*callback)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (callback) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(callback); - } - } - - return err; - } + ); /** * Start the scanning procedure. @@ -2400,27 +2223,20 @@ public: * * @deprecated Deprecated since addition of extended advertising support. * Use createAdvertisingSet(). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use startScan(duplicates_filter_t, scan_duration_t, scan_period_t) instead. */ - MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." - ); template + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use startScan(duplicates_filter_t, scan_duration_t, scan_period_t) instead." + ) ble_error_t startScan( T *object, void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) - ) { - ble_error_t err = BLE_ERROR_NONE; - if (object && callbackMember) { - if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { - scanningActive = true; - onAdvertisementReport.attach(object, callbackMember); - } - } - - return err; - } + ); /** * Enable radio-notification events. @@ -2436,13 +2252,14 @@ public: * or to trigger sensor data collection for transmission in the Radio Event. * * @return BLE_ERROR_NONE on successful initialization, otherwise an error code. + * + * @deprecated Deprecated since addition of extended advertising support. */ - virtual ble_error_t initRadioNotification(void) - { - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + ) + virtual ble_error_t initRadioNotification(void); /** * Enable or disable privacy mode of the local device. @@ -2547,12 +2364,12 @@ private: * @note Must be implemented in vendor port. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Implement setAdvertisingPayload() and setAdvertisingScanResponse() instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Implement setAdvertisingPayload() and setAdvertisingScanResponse() instead." ) virtual ble_error_t setAdvertisingData( const GapAdvertisingData &advData, @@ -2570,12 +2387,14 @@ private: * @note Must be implemented in vendor port. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Implement startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) + * instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Deprecated since addition of extended advertising support. " + "Implement startAdvertising(advertising_handle_t, adv_duration_t, uint8_t)" + "instead." ) virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) = 0; @@ -2586,17 +2405,12 @@ public: * @return A reference to the current advertising parameters. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." ) - GapAdvertisingParams &getAdvertisingParams(void) - { - return _advParams; - } + GapAdvertisingParams &getAdvertisingParams(void); /** * Const alternative to Gap::getAdvertisingParams(). @@ -2604,17 +2418,12 @@ public: * @return A const reference to the current advertising parameters. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." ) - const GapAdvertisingParams &getAdvertisingParams(void) const - { - return _advParams; - } + const GapAdvertisingParams &getAdvertisingParams(void) const; /** * Set the advertising parameters. @@ -2622,17 +2431,14 @@ public: * @param[in] newParams The new advertising parameters. * * @deprecated Deprecated since addition of extended advertising support. - * Use createAdvertisingSet(). + * Use setAdvertisingParameters() instead. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support." - "Use createAdvertisingSet() and use the resulting object's interface." + "Use setAdvertisingParameters() instead." ) - void setAdvertisingParams(const GapAdvertisingParams &newParams) - { - _advParams = newParams; - } + void setAdvertisingParams(const GapAdvertisingParams &newParams); /* Event handlers. */ public: @@ -2645,11 +2451,16 @@ public: * @note A callback may be unregistered using onTimeout().detach(callback). * * @see TimeoutSource_t + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - void onTimeout(TimeoutEventCallback_t callback) - { - timeoutCallbackChain.add(callback); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onTimeout(TimeoutEventCallback_t callback); /** * Get the callchain of registered timeout event handlers. @@ -2659,11 +2470,16 @@ public: * @note To unregister callbacks, use onTimeout().detach(callback). * * @return A reference to the timeout event callbacks chain. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - TimeoutEventCallbackChain_t& onTimeout() - { - return timeoutCallbackChain; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + TimeoutEventCallbackChain_t& onTimeout(); /** * Register a callback handling connection events. @@ -2671,11 +2487,16 @@ public: * @param[in] callback Event handler being registered. * * @note A callback may be unregistered using onConnection().detach(callback). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - void onConnection(ConnectionEventCallback_t callback) - { - connectionCallChain.add(callback); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onConnection(ConnectionEventCallback_t callback); /** * Register a callback handling connection events. @@ -2684,12 +2505,17 @@ public: * @param[in] mptr Event handler being registered. * * @note A callback may be unregistered using onConnection().detach(callback). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ template - void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) - { - connectionCallChain.add(tptr, mptr); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)); /** * Get the callchain of registered connection event handlers. @@ -2699,11 +2525,16 @@ public: * @note To unregister callbacks, use onConnection().detach(callback). * * @return A reference to the connection event callbacks chain. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - ConnectionEventCallbackChain_t& onConnection() - { - return connectionCallChain; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + ConnectionEventCallbackChain_t& onConnection(); /** * Register a callback handling disconnection events. @@ -2711,11 +2542,16 @@ public: * @param[in] callback Event handler being registered. * * @note A callback may be unregistered using onDisconnection().detach(callback). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - void onDisconnection(DisconnectionEventCallback_t callback) - { - disconnectionCallChain.add(callback); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onDisconnection(DisconnectionEventCallback_t callback); /** * Register a callback handling disconnection events. @@ -2724,12 +2560,17 @@ public: * @param[in] mptr Event handler being registered. * * @note A callback may be unregistered using onDisconnection().detach(callback). + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ template - void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) - { - disconnectionCallChain.add(tptr, mptr); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)); /** * Get the callchain of registered disconnection event handlers. @@ -2739,11 +2580,16 @@ public: * @note To unregister callbacks use onDisconnection().detach(callback). * * @return A reference to the disconnection event callbacks chain. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ - DisconnectionEventCallbackChain_t& onDisconnection() - { - return disconnectionCallChain; - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + DisconnectionEventCallbackChain_t& onDisconnection(); /** * Set the radio-notification events handler. @@ -2761,11 +2607,14 @@ public: * * @param[in] callback Application handler to be invoked in response to a * radio ACTIVE/INACTIVE event. + * + * @deprecated Deprecated since addition of extended advertising support. */ - void onRadioNotification(void (*callback)(bool param)) - { - radioNotificationCallback.attach(callback); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + ) + void onRadioNotification(void (*callback)(bool param)); /** * Set the radio-notification events handler. @@ -2773,12 +2622,17 @@ public: * @param[in] tptr Instance to be used to invoke mptr. * @param[in] mptr Application handler to be invoked in response to a * radio ACTIVE/INACTIVE event. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use setEventHandler() instead. */ template - void onRadioNotification(T *tptr, void (T::*mptr)(bool)) - { - radioNotificationCallback.attach(tptr, mptr); - } + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setEventHandler() instead." + ) + void onRadioNotification(T *tptr, void (T::*mptr)(bool)); /** * Register a Gap shutdown event handler. @@ -2791,10 +2645,7 @@ public: * @note To unregister a shutdown event handler, use * onShutdown().detach(callback). */ - void onShutdown(const GapShutdownCallback_t& callback) - { - shutdownCallChain.add(callback); - } + void onShutdown(const GapShutdownCallback_t& callback); /** * Register a Gap shutdown event handler. @@ -2817,10 +2668,7 @@ public: * * @return A reference to the shutdown event callback chain. */ - GapShutdownCallbackChain_t& onShutdown() - { - return shutdownCallChain; - } + GapShutdownCallbackChain_t& onShutdown(); public: /** @@ -2910,7 +2758,15 @@ public: * @param[in] connectionParams Parameters of the connection. * @param[in] peerResolvableAddr Resolvable address used by the peer. * @param[in] localResolvableAddr resolvable address used by the local device. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use EventHandler::onConnectionComplete() instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use EventHandler::onConnectionComplete() instead" + ) void processConnectionEvent( Handle_t handle, Role_t role, @@ -2969,7 +2825,15 @@ public: * * @param[in] handle Handle of the terminated connection. * @param[in] reason Reason of the disconnection. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use EventHandler::onDisconnection() instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use EventHandler::onDisconnection() instead" + ) void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) { /* Update Gap state */ @@ -2998,7 +2862,15 @@ public: * @param[in] advertisingData Pointer to the advertisement packet's data. * @param[in] addressType Type of the address of the peer that has emitted * the packet. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use EventHandler::onAdvertisingReport() instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use EventHandler::onAdvertisingReport() instead" + ) void processAdvertisementReport( const BLEProtocol::AddressBytes_t peerAddr, int8_t rssi, @@ -3052,7 +2924,15 @@ public: * implementation when a disconnection event occurs. * * @param[in] source Source of the timout event. + * + * @deprecated Deprecated since addition of extended advertising support. + * Use EventHandler instead. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use EventHandler instead" + ) void processTimeoutEvent(TimeoutSource_t source) { if (source == TIMEOUT_SRC_ADVERTISING) { @@ -3148,4 +3028,55 @@ private: * @} */ +/* -------- deprecated template implementation -------- */ + +#if defined(__GNUC__) && !defined(__CC_ARM) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__CC_ARM) +#pragma push +#pragma diag_suppress 1361 +#endif + +template +ble_error_t Gap::startScan( + T *object, + void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) +) { + ble_error_t err = BLE_ERROR_NONE; + if (object && callbackMember) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(object, callbackMember); + } + } + + return err; +} + + +template +void Gap::onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) +{ + connectionCallChain.add(tptr, mptr); +} + +template +void Gap::onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) +{ + disconnectionCallChain.add(tptr, mptr); +} + +template +void Gap::onRadioNotification(T *tptr, void (T::*mptr)(bool)) +{ + radioNotificationCallback.attach(tptr, mptr); +} + +#if defined(__GNUC__) && !defined(__CC_ARM) +#pragma GCC diagnostic pop +#elif defined(__CC_ARM) +#pragma pop +#endif + #endif // ifndef MBED_BLE_GAP_H__ diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index 00f29238ee..dbeeb3a8a2 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -130,32 +130,175 @@ void Gap::processConnectionEvent( connectionCallChain.call(&callbackParams); } -void Gap::processAdvertisementReport( - const BLEProtocol::AddressBytes_t peerAddr, - int8_t rssi, - bool isScanResponse, - GapAdvertisingParams::AdvertisingType_t type, - uint8_t advertisingDataLen, - const uint8_t *advertisingData, - PeerAddressType_t addressType +ble_error_t Gap::setAddress( + BLEProtocol::AddressType_t type, + const BLEProtocol::AddressBytes_t address ) { - AdvertisementCallbackParams_t params; + /* avoid compiler warnings about unused variables */ + (void)type; + (void)address; - memcpy(params.peerAddr, peerAddr, ADDR_LEN); - params.rssi = rssi; - params.isScanResponse = isScanResponse; - params.type = type; - params.advertisingDataLen = advertisingDataLen; - params.advertisingData = advertisingData; - params.peerAddrType = addressType; + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} - convert_address_type( - addressType, - peerAddr, - params.addressType - ); +ble_error_t Gap::getAddress( + BLEProtocol::AddressType_t *typeP, + BLEProtocol::AddressBytes_t address +) { + /* Avoid compiler warnings about unused variables. */ + (void)typeP; + (void)address; - onAdvertisementReport.call(¶ms); + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::stopAdvertising(void) +{ + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::connect( + const BLEProtocol::AddressBytes_t peerAddr, + PeerAddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams +) { + /* Avoid compiler warnings about unused variables. */ + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams; + (void)scanParams; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::connect( + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t peerAddrType, + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams +) { + /* Avoid compiler warnings about unused variables. */ + (void)peerAddr; + (void)peerAddrType; + (void)connectionParams; + (void)scanParams; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::disconnect( + Handle_t connectionHandle, DisconnectionReason_t reason +) { + /* avoid compiler warnings about unused variables */ + (void)connectionHandle; + (void)reason; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::disconnect(DisconnectionReason_t reason) { + /* Avoid compiler warnings about unused variables. */ + (void)reason; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::updateConnectionParams( + Handle_t handle, + const ConnectionParams_t *params +) { + /* avoid compiler warnings about unused variables */ + (void)handle; + (void)params; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setTxPower(int8_t txPower) +{ + /* Avoid compiler warnings about unused variables. */ + (void)txPower; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +void Gap::getPermittedTxPowerValues( + const int8_t **valueArrayPP, size_t *countP +) { + /* Avoid compiler warnings about unused variables. */ + (void)valueArrayPP; + (void)countP; + + /* Requesting action from porter(s): override this API if this capability + is supported. */ + *countP = 0; +} + +ble_error_t Gap::setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) +{ + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setScanningPolicyMode(ScanningPolicyMode_t mode) +{ + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) +{ + (void) mode; + return BLE_ERROR_NOT_IMPLEMENTED; +} + +Gap::AdvertisingPolicyMode_t Gap::getAdvertisingPolicyMode(void) const +{ + return ADV_POLICY_IGNORE_WHITELIST; +} + +Gap::ScanningPolicyMode_t Gap::getScanningPolicyMode(void) const +{ + return SCAN_POLICY_IGNORE_WHITELIST; +} + +Gap::InitiatorPolicyMode_t Gap::getInitiatorPolicyMode(void) const +{ + return INIT_POLICY_IGNORE_WHITELIST; +} + +ble_error_t Gap::startRadioScan(const GapScanningParams &scanningParams) +{ + (void)scanningParams; + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::initRadioNotification(void) +{ + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; } @@ -167,6 +310,314 @@ void Gap::processAdvertisementReport( #pragma diag_suppress 1361 #endif +Gap::GapState_t Gap::getState(void) const +{ + return state; +} + +void Gap::setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType) +{ + _advParams.setAdvertisingType(advType); +} + +void Gap::setAdvertisingInterval(uint16_t interval) +{ + if (interval == 0) { + stopAdvertising(); + } else if (interval < getMinAdvertisingInterval()) { + interval = getMinAdvertisingInterval(); + } + _advParams.setInterval(interval); +} + +void Gap::setAdvertisingTimeout(uint16_t timeout) +{ + _advParams.setTimeout(timeout); +} + +ble_error_t Gap::startAdvertising(void) +{ + ble_error_t rc; + if ((rc = startAdvertising(_advParams)) == BLE_ERROR_NONE) { + state.advertising = 1; + } + return rc; +} + +void Gap::clearAdvertisingPayload(void) +{ + _advPayload.clear(); + setAdvertisingData(_advPayload, _scanResponse); +} + +ble_error_t Gap::accumulateAdvertisingPayload(uint8_t flags) +{ + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addFlags(flags)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; +} + +ble_error_t Gap::accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) +{ + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addAppearance(app)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; +} + +ble_error_t Gap::accumulateAdvertisingPayloadTxPower(int8_t power) +{ + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addTxPower(power)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; +} + +ble_error_t Gap::accumulateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len +) { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; +} + +ble_error_t Gap::updateAdvertisingPayload( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len +) { + GapAdvertisingData advPayloadCopy = _advPayload; + ble_error_t rc; + if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(advPayloadCopy, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = advPayloadCopy; + } + + return rc; +} + +ble_error_t Gap::setAdvertisingPayload(const GapAdvertisingData &payload) +{ + ble_error_t rc = setAdvertisingData(payload, _scanResponse); + if (rc == BLE_ERROR_NONE) { + _advPayload = payload; + } + + return rc; +} + +const GapAdvertisingData &Gap::getAdvertisingPayload(void) const +{ + return _advPayload; +} + +ble_error_t Gap::accumulateScanResponse( + GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len +) { + GapAdvertisingData scanResponseCopy = _scanResponse; + ble_error_t rc; + if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) { + return rc; + } + + rc = setAdvertisingData(_advPayload, scanResponseCopy); + if (rc == BLE_ERROR_NONE) { + _scanResponse = scanResponseCopy; + } + + return rc; +} + +void Gap::clearScanResponse(void) +{ + _scanResponse.clear(); + setAdvertisingData(_advPayload, _scanResponse); +} + +ble_error_t Gap::setScanParams( + uint16_t interval, + uint16_t window, + uint16_t timeout, + bool activeScanning +) { + ble_error_t rc; + if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) && + ((rc = _scanningParams.setWindow(window)) == BLE_ERROR_NONE) && + ((rc = _scanningParams.setTimeout(timeout)) == BLE_ERROR_NONE)) { + _scanningParams.setActiveScanning(activeScanning); + return BLE_ERROR_NONE; + } + + return rc; +} + +ble_error_t Gap::setScanParams(const GapScanningParams& scanningParams) { + return setScanParams( + scanningParams.getInterval(), + scanningParams.getWindow(), + scanningParams.getTimeout(), + scanningParams.getActiveScanning() + ); +} + +ble_error_t Gap::setScanInterval(uint16_t interval) +{ + return _scanningParams.setInterval(interval); +} + +ble_error_t Gap::setScanWindow(uint16_t window) +{ + ble_error_t rc; + if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) { + return rc; + } + + /* If scanning is already active, propagate the new setting to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::setScanTimeout(uint16_t timeout) +{ + ble_error_t rc; + if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) { + return rc; + } + + /* If scanning is already active, propagate the new settings to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::setActiveScanning(bool activeScanning) +{ + _scanningParams.setActiveScanning(activeScanning); + + /* If scanning is already active, propagate the new settings to the stack. */ + if (scanningActive) { + return startRadioScan(_scanningParams); + } + + return BLE_ERROR_NONE; +} + +ble_error_t Gap::startScan( + void (*callback)(const AdvertisementCallbackParams_t *params) +) { + ble_error_t err = BLE_ERROR_NONE; + if (callback) { + if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { + scanningActive = true; + onAdvertisementReport.attach(callback); + } + } + + return err; +} + +GapAdvertisingParams &Gap::getAdvertisingParams(void) +{ + return _advParams; +} + +const GapAdvertisingParams &Gap::getAdvertisingParams(void) const +{ + return _advParams; +} + +void Gap::setAdvertisingParams(const GapAdvertisingParams &newParams) +{ + _advParams = newParams; +} + +void Gap::onTimeout(TimeoutEventCallback_t callback) +{ + timeoutCallbackChain.add(callback); +} + +Gap::TimeoutEventCallbackChain_t& Gap::onTimeout() +{ + return timeoutCallbackChain; +} + +void Gap::onConnection(ConnectionEventCallback_t callback) +{ + connectionCallChain.add(callback); +} + +Gap::ConnectionEventCallbackChain_t& Gap::onConnection() +{ + return connectionCallChain; +} + +void Gap::onDisconnection(DisconnectionEventCallback_t callback) +{ + disconnectionCallChain.add(callback); +} + +Gap::DisconnectionEventCallbackChain_t& Gap::onDisconnection() +{ + return disconnectionCallChain; +} + +void Gap::onRadioNotification(void (*callback)(bool param)) +{ + radioNotificationCallback.attach(callback); +} + +void Gap::onShutdown(const GapShutdownCallback_t& callback) +{ + shutdownCallChain.add(callback); +} + +Gap::GapShutdownCallbackChain_t& Gap::onShutdown() +{ + return shutdownCallChain; +} + + Gap::AdvertisementCallbackParams_t::AdvertisementCallbackParams_t() : peerAddr(), rssi(), @@ -354,6 +805,34 @@ void Gap::processAdvertisementReport( onAdvertisementReport.call(¶ms); } +void Gap::processAdvertisementReport( + const BLEProtocol::AddressBytes_t peerAddr, + int8_t rssi, + bool isScanResponse, + GapAdvertisingParams::AdvertisingType_t type, + uint8_t advertisingDataLen, + const uint8_t *advertisingData, + PeerAddressType_t addressType +) { + AdvertisementCallbackParams_t params; + + memcpy(params.peerAddr, peerAddr, ADDR_LEN); + params.rssi = rssi; + params.isScanResponse = isScanResponse; + params.type = type; + params.advertisingDataLen = advertisingDataLen; + params.advertisingData = advertisingData; + params.peerAddrType = addressType; + + convert_address_type( + addressType, + peerAddr, + params.addressType + ); + + onAdvertisementReport.call(¶ms); +} + #if defined(__GNUC__) && !defined(__CC_ARM) #pragma GCC diagnostic pop #elif defined(__CC_ARM) From a9fd0038033f5ef45841ca543c01dd9cc56cbd1f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 15:31:33 +0000 Subject: [PATCH 243/361] BLE: Move uses of deprecated Gap functions into isolated and warning free block. --- features/FEATURE_BLE/ble/BLE.h | 128 +++++++--------------------- features/FEATURE_BLE/source/BLE.cpp | 128 ++++++++++++++++++++++++++++ 2 files changed, 160 insertions(+), 96 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index 5ba835b24a..5b2ddc1dbc 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -484,9 +484,7 @@ public: * ble.gap().setAdvertisingType(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingType(...)") - void setAdvertisingType(GapAdvertisingParams::AdvertisingType advType) { - gap().setAdvertisingType(advType); - } + void setAdvertisingType(GapAdvertisingParams::AdvertisingType advType); /** * @param[in] interval @@ -515,9 +513,7 @@ public: * code depending on the old semantics needs to be updated accordingly. */ MBED_DEPRECATED("Use ble.gap().setAdvertisingInterval(...)") - void setAdvertisingInterval(uint16_t interval) { - gap().setAdvertisingInterval(interval); - } + void setAdvertisingInterval(uint16_t interval); /** * @return Minimum Advertising interval in milliseconds. @@ -569,9 +565,7 @@ public: * ble.gap().setAdvertisingTimeout(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingTimeout(...)") - void setAdvertisingTimeout(uint16_t timeout) { - gap().setAdvertisingTimeout(timeout); - } + void setAdvertisingTimeout(uint16_t timeout); /** * Set up a particular, user-constructed set of advertisement parameters for @@ -585,9 +579,7 @@ public: * ble.gap().setAdvertisingParams(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingParams(...)") - void setAdvertisingParams(const GapAdvertisingParams &advParams) { - gap().setAdvertisingParams(advParams); - } + void setAdvertisingParams(const GapAdvertisingParams &advParams); /** * @return Read back advertising parameters. Useful for storing and @@ -599,9 +591,7 @@ public: * ble.gap().getAdvertisingParams(...). */ MBED_DEPRECATED("Use ble.gap().getAdvertisingParams(...)") - const GapAdvertisingParams &getAdvertisingParams(void) const { - return gap().getAdvertisingParams(); - } + const GapAdvertisingParams &getAdvertisingParams(void) const; /** * Accumulate an AD structure in the advertising payload. Please note that @@ -620,9 +610,7 @@ public: * ble.gap().accumulateAdvertisingPayload(flags). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(flags)") - ble_error_t accumulateAdvertisingPayload(uint8_t flags) { - return gap().accumulateAdvertisingPayload(flags); - } + ble_error_t accumulateAdvertisingPayload(uint8_t flags); /** * Accumulate an AD structure in the advertising payload. Please note that @@ -640,9 +628,7 @@ public: * ble.gap().accumulateAdvertisingPayload(appearance). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(appearance)") - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) { - return gap().accumulateAdvertisingPayload(app); - } + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app); /** * Accumulate an AD structure in the advertising payload. Please note that @@ -660,9 +646,7 @@ public: * ble.gap().accumulateAdvertisingPayloadTxPower(txPower). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayloadTxPower(...)") - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) { - return gap().accumulateAdvertisingPayloadTxPower(power); - } + ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power); /** * Accumulate a variable length byte-stream as an AD structure in the @@ -680,9 +664,7 @@ public: * be replaced with ble.gap().accumulateAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(...)") - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { - return gap().accumulateAdvertisingPayload(type, data, len); - } + ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len); /** * Set up a particular, user-constructed advertisement payload for the @@ -695,9 +677,7 @@ public: * ble.gap().setAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().setAdvertisingData(...)") - ble_error_t setAdvertisingData(const GapAdvertisingData &advData) { - return gap().setAdvertisingPayload(advData); - } + ble_error_t setAdvertisingData(const GapAdvertisingData &advData); /** * @return Read back advertising data. Useful for storing and @@ -709,9 +689,7 @@ public: * ble.gap().getAdvertisingPayload()(...). */ MBED_DEPRECATED("Use ble.gap().getAdvertisingData(...)") - const GapAdvertisingData &getAdvertisingData(void) const { - return gap().getAdvertisingPayload(); - } + const GapAdvertisingData &getAdvertisingData(void) const; /** * Reset any advertising payload prepared from prior calls to @@ -724,9 +702,7 @@ public: * ble.gap().clearAdvertisingPayload(...). */ MBED_DEPRECATED("Use ble.gap().clearAdvertisingPayload(...)") - void clearAdvertisingPayload(void) { - gap().clearAdvertisingPayload(); - } + void clearAdvertisingPayload(void); /** * Dynamically reset the accumulated advertising @@ -743,9 +719,7 @@ public: * implicitly. */ MBED_DEPRECATED("Use ble.gap().setAdvertisingPayload(...)") - ble_error_t setAdvertisingPayload(void) { - return BLE_ERROR_NONE; - } + ble_error_t setAdvertisingPayload(void); /** * Accumulate a variable length byte-stream as an AD structure in the @@ -761,9 +735,7 @@ public: * ble.gap().accumulateScanResponse(...). */ MBED_DEPRECATED("Use ble.gap().accumulateScanResponse(...)") - ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { - return gap().accumulateScanResponse(type, data, len); - } + ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len); /** * Reset any scan response prepared from prior calls to @@ -775,9 +747,7 @@ public: * ble.gap().clearScanResponse(...). */ MBED_DEPRECATED("Use ble.gap().clearScanResponse(...)") - void clearScanResponse(void) { - gap().clearScanResponse(); - } + void clearScanResponse(void); /** * Start advertising. @@ -788,9 +758,7 @@ public: * ble.gap().startAdvertising(...). */ MBED_DEPRECATED("Use ble.gap().startAdvertising(...)") - ble_error_t startAdvertising(void) { - return gap().startAdvertising(); - } + ble_error_t startAdvertising(void); /** * Stop advertising. @@ -801,9 +769,7 @@ public: * ble.gap().stopAdvertising(...). */ MBED_DEPRECATED("Use ble.gap().stopAdvertising(...)") - ble_error_t stopAdvertising(void) { - return gap().stopAdvertising(); - } + ble_error_t stopAdvertising(void); /** * Set up parameters for GAP scanning (observer mode). @@ -838,9 +804,7 @@ public: ble_error_t setScanParams(uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, uint16_t timeout = 0, - bool activeScanning = false) { - return gap().setScanParams(interval, window, timeout, activeScanning); - } + bool activeScanning = false); /** * Set up the scanInterval parameter for GAP scanning (observer mode). @@ -863,9 +827,7 @@ public: * ble.gap().setScanInterval(interval). */ MBED_DEPRECATED("Use ble.gap().setScanInterval(...)") - ble_error_t setScanInterval(uint16_t interval) { - return gap().setScanInterval(interval); - } + ble_error_t setScanInterval(uint16_t interval); /** * Set up the scanWindow parameter for GAP scanning (observer mode). @@ -888,9 +850,7 @@ public: * ble.gap().setScanWindow(window). */ MBED_DEPRECATED("Use ble.gap().setScanWindow(...)") - ble_error_t setScanWindow(uint16_t window) { - return gap().setScanWindow(window); - } + ble_error_t setScanWindow(uint16_t window); /** * Set up parameters for GAP scanning (observer mode). @@ -915,9 +875,7 @@ public: * ble.gap().setScanTimeout(...). */ MBED_DEPRECATED("Use ble.gap().setScanTimeout(...)") - ble_error_t setScanTimeout(uint16_t timeout) { - return gap().setScanTimeout(timeout); - } + ble_error_t setScanTimeout(uint16_t timeout); /** * Set up parameters for GAP scanning (observer mode). @@ -934,9 +892,7 @@ public: * ble.gap().setActiveScanning(...). */ MBED_DEPRECATED("Use ble.gap().setActiveScan(...)") - void setActiveScan(bool activeScanning) { - gap().setActiveScanning(activeScanning); - } + void setActiveScan(bool activeScanning); /** * Start scanning (Observer Procedure) based on the parameters currently in @@ -953,9 +909,7 @@ public: * ble.gap().startScan(callback). */ MBED_DEPRECATED("Use ble.gap().startScan(callback)") - ble_error_t startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)) { - return gap().startScan(callback); - } + ble_error_t startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)); /** * Same as above, but this takes an (object, method) pair for a callback. @@ -1019,9 +973,7 @@ public: * The reason for disconnection; sent back to the peer. */ MBED_DEPRECATED("Use ble.gap().disconnect(...)") - ble_error_t disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason) { - return gap().disconnect(connectionHandle, reason); - } + ble_error_t disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason); /** * This call initiates the disconnection procedure, and its completion @@ -1053,9 +1005,7 @@ public: * ble.gap().getState(). */ MBED_DEPRECATED("Use ble.gap().getGapState(...)") - Gap::GapState_t getGapState(void) const { - return gap().getState(); - } + Gap::GapState_t getGapState(void) const; /** * Get the GAP peripheral's preferred connection parameters. These are the @@ -1113,9 +1063,7 @@ public: * ble.gap().updateConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().updateConnectionParams(...)") - ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params) { - return gap().updateConnectionParams(handle, params); - } + ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params); /** * Set the device name characteristic in the Gap service. @@ -1200,9 +1148,7 @@ public: * ble.gap().setTxPower(). */ MBED_DEPRECATED("Use ble.gap().setTxPower(...)") - ble_error_t setTxPower(int8_t txPower) { - return gap().setTxPower(txPower); - } + ble_error_t setTxPower(int8_t txPower); /** * Query the underlying stack for permitted arguments for setTxPower(). @@ -1218,9 +1164,7 @@ public: * ble.gap().getPermittedTxPowerValues(). */ MBED_DEPRECATED("Use ble.gap().getPermittedTxPowerValues(...)") - void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP) { - gap().getPermittedTxPowerValues(valueArrayPP, countP); - } + void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP); /** * Add a service declaration to the local server ATT table. Also add the @@ -1433,9 +1377,7 @@ public: * ble.gap().onTimeout(callback). */ MBED_DEPRECATED("ble.gap().onTimeout(callback)") - void onTimeout(Gap::TimeoutEventCallback_t timeoutCallback) { - gap().onTimeout(timeoutCallback); - } + void onTimeout(Gap::TimeoutEventCallback_t timeoutCallback); /** * Set up a callback for connection events. Refer to Gap::ConnectionEventCallback_t. @@ -1446,9 +1388,7 @@ public: * ble.gap().onConnection(callback). */ MBED_DEPRECATED("ble.gap().onConnection(callback)") - void onConnection(Gap::ConnectionEventCallback_t connectionCallback) { - gap().onConnection(connectionCallback); - } + void onConnection(Gap::ConnectionEventCallback_t connectionCallback); /** * Append to a chain of callbacks to be invoked upon GAP disconnection. @@ -1459,9 +1399,7 @@ public: * ble.gap().onDisconnection(callback). */ MBED_DEPRECATED("ble.gap().onDisconnection(callback)") - void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback) { - gap().onDisconnection(disconnectionCallback); - } + void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback); /** * The same as onDisconnection() but allows an object reference and member function @@ -1500,9 +1438,7 @@ public: * ble.gap().onRadioNotification(...). */ MBED_DEPRECATED("ble.gap().onRadioNotification(...)") - void onRadioNotification(void (*callback)(bool)) { - gap().onRadioNotification(callback); - } + void onRadioNotification(void (*callback)(bool)); /** * Add a callback for the GATT event DATA_SENT (which is triggered when diff --git a/features/FEATURE_BLE/source/BLE.cpp b/features/FEATURE_BLE/source/BLE.cpp index e6212e0e9c..e61356c075 100644 --- a/features/FEATURE_BLE/source/BLE.cpp +++ b/features/FEATURE_BLE/source/BLE.cpp @@ -383,5 +383,133 @@ ble_error_t BLE::disconnect(Gap::DisconnectionReason_t reason) { return gap().disconnect(reason); } +Gap::GapState_t BLE::getGapState(void) const { + return gap().getState(); +} + +void BLE::setAdvertisingType(GapAdvertisingParams::AdvertisingType advType) { + gap().setAdvertisingType(advType); +} + +void BLE::setAdvertisingInterval(uint16_t interval) { + gap().setAdvertisingInterval(interval); +} + +void BLE::setAdvertisingTimeout(uint16_t timeout) { + gap().setAdvertisingTimeout(timeout); +} + +void BLE::setAdvertisingParams(const GapAdvertisingParams &advParams) { + gap().setAdvertisingParams(advParams); +} + +const GapAdvertisingParams &BLE::getAdvertisingParams(void) const { + return gap().getAdvertisingParams(); +} + +ble_error_t BLE::accumulateAdvertisingPayload(uint8_t flags) { + return gap().accumulateAdvertisingPayload(flags); +} + +ble_error_t BLE::accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) { + return gap().accumulateAdvertisingPayload(app); +} + +ble_error_t BLE::accumulateAdvertisingPayloadTxPower(int8_t power) { + return gap().accumulateAdvertisingPayloadTxPower(power); +} + +ble_error_t BLE::accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { + return gap().accumulateAdvertisingPayload(type, data, len); +} + +ble_error_t BLE::setAdvertisingData(const GapAdvertisingData &advData) { + return gap().setAdvertisingPayload(advData); +} + +const GapAdvertisingData &BLE::getAdvertisingData(void) const { + return gap().getAdvertisingPayload(); +} + +void BLE::clearAdvertisingPayload(void) { + gap().clearAdvertisingPayload(); +} + +ble_error_t BLE::setAdvertisingPayload(void) { + return BLE_ERROR_NONE; +} + +ble_error_t BLE::accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) { + return gap().accumulateScanResponse(type, data, len); +} + +void BLE::clearScanResponse(void) { + gap().clearScanResponse(); +} + +ble_error_t BLE::startAdvertising(void) { + return gap().startAdvertising(); +} + +ble_error_t BLE::stopAdvertising(void) { + return gap().stopAdvertising(); +} + +ble_error_t BLE::setScanParams(uint16_t interval, + uint16_t window, + uint16_t timeout, + bool activeScanning) { + return gap().setScanParams(interval, window, timeout, activeScanning); +} + +ble_error_t BLE::setScanInterval(uint16_t interval) { + return gap().setScanInterval(interval); +} + +ble_error_t BLE::setScanWindow(uint16_t window) { + return gap().setScanWindow(window); +} + +ble_error_t BLE::setScanTimeout(uint16_t timeout) { + return gap().setScanTimeout(timeout); +} + +void BLE::setActiveScan(bool activeScanning) { + gap().setActiveScanning(activeScanning); +} + +ble_error_t BLE::startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)) { + return gap().startScan(callback); +} + +ble_error_t BLE::disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason) { + return gap().disconnect(connectionHandle, reason); +} + +ble_error_t BLE::updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params) { + return gap().updateConnectionParams(handle, params); +} + +ble_error_t BLE::setTxPower(int8_t txPower) { + return gap().setTxPower(txPower); +} + +void BLE::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP) { + gap().getPermittedTxPowerValues(valueArrayPP, countP); +} + +void BLE::onTimeout(Gap::TimeoutEventCallback_t timeoutCallback) { + gap().onTimeout(timeoutCallback); +} + +void BLE::onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback) { + gap().onDisconnection(disconnectionCallback); +} + +void BLE::onRadioNotification(void (*callback)(bool)) { + gap().onRadioNotification(callback); +} + + BLE_DEPRECATED_API_USE_END From 4fdb9c7e6709e784cc85bcda6b1289cee01722c1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 15:32:09 +0000 Subject: [PATCH 244/361] BLE: provide default implementation ::ble::Gap::isFeatureSupported --- features/FEATURE_BLE/ble/gap/Gap.h | 5 +---- features/FEATURE_BLE/source/gap/Gap.cpp | 5 +++++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 512e9b30fe..6d41d0e0a3 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -167,10 +167,7 @@ public: * @param feature Feature to check. * @return True if feature is supported. */ - virtual bool isFeatureSupported(controller_supported_features_t feature) - { - // TODO: deal with legacy implementation - } + virtual bool isFeatureSupported(controller_supported_features_t feature); /* advertising */ diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 3907f88040..782e69e13b 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -18,6 +18,11 @@ namespace ble { +bool Gap::isFeatureSupported(controller_supported_features_t feature) +{ + return false; +} + uint8_t Gap::getMaxAdvertisingSetNumber() { /* Requesting action from porter(s): override this API if this capability is supported. */ From bc6078eb779058cddbd716319cd8f47a09534338 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 15:32:56 +0000 Subject: [PATCH 245/361] BLE: prevent warning from deprecated API implementation in GenericGap. --- features/FEATURE_BLE/ble/pal/Deprecated.h | 48 +++++++++++++++++++ .../FEATURE_BLE/source/generic/GenericGap.cpp | 16 ++++++- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 features/FEATURE_BLE/ble/pal/Deprecated.h diff --git a/features/FEATURE_BLE/ble/pal/Deprecated.h b/features/FEATURE_BLE/ble/pal/Deprecated.h new file mode 100644 index 0000000000..7af4795cef --- /dev/null +++ b/features/FEATURE_BLE/ble/pal/Deprecated.h @@ -0,0 +1,48 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BLE_PAL_DEPRECATED_H +#define BLE_PAL_DEPRECATED_H + +/** + * Declare the beginning of a code block that uses a deprecated API + */ +#if defined(__GNUC__) && !defined(__CC_ARM) +#define BLE_DEPRECATED_API_USE_BEGIN() \ + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif defined(__CC_ARM) +#define BLE_DEPRECATED_API_USE_BEGIN() \ + _Pragma("push") \ + _Pragma("diag_suppress 1361") +#else +#define BLE_DEPRECATED_API_USE_BEGIN() +#endif + +/** + * Declare the end of a code block that uses a deprecated API + */ +#if defined(__GNUC__) && !defined(__CC_ARM) +#define BLE_DEPRECATED_API_USE_END() \ + _Pragma("GCC diagnostic pop") +#elif defined(__CC_ARM) +#define BLE_DEPRECATED_API_USE_END() \ + _Pragma("pop") +#else +#define BLE_DEPRECATED_API_USE_END() +#endif + + +#endif //BLE_PAL_DEPRECATED_H diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0ce8e56e8c..02adff4751 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -27,7 +27,9 @@ #include "ble/generic/GenericGap.h" #include "drivers/Timeout.h" -#include "Span.h" +#include "platform/Span.h" + +#include "ble/pal/Deprecated.h" namespace ble { namespace generic { @@ -1273,6 +1275,7 @@ void GenericGap::processConnectionEvent( ); } +BLE_DEPRECATED_API_USE_BEGIN() ::Gap::processConnectionEvent( handle, role, @@ -1284,6 +1287,7 @@ void GenericGap::processConnectionEvent( peerResolvableAddr, localResolvableAddr ); +BLE_DEPRECATED_API_USE_END() } void GenericGap::processDisconnectionEvent( @@ -1306,10 +1310,12 @@ void GenericGap::processDisconnectionEvent( ); } +BLE_DEPRECATED_API_USE_BEGIN() ::Gap::processDisconnectionEvent( handle, reason ); +BLE_DEPRECATED_API_USE_END() } void GenericGap::on_scan_timeout() @@ -1327,7 +1333,9 @@ void GenericGap::process_scan_timeout() if (err) { // TODO: define the mechanism signaling the error } +BLE_DEPRECATED_API_USE_BEGIN() processTimeoutEvent(::Gap::TIMEOUT_SRC_SCAN); +BLE_DEPRECATED_API_USE_END() } void GenericGap::on_advertising_timeout() @@ -1345,7 +1353,9 @@ void GenericGap::process_advertising_timeout() // Stop address rotation if required set_random_address_rotation(false); +BLE_DEPRECATED_API_USE_BEGIN() processTimeoutEvent(::Gap::TIMEOUT_SRC_ADVERTISING); +BLE_DEPRECATED_API_USE_END() } void GenericGap::on_gap_event_received(const pal::GapEvent& e) @@ -1400,6 +1410,7 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent& e) peer_address_type_t peer_address_type = static_cast(advertising.address_type.value()); +BLE_DEPRECATED_API_USE_BEGIN() processAdvertisementReport( advertising.address.data(), advertising.rssi, @@ -1409,6 +1420,7 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent& e) advertising.data.data(), peer_address_type ); +BLE_DEPRECATED_API_USE_END() } } @@ -1419,7 +1431,9 @@ void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent& e // event // TODO: Define events in case of connection faillure +BLE_DEPRECATED_API_USE_BEGIN() processTimeoutEvent(::Gap::TIMEOUT_SRC_CONN); +BLE_DEPRECATED_API_USE_END() return; } From dd2c85d0631799779a7e329f9f67bbd56226be26 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 15:33:34 +0000 Subject: [PATCH 246/361] BLE: Fix signeness warning in AdvertisingDataBuilder. --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 6e12d9a833..495a6f38bb 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -1208,7 +1208,7 @@ private: size_t size_long = 0; size_t size_short = 0; - for (size_t i = 0; i < data.size(); ++i) { + for (size_t i = 0, end = data.size(); i < end; ++i) { if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { size_short++; } else { @@ -1237,7 +1237,7 @@ private: removeData(longType); /* and insert individual UUIDs into appropriate fields */ - for (size_t i = 0; i < data.size(); ++i) { + for (size_t i = 0, end = data.size(); i < end; ++i) { adv_data_type_t field_type = (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) ? shortType : longType; mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); From c54e0d9862b4f624b13a381f2aef573c9177b36f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:22:34 +0000 Subject: [PATCH 247/361] BLE: Move Gap::StopScan into ::ble::Gap::stopScan . --- features/FEATURE_BLE/ble/Gap.h | 14 -------------- features/FEATURE_BLE/ble/gap/Gap.h | 15 +++++++++++++++ features/FEATURE_BLE/source/gap/Gap.cpp | 7 +++++++ 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 8cf6be79ce..c3d7168cb8 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1198,20 +1198,6 @@ public: "Use stopAdvertising(advertising_handle_t) instead." ) virtual ble_error_t stopAdvertising(void); - - /** - * Stop the ongoing scanning procedure. - * - * The current scanning parameters remain in effect. - * - * @retval BLE_ERROR_NONE if successfully stopped scanning procedure. - */ - virtual ble_error_t stopScan() - { - /* Requesting action from porter(s): override this API if this capability - is supported. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } /** * Initiate a connection to a peer. diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 6d41d0e0a3..eec42ee863 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -351,6 +351,15 @@ public: scan_period_t period = scan_period_t(0) ); + /** + * Stop the ongoing scanning procedure. + * + * The current scanning parameters remain in effect. + * + * @retval BLE_ERROR_NONE if successfully stopped scanning procedure. + */ + virtual ble_error_t stopScan(); + /** Synchronise with periodic advertising from an advertiser and begin receiving periodic * advertising packets. * @@ -583,6 +592,12 @@ protected: */ virtual void useVersionTwoAPI() const { } + + /* -------- soon to be deprecated API -------- */ + + + +protected: /** * Construct a Gap instance. */ diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 782e69e13b..e6adc087b3 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -148,6 +148,13 @@ ble_error_t Gap::startScan( return BLE_ERROR_NOT_IMPLEMENTED; }; +ble_error_t Gap::stopScan() +{ + /* Requesting action from porter(s): override this API if this capability + is supported. */ + return BLE_ERROR_NOT_IMPLEMENTED; +} + ble_error_t Gap::createSync( peer_address_type_t peerAddressType, const address_t &peerAddress, From 586aea553b2754efce60754bc24ec3d3f9eaa946 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:33:04 +0000 Subject: [PATCH 248/361] BLE: Move privacy subsystem to ::ble::Gap. --- features/FEATURE_BLE/ble/Gap.h | 199 ------------------------ features/FEATURE_BLE/ble/gap/Gap.h | 189 ++++++++++++++++++++++ features/FEATURE_BLE/source/Gap.cpp | 12 -- features/FEATURE_BLE/source/gap/Gap.cpp | 43 +++++ 4 files changed, 232 insertions(+), 211 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index c3d7168cb8..f357e09ac2 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -865,119 +865,11 @@ public: {} }; - /** - * Privacy Configuration of the peripheral role. - * - * @note This configuration also applies to the broadcaster role configuration. - */ - struct PeripheralPrivacyConfiguration_t { - /** - * Indicates if non resolvable random address should be used when the - * peripheral advertises non connectable packets. - * - * Resolvable random address continues to be used for connectable packets. - */ - bool use_non_resolvable_random_address; - - /** - * Resolution strategy for initiator resolvable addresses when a - * connection request is received. - */ - enum ResolutionStrategy { - /** - * Do not resolve the address of the initiator and accept the - * connection request. - */ - DO_NOT_RESOLVE, - - /** - * If a bond is present in the secure database and the address - * resolution fail then reject the connection request with the error - * code AUTHENTICATION_FAILLURE. - */ - REJECT_NON_RESOLVED_ADDRESS, - - /** - * Perform the pairing procedure if the initiator resolvable - * address failed the resolution process. - */ - PERFORM_PAIRING_PROCEDURE, - - /** - * Perform the authentication procedure if the initiator resolvable - * address failed the resolution process. - */ - PERFORM_AUTHENTICATION_PROCEDURE - }; - - /** - * Connection strategy to use when a connection request contains a - * private resolvable address. - */ - ResolutionStrategy resolution_strategy; - }; - - /** - * Privacy Configuration of the central role. - * - * @note This configuration is also used when the local device operates as - * an observer. - */ - struct CentralPrivacyConfiguration_t { - /** - * Indicates if non resolvable random address should be used when the - * central or observer sends scan request packets. - * - * Resolvable random address continue to be used for connection requests. - */ - bool use_non_resolvable_random_address; - - - /** - * Resolution strategy of resolvable addresses received in advertising - * packets. - */ - enum ResolutionStrategy { - /** - * Do not resolve the address received in advertising packets. - */ - DO_NOT_RESOLVE, - - /** - * Resolve the resolvable addresses in the advertising packet and - * forward advertising packet to the application independently of - * the address resolution procedure result. - */ - RESOLVE_AND_FORWARD, - - /** - * Filter out packets containing a resolvable that cannot be resolved - * by this device. - * - * @note Filtering is applied if the local device contains at least - * one bond. - */ - RESOLVE_AND_FILTER - }; - - /** - * Resolution strategy applied to advertising packets received by the - * local device. - */ - ResolutionStrategy resolution_strategy; - }; - /** * Number of microseconds in 1.25 milliseconds. */ static const uint16_t UNIT_1_25_MS = 1250; - static const PeripheralPrivacyConfiguration_t - default_peripheral_privacy_configuration; - - static const CentralPrivacyConfiguration_t - default_central_privacy_configuration; - /** * Convert milliseconds into 1.25ms units. * @@ -2247,97 +2139,6 @@ public: ) virtual ble_error_t initRadioNotification(void); - /** - * Enable or disable privacy mode of the local device. - * - * When privacy is enabled, the system use private addresses while it scans, - * advertises or initiate a connection. The device private address is - * renewed every 15 minutes. - * - * @par Configuration - * - * The privacy feature can be configured with the help of the functions - * setPeripheralPrivacyConfiguration and setCentralPrivacyConfiguration - * which respectively set the privacy configuration of the peripheral and - * central role. - * - * @par Default configuration of peripheral role - * - * By default private resolvable addresses are used for all procedures; - * including advertisement of non connectable packets. Connection request - * from an unknown initiator with a private resolvable address triggers the - * pairing procedure. - * - * @par Default configuration of central role - * - * By default private resolvable addresses are used for all procedures; - * including active scanning. Addresses present in advertisement packet are - * resolved and advertisement packets are forwarded to the application - * even if the advertiser private address is unknown. - * - * @param[in] enable Should be set to true to enable the privacy mode and - * false to disable it. - * - * @return BLE_ERROR_NONE in case of success or an appropriate error code. - */ - virtual ble_error_t enablePrivacy(bool enable) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the privacy configuration used by the peripheral role. - * - * @param[in] configuration The configuration to set. - * - * @return BLE_ERROR_NONE in case of success or an appropriate error code. - */ - virtual ble_error_t setPeripheralPrivacyConfiguration( - const PeripheralPrivacyConfiguration_t *configuration - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the privacy configuration used by the peripheral role. - * - * @param[out] configuration The variable filled with the current - * configuration. - * - * @return BLE_ERROR_NONE in case of success or an appropriate error code. - */ - virtual ble_error_t getPeripheralPrivacyConfiguration( - PeripheralPrivacyConfiguration_t *configuration - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Set the privacy configuration used by the central role. - * - * @param[in] configuration The configuration to set. - * - * @return BLE_ERROR_NONE in case of success or an appropriate error code. - */ - virtual ble_error_t setCentralPrivacyConfiguration( - const CentralPrivacyConfiguration_t *configuration - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /** - * Get the privacy configuration used by the central role. - * - * @param[out] configuration The variable filled with the current - * configuration. - * - * @return BLE_ERROR_NONE in case of success or an appropriate error code. - */ - virtual ble_error_t getCentralPrivacyConfiguration( - CentralPrivacyConfiguration_t *configuration - ) { - return BLE_ERROR_NOT_IMPLEMENTED; - } - private: /** * Set the advertising data and scan response in the vendor subsytem. diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index eec42ee863..220fc0822b 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -595,7 +595,196 @@ protected: /* -------- soon to be deprecated API -------- */ +public: + /** + * Privacy Configuration of the peripheral role. + * + * @note This configuration also applies to the broadcaster role configuration. + */ + struct PeripheralPrivacyConfiguration_t { + /** + * Indicates if non resolvable random address should be used when the + * peripheral advertises non connectable packets. + * + * Resolvable random address continues to be used for connectable packets. + */ + bool use_non_resolvable_random_address; + + /** + * Resolution strategy for initiator resolvable addresses when a + * connection request is received. + */ + enum ResolutionStrategy { + /** + * Do not resolve the address of the initiator and accept the + * connection request. + */ + DO_NOT_RESOLVE, + + /** + * If a bond is present in the secure database and the address + * resolution fail then reject the connection request with the error + * code AUTHENTICATION_FAILLURE. + */ + REJECT_NON_RESOLVED_ADDRESS, + + /** + * Perform the pairing procedure if the initiator resolvable + * address failed the resolution process. + */ + PERFORM_PAIRING_PROCEDURE, + + /** + * Perform the authentication procedure if the initiator resolvable + * address failed the resolution process. + */ + PERFORM_AUTHENTICATION_PROCEDURE + }; + + /** + * Connection strategy to use when a connection request contains a + * private resolvable address. + */ + ResolutionStrategy resolution_strategy; + }; + + /** + * Privacy Configuration of the central role. + * + * @note This configuration is also used when the local device operates as + * an observer. + */ + struct CentralPrivacyConfiguration_t { + /** + * Indicates if non resolvable random address should be used when the + * central or observer sends scan request packets. + * + * Resolvable random address continue to be used for connection requests. + */ + bool use_non_resolvable_random_address; + + + /** + * Resolution strategy of resolvable addresses received in advertising + * packets. + */ + enum ResolutionStrategy { + /** + * Do not resolve the address received in advertising packets. + */ + DO_NOT_RESOLVE, + + /** + * Resolve the resolvable addresses in the advertising packet and + * forward advertising packet to the application independently of + * the address resolution procedure result. + */ + RESOLVE_AND_FORWARD, + + /** + * Filter out packets containing a resolvable that cannot be resolved + * by this device. + * + * @note Filtering is applied if the local device contains at least + * one bond. + */ + RESOLVE_AND_FILTER + }; + + /** + * Resolution strategy applied to advertising packets received by the + * local device. + */ + ResolutionStrategy resolution_strategy; + }; + + static const PeripheralPrivacyConfiguration_t + default_peripheral_privacy_configuration; + + static const CentralPrivacyConfiguration_t + default_central_privacy_configuration; + + /** + * Enable or disable privacy mode of the local device. + * + * When privacy is enabled, the system use private addresses while it scans, + * advertises or initiate a connection. The device private address is + * renewed every 15 minutes. + * + * @par Configuration + * + * The privacy feature can be configured with the help of the functions + * setPeripheralPrivacyConfiguration and setCentralPrivacyConfiguration + * which respectively set the privacy configuration of the peripheral and + * central role. + * + * @par Default configuration of peripheral role + * + * By default private resolvable addresses are used for all procedures; + * including advertisement of non connectable packets. Connection request + * from an unknown initiator with a private resolvable address triggers the + * pairing procedure. + * + * @par Default configuration of central role + * + * By default private resolvable addresses are used for all procedures; + * including active scanning. Addresses present in advertisement packet are + * resolved and advertisement packets are forwarded to the application + * even if the advertiser private address is unknown. + * + * @param[in] enable Should be set to true to enable the privacy mode and + * false to disable it. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + */ + virtual ble_error_t enablePrivacy(bool enable); + + /** + * Set the privacy configuration used by the peripheral role. + * + * @param[in] configuration The configuration to set. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + */ + virtual ble_error_t setPeripheralPrivacyConfiguration( + const PeripheralPrivacyConfiguration_t *configuration + ); + + /** + * Get the privacy configuration used by the peripheral role. + * + * @param[out] configuration The variable filled with the current + * configuration. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + */ + virtual ble_error_t getPeripheralPrivacyConfiguration( + PeripheralPrivacyConfiguration_t *configuration + ); + + /** + * Set the privacy configuration used by the central role. + * + * @param[in] configuration The configuration to set. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + */ + virtual ble_error_t setCentralPrivacyConfiguration( + const CentralPrivacyConfiguration_t *configuration + ); + + /** + * Get the privacy configuration used by the central role. + * + * @param[out] configuration The variable filled with the current + * configuration. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + */ + virtual ble_error_t getCentralPrivacyConfiguration( + CentralPrivacyConfiguration_t *configuration + ); protected: /** diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index dbeeb3a8a2..bd6c353f16 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -87,18 +87,6 @@ ble_error_t Gap::setWhitelist(const Whitelist_t &whitelist) return BLE_ERROR_NOT_IMPLEMENTED; } - - -const Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = { - /* use_non_resolvable_random_address */ false, - /* resolution_strategy */ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE -}; - -const Gap::CentralPrivacyConfiguration_t Gap::default_central_privacy_configuration = { - /* use_non_resolvable_random_address */ false, - /* resolution_strategy */ CentralPrivacyConfiguration_t::RESOLVE_AND_FORWARD -}; - void Gap::processConnectionEvent( Handle_t handle, Role_t role, diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index e6adc087b3..77dfda8ba0 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -294,5 +294,48 @@ ble_error_t Gap::setPhy( return BLE_ERROR_NOT_IMPLEMENTED; } +/* -------------------- Future deprecation ------------------------- */ + +const Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = { + /* use_non_resolvable_random_address */ false, + /* resolution_strategy */ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE +}; + +const Gap::CentralPrivacyConfiguration_t Gap::default_central_privacy_configuration = { + /* use_non_resolvable_random_address */ false, + /* resolution_strategy */ CentralPrivacyConfiguration_t::RESOLVE_AND_FORWARD +}; + +ble_error_t Gap::enablePrivacy(bool enable) +{ + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setPeripheralPrivacyConfiguration( + const PeripheralPrivacyConfiguration_t *configuration +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::getPeripheralPrivacyConfiguration( + PeripheralPrivacyConfiguration_t *configuration +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::setCentralPrivacyConfiguration( + const CentralPrivacyConfiguration_t *configuration +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + +ble_error_t Gap::getCentralPrivacyConfiguration( + CentralPrivacyConfiguration_t *configuration +) { + return BLE_ERROR_NOT_IMPLEMENTED; +} + + + } // namespace ble From 0c2efc4dd96ad5aaac7357f19b65cfac9d91235d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:38:40 +0000 Subject: [PATCH 249/361] BLE: Fix return value of GenericGap::manageConnectionParametersUpdateRequest. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 02adff4751..3884e31274 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -651,6 +651,7 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::manageConnectionParametersUpdateRequest(bool flag) { _user_manage_connection_parameter_requests = flag; + return BLE_ERROR_NONE; } ble_error_t GenericGap::updateConnectionParameters( From 86dc6d71ee61b7c8feb59c88cdbc1ec1bfe10462 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:41:02 +0000 Subject: [PATCH 250/361] BLE: Fix includes of ble/gap/AdvertisingDataBuilder.h , --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 495a6f38bb..adc0606675 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -27,6 +27,7 @@ #include "ble/blecommon.h" #include "ble/SafeEnum.h" #include "UUID.h" +#include "ble/gap/Types.h" /** * @addtogroup ble From dfa7749d8acef639d6e336d3c6b6c5247626d363 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:56:58 +0000 Subject: [PATCH 251/361] BLE: Split ble/gap/AdvertisingDataBuilder.h into declaration and implementation file. --- .../ble/gap/AdvertisingDataBuilder.h | 411 ++------------- .../source/gap/AdvertisingDataBuilder.cpp | 469 ++++++++++++++++++ 2 files changed, 498 insertions(+), 382 deletions(-) create mode 100644 features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index adc0606675..42e63fa466 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -532,10 +532,7 @@ public: * @param buffer Buffer used to store the data. * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. */ - AdvertisingDataBuilder(mbed::Span buffer) : - _buffer(buffer), - _payload_length(0) { - } + AdvertisingDataBuilder(mbed::Span buffer); /** Advertising data needs a user provided buffer to store the data. * @@ -543,19 +540,14 @@ public: * @param buffer_size Size of the buffer. * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. */ - AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size) : - _buffer(buffer, buffer_size), - _payload_length(0) { - } + AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size); /** * Get the subspan of the buffer containing valid data. * * @return A Span containing the payload. */ - mbed::Span getAdvertisingData() const { - return _buffer.first(_payload_length); - } + mbed::Span getAdvertisingData() const; /** * Add a new field into the payload. Will return an error if type is already present. @@ -573,13 +565,7 @@ public: ble_error_t addData( adv_data_type_t advDataType, mbed::Span fieldData - ) { - if (findField(advDataType)) { - return BLE_ERROR_OPERATION_NOT_PERMITTED; - } else { - return addField(advDataType, fieldData); - } - } + ); /** * Replace a new field into the payload. Will fail if type is not already present. @@ -597,15 +583,7 @@ public: ble_error_t replaceData( adv_data_type_t advDataType, mbed::Span fieldData - ) { - uint8_t* field = findField(advDataType); - - if (field) { - return replaceField(advDataType, fieldData, field); - } else { - return BLE_ERROR_NOT_FOUND; - } - } + ); /** * Append data to an existing field in the payload. Will fail if type is not already @@ -624,15 +602,7 @@ public: ble_error_t appendData( adv_data_type_t advDataType, mbed::Span fieldData - ) { - uint8_t* field = findField(advDataType); - - if (field) { - return appendToField(fieldData, field); - } else { - return BLE_ERROR_NOT_FOUND; - } - } + ); /** * Remove existing date of given type. Will return an error if type is not present. @@ -641,17 +611,7 @@ public: * * @return BLE_ERROR_NONE returned on success, BLE_ERROR_INVALID_PARAM if field doesn't exist */ - ble_error_t removeData( - adv_data_type_t advDataType - ) { - uint8_t* field = findField(advDataType); - - if (field) { - return removeField(field); - } else { - return BLE_ERROR_NOT_FOUND; - } - } + ble_error_t removeData(adv_data_type_t advDataType); /** * Adds a new field into the payload. If the supplied advertising data type is @@ -669,15 +629,7 @@ public: ble_error_t addOrReplaceData( adv_data_type_t advDataType, mbed::Span fieldData - ) { - uint8_t* field = findField(advDataType); - - if (field) { - return replaceField(advDataType, fieldData, field); - } else { - return addField(advDataType, fieldData); - } - } + ); /** * Adds a new field into the payload. If the supplied advertising data type is @@ -695,25 +647,14 @@ public: ble_error_t addOrAppendData( adv_data_type_t advDataType, mbed::Span fieldData - ) { - uint8_t* field = findField(advDataType); - - if (field) { - return appendToField(fieldData, field); - } else { - return addField(advDataType, fieldData); - } - } + ); /** * Clears the advertising data payload. * * @post getPayloadLen() returns 0. */ - void clear() { - memset(_buffer.data(), 0, _buffer.size()); - _payload_length = 0; - } + void clear(); /** * Add device appearance in the advertising payload. @@ -726,13 +667,7 @@ public: * @note This call is equivalent to calling addOrReplaceData() with * adv_data_type_t::APPEARANCE as the field type. */ - ble_error_t setAppearance( - adv_data_appearance_t appearance - ) { - uint8_t appearence_byte = appearance.value(); - mbed::Span appearance_span((const uint8_t*) &appearence_byte, 2); - return addOrReplaceData(adv_data_type_t::APPEARANCE, appearance_span); - } + ble_error_t setAppearance(adv_data_appearance_t appearance); /** * Add BLE flags in the advertising payload. @@ -748,11 +683,7 @@ public: */ ble_error_t setFlags( adv_data_flags_t flags = adv_data_flags_t::default_flags - ) { - uint8_t flags_byte = flags.value(); - mbed::Span flags_span((const uint8_t*) &flags_byte, 1); - return addOrReplaceData(adv_data_type_t::FLAGS, flags_span); - } + ); /** * Add the advertising TX in the advertising payload. @@ -765,12 +696,7 @@ public: * @note This call is equivalent to calling addOrReplaceData() with * adv_data_type_t::TX_POWER_LEVEL as the field type. */ - ble_error_t setTxPowerAdvertised( - advertising_power_t txPower - ) { - mbed::Span power_span((const uint8_t*) &txPower, 1); - return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, power_span); - } + ble_error_t setTxPowerAdvertised(advertising_power_t txPower); /** * Add device name to the advertising payload. @@ -784,18 +710,7 @@ public: * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ - ble_error_t setName( - const char* name, - bool complete = true - ) { - mbed::Span power_span((const uint8_t*)name, strlen(name)); - - if (complete) { - return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); - } else { - return addOrReplaceData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); - } - } + ble_error_t setName(const char* name, bool complete = true); /** * Add manufacturer specific data to the advertising payload. @@ -810,15 +725,7 @@ public: * data field or the data is too small (must contain * 2 bytes of manufacturer ID) */ - ble_error_t setManufacturerSpecificData( - mbed::Span data - ) { - if (data.size() < 2) { - return BLE_ERROR_INVALID_PARAM; - } - - return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); - } + ble_error_t setManufacturerSpecificData(mbed::Span data); /** * Add advertising interval to the payload. This field can only carry 2 bytes. @@ -829,18 +736,7 @@ public: * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_INVALID_PARAM if interval value outside of valid range. */ - ble_error_t setAdvertisingInterval( - adv_interval_t interval - ) { - if (interval.value() > 0xFFFF) { - return BLE_ERROR_INVALID_PARAM; - } - - return addOrReplaceData( - adv_data_type_t::ADVERTISING_INTERVAL, - mbed::make_Span((const uint8_t*)interval.storage(), 2) - ); - } + ble_error_t setAdvertisingInterval(adv_interval_t interval); /** * Add connection interval preferences to the payload @@ -854,15 +750,7 @@ public: ble_error_t setConnectionIntervalPreference( conn_interval_t min, conn_interval_t max - ) { - uint32_t interval = max.value(); - interval = interval << 16; - interval |= min.value(); - return addOrReplaceData( - adv_data_type_t::SLAVE_CONNECTION_INTERVAL_RANGE, - mbed::make_Span((const uint8_t*)&interval, 4) - ); - } + ); /** * Add service data data to the advertising payload. @@ -877,50 +765,7 @@ public: * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ - ble_error_t setServiceData( - UUID service, - mbed::Span data - ) { - if (service.getLen() + data.size() > 0xFE) { - return BLE_ERROR_INVALID_PARAM; - } - - adv_data_type_t short_type = adv_data_type_t::SERVICE_DATA_16BIT_ID; - adv_data_type_t long_type = adv_data_type_t::SERVICE_DATA_128BIT_ID; - - size_t total_size = data.size() + service.getLen() + 2; - size_t old_size = getFieldSize( - (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type - ); - - /* if we can't fit the new data do not proceed */ - if (total_size > data.size() - (_payload_length - old_size)) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* this will insert only the UUID (and remove old data) */ - ble_error_t status = setUUIDData( - mbed::make_Span(&service, 1), - short_type, - long_type - ); - - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - - status = appendData( - (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type, - data - ); - - if (status != BLE_ERROR_NONE) { - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - - return BLE_ERROR_NONE; - } + ble_error_t setServiceData(UUID service, mbed::Span data); /** * Add local service IDs to the advertising payload. If they data can't fit @@ -938,17 +783,7 @@ public: ble_error_t setLocalServiceList( mbed::Span data, bool complete = true - ) { - adv_data_type_t short_type = complete ? - adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS : - adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; - - adv_data_type_t long_type = complete ? - adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS : - adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; - - return setUUIDData(data, short_type, long_type); - } + ); /** * Add a list of UUIDs of solicited services. @@ -961,14 +796,7 @@ public: * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_INVALID_PARAM if number of UUIDs of any one type is too high. */ - ble_error_t setRequestedServiceList( - mbed::Span data - ) { - adv_data_type_t short_type = adv_data_type_t::LIST_16BIT_SOLICITATION_IDS; - adv_data_type_t long_type = adv_data_type_t::LIST_128BIT_SOLICITATION_IDS; - - return setUUIDData(data, short_type, long_type); - } + ble_error_t setRequestedServiceList(mbed::Span data); /** * Return a span of data containing the the type of data requested. @@ -981,16 +809,7 @@ public: ble_error_t getData( mbed::Span &data, adv_data_type_t advDataType - ) { - uint8_t *field = findField(advDataType); - if (field) { - uint8_t data_length = field[0] - 1 /* skip type */; - data = mbed::make_Span((const uint8_t*)(field + 2 /* skip type and length */), data_length); - return BLE_ERROR_NONE; - } else { - return BLE_ERROR_NOT_FOUND; - } - } + ); private: /** @@ -1002,22 +821,7 @@ private: * element being the length of the field followed by the value of the field. * NULL if the field is not present in the payload. */ - uint8_t* findField(adv_data_type_t type) - { - /* Scan through advertisement data */ - for (uint8_t idx = 0; idx < _payload_length; ) { - uint8_t fieldType = _buffer[idx + 1]; - - if (fieldType == type) { - return _buffer.data() + idx; - } - - /* Advance to next field */ - idx += _buffer[idx] + 1; - } - - return NULL; - } + uint8_t* findField(adv_data_type_t type); /** * Get field size (includes type and size bytes) @@ -1026,14 +830,7 @@ private: * * @return Size of the whole field including type and size bytes. */ - uint8_t getFieldSize(adv_data_type_t type) { - uint8_t *field = findField(type); - if (field) { - return field[0] + 1; - } else { - return 0; - } - } + uint8_t getFieldSize(adv_data_type_t type); /** * Append advertising data based on the specified type. @@ -1049,30 +846,7 @@ private: ble_error_t addField( adv_data_type_t advDataType, mbed::Span fieldData - ) { - if (fieldData.size() > 0xFE) { - return BLE_ERROR_INVALID_PARAM; - } - - /* Make sure we don't exceed the buffer size */ - if (_payload_length + fieldData.size() + 2 > _buffer.size()) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* Field length (includes field ID byte) */ - _buffer[_payload_length] = fieldData.size() + 1; - ++_payload_length; - - /* Field ID. */ - _buffer[_payload_length] = advDataType.value(); - ++_payload_length; - - /* Payload. */ - memcpy(&_buffer[_payload_length], fieldData.data(), fieldData.size()); - _payload_length += fieldData.size(); - - return BLE_ERROR_NONE; - } + ); /** * Append data to a field in the advertising payload. @@ -1087,41 +861,7 @@ private: ble_error_t appendToField( mbed::Span fieldData, uint8_t* field - ) { - if (fieldData.size() + field[0] > 0xFF /* field[0] already includes the type byte */) { - return BLE_ERROR_INVALID_PARAM; - } - - /* Check if data fits */ - if ((_payload_length + fieldData.size()) <= _buffer.size()) { - uint8_t old_data_length = field[0]; - - /* get the size of bytes in the payload after the field */ - size_t remainder_size = _payload_length - - (field - _buffer.data()) - /* length of all data before the field */ - (old_data_length + 1) /* length of the old field */; - - /* move data after the field to fit new data */ - if (remainder_size) { - memmove( - field + old_data_length + 1 + fieldData.size(), - field + old_data_length + 1, - remainder_size - ); - } - - /* append new data */ - memcpy(field + old_data_length + 1, fieldData.data(), fieldData.size()); - - /* Increment lengths */ - field[0] += fieldData.size(); - _payload_length += fieldData.size(); - - return BLE_ERROR_NONE; - } else { - return BLE_ERROR_BUFFER_OVERFLOW; - } - } + ); /** * Update in place the value of a field in the advertising payload. @@ -1140,30 +880,7 @@ private: adv_data_type_t advDataType, mbed::Span fieldData, uint8_t* field - ) { - if (fieldData.size() > 0xFE) { - return BLE_ERROR_INVALID_PARAM; - } - - uint8_t old_data_length = field[0] - 1; - - /* New data has same length, do in-order replacement */ - if (fieldData.size() == old_data_length) { - memcpy(field + 2, fieldData.data(), old_data_length); - - return BLE_ERROR_NONE; - } else { - /* Check if data fits */ - if ((_payload_length - old_data_length + fieldData.size()) <= _buffer.size()) { - removeField(field); - - /* Add new field */ - return addField(advDataType, fieldData); - } else { - return BLE_ERROR_BUFFER_OVERFLOW; - } - } - } + ); /** * Remove the field. @@ -1172,18 +889,7 @@ private: * * @return BLE_ERROR_NONE on success. */ - ble_error_t removeField( - uint8_t* field - ) { - /* stored length + the byte containing length */ - uint8_t old_field_length = field[0] + 1; - - memmove(field, field + old_field_length, old_field_length); - - _payload_length -= old_field_length; - - return BLE_ERROR_NONE; - } + ble_error_t removeField(uint8_t* field); /** * Add a list of UUIDs to given types. @@ -1202,68 +908,9 @@ private: mbed::Span data, adv_data_type_t shortType, adv_data_type_t longType - ) { - ble_error_t status = BLE_ERROR_NONE; + ); - /* first count all the bytes we need to store all the UUIDs */ - size_t size_long = 0; - size_t size_short = 0; - - for (size_t i = 0, end = data.size(); i < end; ++i) { - if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - size_short++; - } else { - size_long++; - } - } - - if ((size_long * 8 > 0xFE) || (size_short * 2 > 0xFE)) { - return BLE_ERROR_INVALID_PARAM; - } - - /* calculate total size including headers for types */ - size_t total_size = size_long + (!!size_long) * 2 + - size_short + (!!size_short) * 2; - - /* count all the bytes of existing data */ - size_t old_size = getFieldSize(shortType) + getFieldSize(longType); - - /* if we can't fit the new data do not proceed */ - if (total_size > data.size() - (_payload_length - old_size)) { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* otherwise wipe old data */ - removeData(shortType); - removeData(longType); - - /* and insert individual UUIDs into appropriate fields */ - for (size_t i = 0, end = data.size(); i < end; ++i) { - adv_data_type_t field_type = (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) ? shortType : longType; - - mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); - - uint8_t *field = findField(field_type); - - if (field) { - status = appendToField(span, field); - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - } else { - status = addField(field_type, span); - if (status != BLE_ERROR_NONE) { - /* we already checked for size so this must not happen */ - return BLE_ERROR_INTERNAL_STACK_FAILURE; - } - } - } - - return status; - } - -protected: +private: /** The memory backing the the data provided by the user. */ mbed::Span _buffer; diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp new file mode 100644 index 0000000000..eb64f2f449 --- /dev/null +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -0,0 +1,469 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ble/gap/AdvertisingDataBuilder.h" + +namespace ble { + +AdvertisingDataBuilder::AdvertisingDataBuilder(mbed::Span buffer) : + _buffer(buffer), + _payload_length(0) { +} + +AdvertisingDataBuilder::AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size) : + _buffer(buffer, buffer_size), + _payload_length(0) { +} + +mbed::Span AdvertisingDataBuilder::getAdvertisingData() const { + return _buffer.first(_payload_length); +} + +ble_error_t AdvertisingDataBuilder::addData( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + if (findField(advDataType)) { + return BLE_ERROR_OPERATION_NOT_PERMITTED; + } else { + return addField(advDataType, fieldData); + } +} + +ble_error_t AdvertisingDataBuilder::replaceData( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + uint8_t* field = findField(advDataType); + + if (field) { + return replaceField(advDataType, fieldData, field); + } else { + return BLE_ERROR_NOT_FOUND; + } +} + +ble_error_t AdvertisingDataBuilder::appendData( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + uint8_t* field = findField(advDataType); + + if (field) { + return appendToField(fieldData, field); + } else { + return BLE_ERROR_NOT_FOUND; + } +} + +ble_error_t AdvertisingDataBuilder::removeData( + adv_data_type_t advDataType +) { + uint8_t* field = findField(advDataType); + + if (field) { + return removeField(field); + } else { + return BLE_ERROR_NOT_FOUND; + } +} + +ble_error_t AdvertisingDataBuilder::addOrReplaceData( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + uint8_t* field = findField(advDataType); + + if (field) { + return replaceField(advDataType, fieldData, field); + } else { + return addField(advDataType, fieldData); + } +} + +ble_error_t AdvertisingDataBuilder::addOrAppendData( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + uint8_t* field = findField(advDataType); + + if (field) { + return appendToField(fieldData, field); + } else { + return addField(advDataType, fieldData); + } +} + +void AdvertisingDataBuilder::clear() { + memset(_buffer.data(), 0, _buffer.size()); + _payload_length = 0; +} + +ble_error_t AdvertisingDataBuilder::setAppearance( + adv_data_appearance_t appearance +) { + uint8_t appearence_byte = appearance.value(); + mbed::Span appearance_span((const uint8_t*) &appearence_byte, 2); + return addOrReplaceData(adv_data_type_t::APPEARANCE, appearance_span); +} + +ble_error_t AdvertisingDataBuilder::setFlags( + adv_data_flags_t flags +) { + uint8_t flags_byte = flags.value(); + mbed::Span flags_span((const uint8_t*) &flags_byte, 1); + return addOrReplaceData(adv_data_type_t::FLAGS, flags_span); +} + +ble_error_t AdvertisingDataBuilder::setTxPowerAdvertised( + advertising_power_t txPower +) { + mbed::Span power_span((const uint8_t*) &txPower, 1); + return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, power_span); +} + +ble_error_t AdvertisingDataBuilder::setName( + const char* name, + bool complete +) { + mbed::Span power_span((const uint8_t*)name, strlen(name)); + + if (complete) { + return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); + } else { + return addOrReplaceData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); + } +} + +ble_error_t AdvertisingDataBuilder::setManufacturerSpecificData( + mbed::Span data +) { + if (data.size() < 2) { + return BLE_ERROR_INVALID_PARAM; + } + + return addOrReplaceData(adv_data_type_t::MANUFACTURER_SPECIFIC_DATA, data); +} + +ble_error_t AdvertisingDataBuilder::setAdvertisingInterval( + adv_interval_t interval +) { + if (interval.value() > 0xFFFF) { + return BLE_ERROR_INVALID_PARAM; + } + + return addOrReplaceData( + adv_data_type_t::ADVERTISING_INTERVAL, + mbed::make_Span((const uint8_t*)interval.storage(), 2) + ); +} + +ble_error_t AdvertisingDataBuilder::setConnectionIntervalPreference( + conn_interval_t min, + conn_interval_t max +) { + uint32_t interval = max.value(); + interval = interval << 16; + interval |= min.value(); + return addOrReplaceData( + adv_data_type_t::SLAVE_CONNECTION_INTERVAL_RANGE, + mbed::make_Span((const uint8_t*)&interval, 4) + ); +} + +ble_error_t AdvertisingDataBuilder::setServiceData( + UUID service, + mbed::Span data +) { + if (service.getLen() + data.size() > 0xFE) { + return BLE_ERROR_INVALID_PARAM; + } + + adv_data_type_t short_type = adv_data_type_t::SERVICE_DATA_16BIT_ID; + adv_data_type_t long_type = adv_data_type_t::SERVICE_DATA_128BIT_ID; + + size_t total_size = data.size() + service.getLen() + 2; + size_t old_size = getFieldSize( + (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type + ); + + /* if we can't fit the new data do not proceed */ + if (total_size > data.size() - (_payload_length - old_size)) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* this will insert only the UUID (and remove old data) */ + ble_error_t status = setUUIDData( + mbed::make_Span(&service, 1), + short_type, + long_type + ); + + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + status = appendData( + (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type, + data + ); + + if (status != BLE_ERROR_NONE) { + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + + return BLE_ERROR_NONE; +} + +ble_error_t AdvertisingDataBuilder::setLocalServiceList( + mbed::Span data, + bool complete +) { + adv_data_type_t short_type = complete ? + adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS : + adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; + + adv_data_type_t long_type = complete ? + adv_data_type_t::COMPLETE_LIST_128BIT_SERVICE_IDS : + adv_data_type_t::INCOMPLETE_LIST_128BIT_SERVICE_IDS; + + return setUUIDData(data, short_type, long_type); +} + +ble_error_t AdvertisingDataBuilder::setRequestedServiceList( + mbed::Span data +) { + adv_data_type_t short_type = adv_data_type_t::LIST_16BIT_SOLICITATION_IDS; + adv_data_type_t long_type = adv_data_type_t::LIST_128BIT_SOLICITATION_IDS; + + return setUUIDData(data, short_type, long_type); +} + +ble_error_t AdvertisingDataBuilder::getData( + mbed::Span &data, + adv_data_type_t advDataType +) { + uint8_t *field = findField(advDataType); + if (field) { + uint8_t data_length = field[0] - 1 /* skip type */; + data = mbed::make_Span((const uint8_t*)(field + 2 /* skip type and length */), data_length); + return BLE_ERROR_NONE; + } else { + return BLE_ERROR_NOT_FOUND; + } +} + +uint8_t* AdvertisingDataBuilder::findField(adv_data_type_t type) +{ + /* Scan through advertisement data */ + for (uint8_t idx = 0; idx < _payload_length; ) { + uint8_t fieldType = _buffer[idx + 1]; + + if (fieldType == type) { + return _buffer.data() + idx; + } + + /* Advance to next field */ + idx += _buffer[idx] + 1; + } + + return NULL; +} + +uint8_t AdvertisingDataBuilder::getFieldSize(adv_data_type_t type) { + uint8_t *field = findField(type); + if (field) { + return field[0] + 1; + } else { + return 0; + } +} + +ble_error_t AdvertisingDataBuilder::addField( + adv_data_type_t advDataType, + mbed::Span fieldData +) { + if (fieldData.size() > 0xFE) { + return BLE_ERROR_INVALID_PARAM; + } + + /* Make sure we don't exceed the buffer size */ + if (_payload_length + fieldData.size() + 2 > _buffer.size()) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* Field length (includes field ID byte) */ + _buffer[_payload_length] = fieldData.size() + 1; + ++_payload_length; + + /* Field ID. */ + _buffer[_payload_length] = advDataType.value(); + ++_payload_length; + + /* Payload. */ + memcpy(&_buffer[_payload_length], fieldData.data(), fieldData.size()); + _payload_length += fieldData.size(); + + return BLE_ERROR_NONE; +} + +ble_error_t AdvertisingDataBuilder::appendToField( + mbed::Span fieldData, + uint8_t* field +) { + if (fieldData.size() + field[0] > 0xFF /* field[0] already includes the type byte */) { + return BLE_ERROR_INVALID_PARAM; + } + + /* Check if data fits */ + if ((_payload_length + fieldData.size()) <= _buffer.size()) { + uint8_t old_data_length = field[0]; + + /* get the size of bytes in the payload after the field */ + size_t remainder_size = _payload_length - + (field - _buffer.data()) - /* length of all data before the field */ + (old_data_length + 1) /* length of the old field */; + + /* move data after the field to fit new data */ + if (remainder_size) { + memmove( + field + old_data_length + 1 + fieldData.size(), + field + old_data_length + 1, + remainder_size + ); + } + + /* append new data */ + memcpy(field + old_data_length + 1, fieldData.data(), fieldData.size()); + + /* Increment lengths */ + field[0] += fieldData.size(); + _payload_length += fieldData.size(); + + return BLE_ERROR_NONE; + } else { + return BLE_ERROR_BUFFER_OVERFLOW; + } +} + +ble_error_t AdvertisingDataBuilder::replaceField( + adv_data_type_t advDataType, + mbed::Span fieldData, + uint8_t* field +) { + if (fieldData.size() > 0xFE) { + return BLE_ERROR_INVALID_PARAM; + } + + uint8_t old_data_length = field[0] - 1; + + /* New data has same length, do in-order replacement */ + if (fieldData.size() == old_data_length) { + memcpy(field + 2, fieldData.data(), old_data_length); + + return BLE_ERROR_NONE; + } else { + /* Check if data fits */ + if ((_payload_length - old_data_length + fieldData.size()) <= _buffer.size()) { + removeField(field); + + /* Add new field */ + return addField(advDataType, fieldData); + } else { + return BLE_ERROR_BUFFER_OVERFLOW; + } + } +} + +ble_error_t AdvertisingDataBuilder::removeField(uint8_t* field) +{ + /* stored length + the byte containing length */ + uint8_t old_field_length = field[0] + 1; + + memmove(field, field + old_field_length, old_field_length); + + _payload_length -= old_field_length; + + return BLE_ERROR_NONE; +} + +ble_error_t AdvertisingDataBuilder::setUUIDData( + mbed::Span data, + adv_data_type_t shortType, + adv_data_type_t longType +) { + ble_error_t status = BLE_ERROR_NONE; + + /* first count all the bytes we need to store all the UUIDs */ + size_t size_long = 0; + size_t size_short = 0; + + for (size_t i = 0, end = data.size(); i < end; ++i) { + if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { + size_short++; + } else { + size_long++; + } + } + + if ((size_long * 8 > 0xFE) || (size_short * 2 > 0xFE)) { + return BLE_ERROR_INVALID_PARAM; + } + + /* calculate total size including headers for types */ + size_t total_size = size_long + (!!size_long) * 2 + + size_short + (!!size_short) * 2; + + /* count all the bytes of existing data */ + size_t old_size = getFieldSize(shortType) + getFieldSize(longType); + + /* if we can't fit the new data do not proceed */ + if (total_size > data.size() - (_payload_length - old_size)) { + return BLE_ERROR_BUFFER_OVERFLOW; + } + + /* otherwise wipe old data */ + removeData(shortType); + removeData(longType); + + /* and insert individual UUIDs into appropriate fields */ + for (size_t i = 0, end = data.size(); i < end; ++i) { + adv_data_type_t field_type = (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) ? shortType : longType; + + mbed::Span span(data[i].getBaseUUID(), data[i].getLen()); + + uint8_t *field = findField(field_type); + + if (field) { + status = appendToField(span, field); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } else { + status = addField(field_type, span); + if (status != BLE_ERROR_NONE) { + /* we already checked for size so this must not happen */ + return BLE_ERROR_INTERNAL_STACK_FAILURE; + } + } + } + + return status; +} + +} // end of namespace ble \ No newline at end of file From 87f36450f5c0947c397a6e318f37e4251399fd6d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 20 Nov 2018 18:58:52 +0000 Subject: [PATCH 252/361] BLE: return immutable buffer from AdvertisingDataBuilder::getAdvertisingData --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 2 +- features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 42e63fa466..80901cdecb 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -547,7 +547,7 @@ public: * * @return A Span containing the payload. */ - mbed::Span getAdvertisingData() const; + mbed::Span getAdvertisingData() const; /** * Add a new field into the payload. Will return an error if type is already present. diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp index eb64f2f449..4b8e86e1b4 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -28,7 +28,7 @@ AdvertisingDataBuilder::AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_si _payload_length(0) { } -mbed::Span AdvertisingDataBuilder::getAdvertisingData() const { +mbed::Span AdvertisingDataBuilder::getAdvertisingData() const { return _buffer.first(_payload_length); } From e49b5230cc2714c9d4561ce0d4c76e4c65c4883f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 08:57:13 +0000 Subject: [PATCH 253/361] fix missing index --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index d69122e4f3..6374067383 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -318,7 +318,7 @@ private: uint16_t minEventLength = _minEventLength[LE_2M_INDEX]; uint16_t maxEventLength = _maxEventLength[LE_2M_INDEX]; - _scanInterval[LE_2M_INDEX] = _scanInterval[phy_t::LE_CODED]; + _scanInterval[LE_2M_INDEX] = _scanInterval[LE_CODED_INDEX]; _scanWindow[LE_2M_INDEX] = _scanWindow[LE_CODED_INDEX]; _minConnectionInterval[LE_2M_INDEX] = _minConnectionInterval[LE_CODED_INDEX]; _maxConnectionInterval[LE_2M_INDEX] = _maxConnectionInterval[LE_CODED_INDEX]; From 1bf5826cdce084456c4a746944cd676d2b1a2f04 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 08:57:42 +0000 Subject: [PATCH 254/361] pull in more inherited overloads --- features/FEATURE_BLE/ble/Gap.h | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index f357e09ac2..ea2c486f18 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -267,6 +267,7 @@ public: using ble::Gap::setAdvertisingScanResponse; using ble::Gap::startAdvertising; using ble::Gap::stopAdvertising; + using ble::Gap::connect; /** * Address-type for BLEProtocol addresses. From ed105430930f8a29a7dc0bebe0c1ac87473339cc Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 09:00:59 +0000 Subject: [PATCH 255/361] missing virtual --- features/FEATURE_BLE/ble/gap/Gap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 220fc0822b..4c0d719707 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -52,7 +52,7 @@ public: * * @param event Advertising report @see AdvertisingReportEvent_t for details. */ - void onAdvertisingReport(const AdvertisingReportEvent &event) { } + virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { } /** Called when scan times out. */ From b293426a81716217d7378c6bf49e5b0143d01890 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 09:04:04 +0000 Subject: [PATCH 256/361] missing overloads --- features/FEATURE_BLE/ble/Gap.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index ea2c486f18..84a89a4022 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -268,6 +268,8 @@ public: using ble::Gap::startAdvertising; using ble::Gap::stopAdvertising; using ble::Gap::connect; + using ble::Gap::disconnect; + using ble::Gap::startScan; /** * Address-type for BLEProtocol addresses. From e9c0f587af161e44dc303dcd9d697ff6c4e0a89b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 09:17:47 +0000 Subject: [PATCH 257/361] fix constness to match recent const changes --- features/FEATURE_BLE/ble/gap/Gap.h | 8 ++--- features/FEATURE_BLE/ble/generic/GenericGap.h | 34 +++++++++---------- features/FEATURE_BLE/source/gap/Gap.cpp | 6 ++-- .../FEATURE_BLE/source/generic/GenericGap.cpp | 12 +++---- 4 files changed, 30 insertions(+), 30 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 4c0d719707..2ff90d6843 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -52,7 +52,7 @@ public: * * @param event Advertising report @see AdvertisingReportEvent_t for details. */ - virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { } + void onAdvertisingReport(const AdvertisingReportEvent &event) { } /** Called when scan times out. */ @@ -229,7 +229,7 @@ public: */ virtual ble_error_t setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation = false ); @@ -243,7 +243,7 @@ public: */ virtual ble_error_t setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, + mbed::Span response, bool minimiseFragmentation = false ); @@ -298,7 +298,7 @@ public: */ virtual ble_error_t setPeriodicAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload + mbed::Span payload ); /** Start periodic advertising for a given set. Periodic advertising will not start until diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 0b70b4484f..ecd38e24c0 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -78,55 +78,55 @@ public: /** @copydoc Gap::IsFeatureSupported */ - bool isFeatureSupported( + virtual bool isFeatureSupported( controller_supported_features_t feature ); /** @copydoc Gap::getMaxAdvertisingSetNumber */ - uint8_t getMaxAdvertisingSetNumber(); + virtual uint8_t getMaxAdvertisingSetNumber(); /** @copydoc Gap::getMaxAdvertisingDataLength */ - uint8_t getMaxAdvertisingDataLength(); + virtual uint8_t getMaxAdvertisingDataLength(); /** @copydoc Gap::createAdvertisingSet */ - ble_error_t createAdvertisingSet( + virtual ble_error_t createAdvertisingSet( advertising_handle_t *handle, const AdvertisingParameters ¶meters ); /** @copydoc Gap::destroyAdvertisingSet */ - ble_error_t destroyAdvertisingSet(advertising_handle_t handle); + virtual ble_error_t destroyAdvertisingSet(advertising_handle_t handle); /** @copydoc Gap::setAdvertisingParams */ - ble_error_t setAdvertisingParameters( + virtual ble_error_t setAdvertisingParameters( advertising_handle_t handle, const AdvertisingParameters ¶ms ); /** @copydoc Gap::setAdvertisingPayload */ - ble_error_t setAdvertisingPayload( + virtual ble_error_t setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation ); /** @copydoc Gap::setAdvertisingScanResponse */ - ble_error_t setAdvertisingScanResponse( + virtual ble_error_t setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, + mbed::Span response, bool minimiseFragmentation ); /** @copydoc Gap::startAdvertising */ - ble_error_t startAdvertising( + virtual ble_error_t startAdvertising( advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents @@ -134,11 +134,11 @@ public: /** @copydoc Gap::stopAdvertising */ - ble_error_t stopAdvertising(advertising_handle_t handle); + virtual ble_error_t stopAdvertising(advertising_handle_t handle); /** @copydoc Gap::isAdvertisingActive */ - bool isAdvertisingActive(advertising_handle_t handle); + virtual bool isAdvertisingActive(advertising_handle_t handle); /** @copydoc Gap::setPeriodicAdvertisingParameters */ @@ -153,7 +153,7 @@ public: */ virtual ble_error_t setPeriodicAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload + mbed::Span payload ); /** @copydoc Gap::startPeriodicAdvertising @@ -529,7 +529,7 @@ public: /** * @copydoc ::Gap::processConnectionEvent */ - void processConnectionEvent( + virtual void processConnectionEvent( Handle_t handle, Role_t role, peer_address_type_t peerAddrType, @@ -544,7 +544,7 @@ public: /** * @copydoc ::Gap::processDisconnectionEvent */ - void processDisconnectionEvent( + virtual void processDisconnectionEvent( Handle_t handle, DisconnectionReason_t reason ); @@ -552,7 +552,7 @@ public: private: ble_error_t setAdvertisingData( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation, bool scan_response ); diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 77dfda8ba0..7b685f4545 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -60,7 +60,7 @@ ble_error_t Gap::setAdvertisingParameters( ble_error_t Gap::setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation ) { /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -69,7 +69,7 @@ ble_error_t Gap::setAdvertisingPayload( ble_error_t Gap::setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, + mbed::Span response, bool minimiseFragmentation ) { /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -107,7 +107,7 @@ ble_error_t Gap::setPeriodicAdvertisingParameters( ble_error_t Gap::setPeriodicAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload + mbed::Span payload ) { /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3884e31274..46759fc287 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1907,7 +1907,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( ble_error_t GenericGap::setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation ) { return setAdvertisingData(handle, payload, minimiseFragmentation, false); @@ -1915,7 +1915,7 @@ ble_error_t GenericGap::setAdvertisingPayload( ble_error_t GenericGap::setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, + mbed::Span response, bool minimiseFragmentation ) { return setAdvertisingData(handle, response, minimiseFragmentation, true); @@ -1923,7 +1923,7 @@ ble_error_t GenericGap::setAdvertisingScanResponse( ble_error_t GenericGap::setAdvertisingData( advertising_handle_t handle, - mbed::Span payload, + mbed::Span payload, bool minimiseFragmentation, bool scan_response ) { @@ -1995,7 +1995,7 @@ ble_error_t GenericGap::setAdvertisingData( } // extract the payload - mbed::Span sub_payload = payload.subspan( + mbed::Span sub_payload = payload.subspan( i, std::min(MAX_HCI_DATA_LENGTH, (end - i)) ); @@ -2153,7 +2153,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( ble_error_t GenericGap::setPeriodicAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload + mbed::Span payload ) { if (handle == LEGACY_ADVERTISING_HANDLE) { @@ -2189,7 +2189,7 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( } // extract the payload - mbed::Span sub_payload = payload.subspan( + mbed::Span sub_payload = payload.subspan( i, std::min(MAX_HCI_DATA_LENGTH, (end - i)) ); From 80db38c60a4cecd488aad381117b7e8314444b9b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 09:59:08 +0000 Subject: [PATCH 258/361] BLE: Cleanup bounded and document it. --- features/FEATURE_BLE/ble/common/Bounded.h | 72 +++++++++++++++++-- .../ble/gap/ConnectionParameters.h | 2 +- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Bounded.h b/features/FEATURE_BLE/ble/common/Bounded.h index 192c2387eb..ce076f8bf2 100644 --- a/features/FEATURE_BLE/ble/common/Bounded.h +++ b/features/FEATURE_BLE/ble/common/Bounded.h @@ -21,9 +21,29 @@ namespace ble { -template +/** + * Restrict values of an integer type to a defined range. + * + * The range is a closed interval that includes its left-bound (Min) and + * right-bound value (Max). + * + * @tparam Rep The C++ integer type used to represent the values. + * @tparam Min Minimum value allowed. + * @tparam Max maximum value allowed. + */ +template struct Bounded { - Bounded(T v) : _value(v) { + /** + * Construct a bounded integer. + * + * If v is out of the range [Min : Max] then if it is less than Min the + * value of the bounded integer will be Min and if it greater than Max then + * the value of the bounded integer will be Max. + * + * @param v The value to store. + */ + Bounded(Rep v) : _value(v) + { if (v < Min) { _value = v; } else if (v > Max) { @@ -31,17 +51,57 @@ struct Bounded { } } - T value() const { + /** + * Access the inner value. + * + * @return The current value. + */ + Rep value() const { return _value; } - static const T min = Min; - static const T max = Max; + /** + * The left-bound value. + * + * @return The lowest value that can be represented by this type + */ + static Rep min() + { + return Min; + } + + /** + * The right-bound value. + * + * @return The highest value that can be represented by this type + */ + static Rep max() + { + return Max; + } + + /** + * The left-bound value. + */ + static const Rep MIN; + + /** + * The right-bound value. + */ + static const Rep MAX; private: - T _value; + Rep _value; }; +/* ---------------------- Static variable initialization -------------------- */ + +template +const T Bounded::MIN = Min; + +template +const T Bounded::MAX = Max; + } // namespace ble #endif //BLE_COMMON_BOUNDED_H_ diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 6374067383..f63578b980 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -41,7 +41,7 @@ public: scan_window_t scanWindow = scan_window_t::min(), conn_interval_t minConnectionInterval = conn_interval_t::min(), conn_interval_t maxConnectionInterval = conn_interval_t::max(), - slave_latency_t slaveLatency = slave_latency_t::min, + slave_latency_t slaveLatency = slave_latency_t::min(), supervision_timeout_t connectionSupervisionTimeout = supervision_timeout_t::max(), phy_t phy = phy_t::LE_1M, conn_event_length_t minEventLength = conn_event_length_t::min(), From 7fb863eeb4041dc7bbde04566abd8256c468e91b Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 11:14:43 +0000 Subject: [PATCH 259/361] missing virtual --- features/FEATURE_BLE/ble/gap/Gap.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 2ff90d6843..7236979b98 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -52,7 +52,7 @@ public: * * @param event Advertising report @see AdvertisingReportEvent_t for details. */ - void onAdvertisingReport(const AdvertisingReportEvent &event) { } + virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { } /** Called when scan times out. */ From 7b0cb27427b88e432c8bbf55573bcc3cc6a3e8ea Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 11:27:04 +0000 Subject: [PATCH 260/361] added type conversion for connection params --- features/FEATURE_BLE/ble/BLETypes.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 47936d699a..4e956fda21 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -611,6 +611,14 @@ struct peer_address_type_t :SafeEnum { ANONYMOUS = 0xFF }; + ble::target_peer_address_type_t getTargetAddressType() const { + if (value() == RANDOM || value() == RANDOM_STATIC_IDENTITY) { + return ble::target_peer_address_type_t::RANDOM; + } + + return ble::target_peer_address_type_t::PUBLIC; + } + /** * Construct a new instance of peer_address_type_t. */ From 07c05917e0baab4f16ac7294dae66adc0e5926cf Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 10:22:21 +0000 Subject: [PATCH 261/361] BLE: Add Duration::forever() function. --- features/FEATURE_BLE/ble/common/Duration.h | 23 +++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index f37a03025e..a9082c894c 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -49,8 +49,18 @@ struct DefaultRange { typedef Range<0, 0xFFFFFFFF> type; }; +template +struct Forever { + static const uint32_t VALUE = V; +}; -template::type > + +template< + typename Rep, + uint32_t TB, + typename Range = typename DefaultRange::type, + typename Forever = void* +> struct Duration { Duration() : duration() { } @@ -93,6 +103,11 @@ struct Duration { return &duration; } + static Duration forever() + { + return Duration(Forever::VALUE); + } + private: static Rep clamp(Rep in) { if (in < MIN) { @@ -211,6 +226,12 @@ bool operator>(Duration lhs, Duration rhs) { return rhs < lhs; } +/* ---------------------- Static variable initialization -------------------- */ + + +template +const uint32_t Forever::VALUE; + } #endif //BLE_COMMON_DURATION_H_ From 49f5c7f833b0f646afcceb314ec6a847092c6972 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 11:11:01 +0000 Subject: [PATCH 262/361] BLE: Fix Bounded constant declaration. --- features/FEATURE_BLE/ble/common/Bounded.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Bounded.h b/features/FEATURE_BLE/ble/common/Bounded.h index ce076f8bf2..ea3041ab8e 100644 --- a/features/FEATURE_BLE/ble/common/Bounded.h +++ b/features/FEATURE_BLE/ble/common/Bounded.h @@ -83,12 +83,12 @@ struct Bounded { /** * The left-bound value. */ - static const Rep MIN; + static const Rep MIN = Min; /** * The right-bound value. */ - static const Rep MAX; + static const Rep MAX = Max; private: Rep _value; @@ -97,10 +97,10 @@ private: /* ---------------------- Static variable initialization -------------------- */ template -const T Bounded::MIN = Min; +const T Bounded::MIN; template -const T Bounded::MAX = Max; +const T Bounded::MAX; } // namespace ble From 62674e58e64ae2e14c05a029a0d008d1fdaefa1f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 11:13:14 +0000 Subject: [PATCH 263/361] BLE: Handle forever value in ble::Duration operators. --- features/FEATURE_BLE/ble/common/Duration.h | 112 ++++++++++++++------- 1 file changed, 77 insertions(+), 35 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index a9082c894c..5057fa7ee4 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -126,50 +126,68 @@ typedef Duration microsecond_t; typedef Duration millisecond_t; typedef Duration second_t; -template -DurationOut durationCast(Duration duration) { +template +DurationOut durationCast(Duration duration) { return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); } // ADDITION OPERATOR -template -microsecond_t operator+(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS> +microsecond_t operator+( + Duration lhs, + Duration rhs +) +{ return microsecond_t((lhs.value() * lhs.TIME_BASE) + (rhs.value() * rhs.TIME_BASE)); } -template -Duration operator+(Duration lhs, Duration rhs) { - return Duration(lhs.value() + rhs.value()); +template +Duration operator+( + Duration lhs, + Duration rhs +) { + return Duration(lhs.value() + rhs.value()); } // MULTIPLICATION OPERATOR -template -Duration operator*(Duration lhs, uint32_t rhs) { - return Duration(lhs.value() * rhs); +template +Duration operator*(Duration lhs, uint32_t rhs) { + return Duration(lhs.value() * rhs); } -template -Duration operator*(uint32_t lhs, Duration rhs) { - return Duration(lhs * rhs.value()); +template +Duration operator*(uint32_t lhs, Duration rhs) { + return Duration(lhs * rhs.value()); } // LESS THAN -template -bool operator<(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator<(Duration lhs, Duration rhs) { return lhs.value() * lhs.TIME_BASE < rhs.value() * rhs.TIME_BASE; } -template -bool operator<(Duration lhs, Duration rhs) { +template +bool operator<(Duration lhs, Duration rhs) { return lhs.value() < rhs.value(); } // LESS OR EQUAL TO -template -bool operator<=(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator<=( + Duration lhs, + Duration rhs +) { return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; } @@ -180,49 +198,73 @@ bool operator<=(Duration lhs, Duration rhs) { // EQUAL -template -bool operator==(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator==( + Duration lhs, + Duration rhs +) { return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; } -template -bool operator==(Duration lhs, Duration rhs) { +template +bool operator==(Duration lhs, Duration rhs) { return lhs.value() == rhs.value(); } // NOT EQUAL -template -bool operator!=(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator!=( + Duration lhs, + Duration rhs +) { return !(lhs == rhs); } -template -bool operator!=(Duration lhs, Duration rhs) { +template +bool operator!=(Duration lhs, Duration rhs) { return !(lhs == rhs); } // GREATER OR EQUAL -template -bool operator>=(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator>=( + Duration lhs, + Duration rhs +) { return rhs <= lhs; } -template -bool operator>=(Duration lhs, Duration rhs) { +template +bool operator>=(Duration lhs, Duration rhs) { return rhs <= lhs; } // GREATER THAN -template -bool operator>(Duration lhs, Duration rhs) { +template< + typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, + typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS +> +bool operator>( + Duration lhs, + Duration rhs +) { return rhs < lhs; } -template -bool operator>(Duration lhs, Duration rhs) { +template +bool operator>(Duration lhs, Duration rhs) { return rhs < lhs; } From e602a5f06c943808626a74ce2dbf87c80b8f7a68 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 11:13:51 +0000 Subject: [PATCH 264/361] BLE: Improve static constant of Range and Duration. --- features/FEATURE_BLE/ble/common/Duration.h | 28 +++++++++++++++------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 5057fa7ee4..2c1ff70f38 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -25,10 +25,8 @@ namespace ble { template struct Range { - enum { - MIN = Min, - MAX = Max - }; + static const uint32_t MIN = Min; + static const uint32_t MAX = Max; }; template @@ -82,11 +80,9 @@ struct Duration { return duration; } - enum { - TIME_BASE = TB, - MIN = Range::MIN, - MAX = Range::MAX - }; + static const uint32_t TIME_BASE = TB; + static const Rep MIN = Range::MIN; + static const Rep MAX = Range::MAX; static Duration min() { @@ -270,10 +266,24 @@ bool operator>(Duration lhs, Duration rhs) /* ---------------------- Static variable initialization -------------------- */ +template +const uint32_t Range::MIN; + +template +const uint32_t Range::MAX; template const uint32_t Forever::VALUE; +template +const uint32_t Duration::TIME_BASE; + +template +const Rep Duration::MIN; + +template +const Rep Duration::MAX; + } #endif //BLE_COMMON_DURATION_H_ From ba931f1d4cde85dfda2b4ea84ec9f02ba3742c2d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 11:52:13 +0000 Subject: [PATCH 265/361] BLE: Document ble::Duration and satelite classes. --- features/FEATURE_BLE/ble/common/Duration.h | 250 +++++++++++++++++++-- 1 file changed, 229 insertions(+), 21 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 2c1ff70f38..9fd4063410 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -23,36 +23,69 @@ namespace ble { +/** + * Define a compile time range. + * @tparam Min left-bound + * @tparam Max right-bound + */ template struct Range { static const uint32_t MIN = Min; static const uint32_t MAX = Max; }; +/** + * Deduce default range for C++ basic integer types. + * + * + * @tparam Rep The C++ integer type. + */ template struct DefaultRange; +/** + * DefaultRange specialization for uint8_t. + */ template<> struct DefaultRange { typedef Range<0, 0xFF> type; }; +/** + * DefaultRange specialization for uint16_t. + */ template<> struct DefaultRange { typedef Range<0, 0xFFFF> type; }; +/** + * DefaultRange specialization for uint32_t + */ template<> struct DefaultRange { typedef Range<0, 0xFFFFFFFF> type; }; +/** + * Represent the forever value that can be used in Duration. + * + * @tparam V The integer value representing a never ending duration. + */ template struct Forever { static const uint32_t VALUE = V; }; - +/** + * Model BLE durations. + * + * @tparam Rep The representation type of the duration. + * @tparam TB The time base in us. + * @tparam Range Closed interval of the duration + * @tparam Forever The special value (if applicable) that represents a forever + * duration. + */ template< typename Rep, uint32_t TB, @@ -60,45 +93,113 @@ template< typename Forever = void* > struct Duration { - Duration() : duration() { } + /** + * Construct a default Duration. + * + * It is initialized with the minimum value acceptable. + */ + Duration() : duration(Range::MIN) { } + /** + * Construct a Duration from an integer value. + * + * @param v The value of the duration in TN units. + */ explicit Duration(Rep v) : duration(clamp(v)) { } - template - Duration(Duration other) : + /** + * Construct a Duration from another Duration. + * + * @note The operation fail at compile time of there is a loss of precision. + * + * @tparam OtherRep The type used to represent the other duration. + * @tparam OtherTB The time base in us units of the other duration. + * @tparam OtherRange The range of the other duration. + * @tparam OtherF The forever value of the other type. + * + * @param other The duration used to construct this object. + */ + template + Duration(Duration other) : duration(clamp(other.value() * (OtherTB / TB))) { MBED_STATIC_ASSERT(OtherTB >= TB && (OtherTB % TB) == 0, "Incompatible units"); } - template - explicit Duration(Duration other_ms, void* = NULL) : + /** + * Construct a new Duration from a Duration in milliseconds. + * + * @note The result of the conversion is rounded up. + * + * @tparam OtherRep The representation type used by other_ms. + * @tparam OtherRange The range used by other_ms. + * @tparam OtherF The forever value used by other_ms. + * + * @param other_ms The duration in ms to convert. + */ + template + explicit Duration(Duration other_ms, void* = NULL) : duration(clamp(((other_ms.value() * 1000) + TB - 1) / TB)) { } + /** + * Return the duration in TB units. + * + * @return The duration in TB units. + */ Rep value() { return duration; } + /** + * The time base. + */ static const uint32_t TIME_BASE = TB; + + /** + * Left-bound of the Duration range. + */ static const Rep MIN = Range::MIN; + + /** + * Right bound of the duration range. + */ static const Rep MAX = Range::MAX; + /** + * Return the minimum duration. + * + * @return The minimum duration. + */ static Duration min() { return Duration(MIN); } + /** + * Return the maximum duration. + * + * @return The maximum duration. + */ static Duration max() { return Duration(MAX); } + /** + * Return a pointer to the value of the duration. + * + * @return a pointer to the value of the duration. + */ const Rep* storage() const { return &duration; } + /** + * Return the duration value meaning forever. + * @return the duration value meaning forever. + */ static Duration forever() { return Duration(Forever::VALUE); @@ -118,16 +219,43 @@ private: Rep duration; }; +/** + * Type that represents micro seconds. + */ typedef Duration microsecond_t; + +/** + * Type that represents milliseconds. + */ typedef Duration millisecond_t; + +/** + * Type that represents seconds. + */ typedef Duration second_t; +/** + * Cast a duration to another. + * + * @tparam DurationOut Type of the Duration in output. + * @tparam RepIn The representation type of duration. + * @tparam TBIn The timebase of duration. + * @tparam RangeIn The range of duration. + * @tparam FIn The Forever value of duration. + * @param duration The duration to convert. + * @return The converted duration. It is rounded up if precision is loss. + */ template DurationOut durationCast(Duration duration) { return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); } -// ADDITION OPERATOR +/** + * Add two durations together and return the result in microseconds. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return The result of the addition of the two durations in microseconds. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS> @@ -139,6 +267,12 @@ microsecond_t operator+( return microsecond_t((lhs.value() * lhs.TIME_BASE) + (rhs.value() * rhs.TIME_BASE)); } +/** + * Add two durations together. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return The addition of the two durations in input. + */ template Duration operator+( Duration lhs, @@ -147,20 +281,38 @@ Duration operator+( return Duration(lhs.value() + rhs.value()); } -// MULTIPLICATION OPERATOR - +/** + * Multiply a duration and a positive integer. + * + * @param lhs The duration. + * @param rhs The integer. + * + * @return A duration that represents the multiplication of lhs with rhs. + */ template Duration operator*(Duration lhs, uint32_t rhs) { return Duration(lhs.value() * rhs); } +/** + * Multiply a duration and a positive integer. + * + * @param lhs The integer. + * @param rhs The multiplication. + * + * @return A duration that represents the multiplication of lhs with rhs. + */ template Duration operator*(uint32_t lhs, Duration rhs) { return Duration(lhs * rhs.value()); } -// LESS THAN - +/** + * Indicate if the duration lhs is less than the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is less than rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -169,13 +321,23 @@ bool operator<(Duration lhs, Duration bool operator<(Duration lhs, Duration rhs) { return lhs.value() < rhs.value(); } -// LESS OR EQUAL TO - +/** + * Indicate if the duration lhs is less than or equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is less than or equal to rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -187,13 +349,23 @@ bool operator<=( return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; } +/** + * Indicate if the duration lhs is less than or equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is less than or equal to rhs and false otherwise. + */ template bool operator<=(Duration lhs, Duration rhs) { return lhs.value() <= rhs.value(); } -// EQUAL - +/** + * Indicate if the duration lhs is equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is equal to rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -205,13 +377,23 @@ bool operator==( return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; } +/** + * Indicate if the duration lhs is equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is equal to rhs and false otherwise. + */ template bool operator==(Duration lhs, Duration rhs) { return lhs.value() == rhs.value(); } -// NOT EQUAL - +/** + * Indicate if the duration lhs is not equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is not equal to rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -223,13 +405,23 @@ bool operator!=( return !(lhs == rhs); } +/** + * Indicate if the duration lhs is not equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is not equal to rhs and false otherwise. + */ template bool operator!=(Duration lhs, Duration rhs) { return !(lhs == rhs); } -// GREATER OR EQUAL - +/** + * Indicate if the duration lhs greater or equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is greater or equal to rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -241,13 +433,23 @@ bool operator>=( return rhs <= lhs; } +/** + * Indicate if the duration lhs greater or equal to the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is greater or equal to rhs and false otherwise. + */ template bool operator>=(Duration lhs, Duration rhs) { return rhs <= lhs; } -// GREATER THAN - +/** + * Indicate if the duration lhs greater than the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is greater than rhs and false otherwise. + */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS @@ -259,6 +461,12 @@ bool operator>( return rhs < lhs; } +/** + * Indicate if the duration lhs greater than the duration rhs. + * @param lhs Left hand side operand. + * @param rhs Right hand side operand. + * @return true if lhs is greater than rhs and false otherwise. + */ template bool operator>(Duration lhs, Duration rhs) { return rhs < lhs; From 02cf9ea94d945d12e7bf1456351273bb58e16cbd Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Wed, 21 Nov 2018 12:23:11 +0000 Subject: [PATCH 266/361] moved some funcs to cpp, moved cpp to source folder --- .../ble/gap/ConnectionParameters.h | 88 +----------- .../gap/AdvertisingParameters.cpp | 0 .../source/gap/ConnectionParameters.cpp | 132 ++++++++++++++++++ 3 files changed, 137 insertions(+), 83 deletions(-) rename features/FEATURE_BLE/{ble => source}/gap/AdvertisingParameters.cpp (100%) create mode 100644 features/FEATURE_BLE/source/gap/ConnectionParameters.cpp diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index f63578b980..15ef1f0fb8 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -46,29 +46,7 @@ public: phy_t phy = phy_t::LE_1M, conn_event_length_t minEventLength = conn_event_length_t::min(), conn_event_length_t maxEventLength = conn_event_length_t::max() - ) : - _filterPolicy(initiator_filter_policy_t::NO_FILTER), - _ownAddressType(own_address_type_t::PUBLIC) - { - for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { - _enabledPhy[i] = false; - } - if (phy != phy_t::NONE) { - uint8_t phy_index = phyToIndex(phy); - - if (phy_index < MAX_PARAM_PHYS) { - _scanInterval[phy_index] = scanInterval.value(); - _scanWindow[phy_index] = scanWindow.value(); - _minConnectionInterval[phy_index] = minConnectionInterval.value(); - _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); - _slaveLatency[phy_index] = slaveLatency.value(); - _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); - _enabledPhy[phy_index] = true; - _minEventLength[phy_index] = minEventLength.value(); - _maxEventLength[phy_index] = maxEventLength.value(); - } - } - }; + ); /* setters */ @@ -76,16 +54,7 @@ public: scan_interval_t scanInterval, scan_window_t scanWindow, phy_t phy = phy_t::LE_1M - ) { - uint8_t phy_index = handlePhyToggle(phy, true); - - if (phy_index < MAX_PARAM_PHYS) { - _scanInterval[phy_index] = scanInterval.value(); - _scanWindow[phy_index] = scanWindow.value(); - } - - return *this; - } + ); ConnectionParameters &setConnectionParameters( conn_interval_t minConnectionInterval, @@ -95,26 +64,7 @@ public: phy_t phy = phy_t::LE_1M, conn_event_length_t minEventLength = conn_event_length_t::min(), conn_event_length_t maxEventLength = conn_event_length_t::max() - ) { - uint8_t phy_index = handlePhyToggle(phy, true); - - if (phy_index < MAX_PARAM_PHYS) { - _minConnectionInterval[phy_index] = minConnectionInterval.value(); - _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); - _slaveLatency[phy_index] = slaveLatency.value(); - _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); - - /* avoid overflows and truncation */ - if (minEventLength.value() > maxEventLength.value()) { - minEventLength = maxEventLength; - } - - _minEventLength[phy_index] = minEventLength.value(); - _maxEventLength[phy_index] = maxEventLength.value(); - } - - return *this; - } + ); ConnectionParameters &setOwnAddressType(own_address_type_t ownAddress) { @@ -259,7 +209,7 @@ private: was_swapped = true; } - _enabledPhy[phy.value()] = enable; + _enabledPhy[index] = enable; if (isSwapped()) { is_swapped = true; @@ -307,35 +257,7 @@ private: } /** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ - void swapCodedAnd2M() - { - uint16_t scanInterval = _scanInterval[LE_2M_INDEX]; - uint16_t scanWindow = _scanWindow[LE_2M_INDEX]; - uint16_t minConnectionInterval = _minConnectionInterval[LE_2M_INDEX]; - uint16_t maxConnectionInterval = _maxConnectionInterval[LE_2M_INDEX]; - uint16_t slaveLatency = _maxConnectionInterval[LE_2M_INDEX]; - uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[LE_2M_INDEX]; - uint16_t minEventLength = _minEventLength[LE_2M_INDEX]; - uint16_t maxEventLength = _maxEventLength[LE_2M_INDEX]; - - _scanInterval[LE_2M_INDEX] = _scanInterval[LE_CODED_INDEX]; - _scanWindow[LE_2M_INDEX] = _scanWindow[LE_CODED_INDEX]; - _minConnectionInterval[LE_2M_INDEX] = _minConnectionInterval[LE_CODED_INDEX]; - _maxConnectionInterval[LE_2M_INDEX] = _maxConnectionInterval[LE_CODED_INDEX]; - _slaveLatency[LE_2M_INDEX] = _slaveLatency[LE_CODED_INDEX]; - _connectionSupervisionTimeout[LE_2M_INDEX] = _connectionSupervisionTimeout[LE_CODED_INDEX]; - _minEventLength[LE_2M_INDEX] = _minEventLength[LE_CODED_INDEX]; - _maxEventLength[LE_2M_INDEX] = _maxEventLength[LE_CODED_INDEX]; - - _scanInterval[LE_CODED_INDEX] = scanInterval; - _scanWindow[LE_CODED_INDEX] = scanWindow; - _minConnectionInterval[LE_CODED_INDEX] = minConnectionInterval; - _maxConnectionInterval[LE_CODED_INDEX] = maxConnectionInterval; - _slaveLatency[LE_CODED_INDEX] = slaveLatency; - _connectionSupervisionTimeout[LE_CODED_INDEX] = connectionSupervisionTimeout; - _minEventLength[LE_CODED_INDEX] = minEventLength; - _maxEventLength[LE_CODED_INDEX] = maxEventLength; - } + void swapCodedAnd2M(); private: initiator_filter_policy_t _filterPolicy; diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp b/features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp similarity index 100% rename from features/FEATURE_BLE/ble/gap/AdvertisingParameters.cpp rename to features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp diff --git a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp new file mode 100644 index 0000000000..d73cecdde7 --- /dev/null +++ b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp @@ -0,0 +1,132 @@ +/* mbed Microcontroller Library + * Copyright (c) 2018 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include "gap/ConnectionParameters.h" + +namespace ble { + +ConnectionParameters::ConnectionParameters( + scan_interval_t scanInterval, + scan_window_t scanWindow, + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t connectionSupervisionTimeout, + phy_t phy, + conn_event_length_t minEventLength, + conn_event_length_t maxEventLength +) : + _filterPolicy(initiator_filter_policy_t::NO_FILTER), + _ownAddressType(own_address_type_t::PUBLIC) +{ + for (uint8_t i = 0; i < MAX_PARAM_PHYS; ++i) { + _enabledPhy[i] = false; + } + if (phy != phy_t::NONE) { + uint8_t phy_index = phyToIndex(phy); + + if (phy_index < MAX_PARAM_PHYS) { + _scanInterval[phy_index] = scanInterval.value(); + _scanWindow[phy_index] = scanWindow.value(); + _minConnectionInterval[phy_index] = minConnectionInterval.value(); + _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); + _slaveLatency[phy_index] = slaveLatency.value(); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); + _enabledPhy[phy_index] = true; + _minEventLength[phy_index] = minEventLength.value(); + _maxEventLength[phy_index] = maxEventLength.value(); + } + } +} + +/* setters */ + +ConnectionParameters& ConnectionParameters::setScanParameters( + scan_interval_t scanInterval, + scan_window_t scanWindow, + phy_t phy +) { + uint8_t phy_index = handlePhyToggle(phy, true); + + if (phy_index < MAX_PARAM_PHYS) { + _scanInterval[phy_index] = scanInterval.value(); + _scanWindow[phy_index] = scanWindow.value(); + } + + return *this; +} + +ConnectionParameters& ConnectionParameters::setConnectionParameters( + conn_interval_t minConnectionInterval, + conn_interval_t maxConnectionInterval, + slave_latency_t slaveLatency, + supervision_timeout_t connectionSupervisionTimeout, + phy_t phy, + conn_event_length_t minEventLength, + conn_event_length_t maxEventLength +) { + uint8_t phy_index = handlePhyToggle(phy, true); + + if (phy_index < MAX_PARAM_PHYS) { + _minConnectionInterval[phy_index] = minConnectionInterval.value(); + _maxConnectionInterval[phy_index] = maxConnectionInterval.value(); + _slaveLatency[phy_index] = slaveLatency.value(); + _connectionSupervisionTimeout[phy_index] = connectionSupervisionTimeout.value(); + + /* avoid overflows and truncation */ + if (minEventLength.value() > maxEventLength.value()) { + minEventLength = maxEventLength; + } + + _minEventLength[phy_index] = minEventLength.value(); + _maxEventLength[phy_index] = maxEventLength.value(); + } + + return *this; +} + +/** Handle the swapping of 2M and CODED so that the array is ready for the pal call. */ +void ConnectionParameters::swapCodedAnd2M() +{ + uint16_t scanInterval = _scanInterval[LE_2M_INDEX]; + uint16_t scanWindow = _scanWindow[LE_2M_INDEX]; + uint16_t minConnectionInterval = _minConnectionInterval[LE_2M_INDEX]; + uint16_t maxConnectionInterval = _maxConnectionInterval[LE_2M_INDEX]; + uint16_t slaveLatency = _maxConnectionInterval[LE_2M_INDEX]; + uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[LE_2M_INDEX]; + uint16_t minEventLength = _minEventLength[LE_2M_INDEX]; + uint16_t maxEventLength = _maxEventLength[LE_2M_INDEX]; + + _scanInterval[LE_2M_INDEX] = _scanInterval[LE_CODED_INDEX]; + _scanWindow[LE_2M_INDEX] = _scanWindow[LE_CODED_INDEX]; + _minConnectionInterval[LE_2M_INDEX] = _minConnectionInterval[LE_CODED_INDEX]; + _maxConnectionInterval[LE_2M_INDEX] = _maxConnectionInterval[LE_CODED_INDEX]; + _slaveLatency[LE_2M_INDEX] = _slaveLatency[LE_CODED_INDEX]; + _connectionSupervisionTimeout[LE_2M_INDEX] = _connectionSupervisionTimeout[LE_CODED_INDEX]; + _minEventLength[LE_2M_INDEX] = _minEventLength[LE_CODED_INDEX]; + _maxEventLength[LE_2M_INDEX] = _maxEventLength[LE_CODED_INDEX]; + + _scanInterval[LE_CODED_INDEX] = scanInterval; + _scanWindow[LE_CODED_INDEX] = scanWindow; + _minConnectionInterval[LE_CODED_INDEX] = minConnectionInterval; + _maxConnectionInterval[LE_CODED_INDEX] = maxConnectionInterval; + _slaveLatency[LE_CODED_INDEX] = slaveLatency; + _connectionSupervisionTimeout[LE_CODED_INDEX] = connectionSupervisionTimeout; + _minEventLength[LE_CODED_INDEX] = minEventLength; + _maxEventLength[LE_CODED_INDEX] = maxEventLength; +} + +} // namespace ble From fea3ac87de513c1316e991d02105aa887c858e2d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 14:05:12 +0000 Subject: [PATCH 267/361] BLE: Add forever information to ble::adv_duration_t and ble::scan_duration_t --- features/FEATURE_BLE/ble/gap/Gap.h | 4 ++-- features/FEATURE_BLE/ble/gap/Types.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 7236979b98..2cddf5db88 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -256,7 +256,7 @@ public: */ virtual ble_error_t startAdvertising( advertising_handle_t handle, - adv_duration_t maxDuration = adv_duration_t(0), + adv_duration_t maxDuration = adv_duration_t::forever(), uint8_t maxEvents = 0 ); @@ -347,7 +347,7 @@ public: */ virtual ble_error_t startScan( duplicates_filter_t filtering = duplicates_filter_t::DISABLE, - scan_duration_t duration = scan_duration_t(0), + scan_duration_t duration = scan_duration_t::forever(), scan_period_t period = scan_period_t(0) ); diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index bbe2e39890..3e4a826a73 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -25,8 +25,8 @@ namespace ble { /* BLE units, using microseconds as the common denominator */ typedef Duration > adv_interval_t; -typedef Duration > adv_duration_t; -typedef Duration > scan_duration_t; +typedef Duration, Forever<0x0000> > adv_duration_t; +typedef Duration, Forever<0x0000> > scan_duration_t; typedef Duration > scan_period_t; typedef Duration > scan_interval_t; typedef Duration > scan_window_t; From 9f39dba42939b207a100ca29f1673870bcccce3f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Wed, 21 Nov 2018 14:14:19 +0000 Subject: [PATCH 268/361] BLE: Fix constant declaration of ble::AdvertisingParameters. --- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 6 +++--- features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index fa724f72ce..ca8ce80216 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -48,9 +48,9 @@ namespace ble { */ class AdvertisingParameters { - static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN; + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; - static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX; + static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; /** * Minimum Advertising interval for scannable and nonconnectable @@ -58,7 +58,7 @@ class AdvertisingParameters { * * @note Equal to 100ms. */ - static const uint32_t GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; + static const uint32_t GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; public: /** diff --git a/features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp b/features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp index 8d0db1db88..907d6e2097 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingParameters.cpp @@ -18,8 +18,8 @@ namespace ble { -const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; -const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; -const uint32_t AdvertisingParameters::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON = 0x00A0; +const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MIN; +const uint32_t AdvertisingParameters::DEFAULT_ADVERTISING_INTERVAL_MAX; +const uint32_t AdvertisingParameters::GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; } // namespace ble From c9dcef17dd8958122cca1c4654e4c9a242723d95 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 22 Nov 2018 11:09:43 +0000 Subject: [PATCH 269/361] return func made const --- features/FEATURE_BLE/ble/common/Duration.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 9fd4063410..0bd011cb4b 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -147,7 +147,7 @@ struct Duration { * * @return The duration in TB units. */ - Rep value() { + Rep value() const { return duration; } From cd5dabf464936029a28664999fda1e60713f2829 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 22 Nov 2018 14:01:28 +0000 Subject: [PATCH 270/361] duration added valueInMs --- features/FEATURE_BLE/ble/common/Duration.h | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 0bd011cb4b..83b138d9f4 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -151,6 +151,15 @@ struct Duration { return duration; } + /** + * Return the duration in milliseconds. + * + * @return The duration in milliseconds. + */ + uint32_t valueInMs() const { + return ((uint32_t)duration * TB) / 1000; + } + /** * The time base. */ From 2eaec287fb3421b89c3cb8627d3c53664115fff6 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Thu, 22 Nov 2018 14:04:59 +0000 Subject: [PATCH 271/361] simple scan paramater constructor --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 99d89c8c18..bdd1dd6ff3 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -52,11 +52,17 @@ public: bool active_scanning; }; - ScanParameters() : - own_address_type(own_address_type_t::PUBLIC), + ScanParameters( + scan_window_t scan_interval = scan_interval_t::min(), + scan_interval_t scan_window = scan_window_t::min(), + bool active_scanning = false, + own_address_type_t own_address_type = own_address_type_t::PUBLIC, + scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER + ) : + own_address_type(own_address_type), scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), phys(phy_set_t::PHY_SET_1M), - phy_1m_configuration(), + phy_1m_configuration(scan_interval, scan_window, active_scanning), phy_coded_configuration() { } From 52318e464db2ee1bfce775537437eb38a8d452d6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 22 Nov 2018 11:26:11 +0000 Subject: [PATCH 272/361] BLE: rename AdvertisingParameters::*PolicyMode into AdvertisingParameters::*Filter. --- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 8 ++++---- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index ca8ce80216..d4f37e3cd8 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -267,23 +267,23 @@ public: return _peerAddressType; }; - /** Set the policy of whitelist use during advertising; + /** Set the filter policy of whitelist use during advertising; * * @param Policy to use. * * @return A reference to this object. */ - AdvertisingParameters &setPolicyMode(advertising_filter_policy_t mode) + AdvertisingParameters &setFilter(advertising_filter_policy_t mode) { _policy = mode; return *this; } - /** Get the policy of whitelist use during advertising; + /** Get the filter policy of whitelist use during advertising; * * @return Policy used. */ - advertising_filter_policy_t getPolicyMode() const + advertising_filter_policy_t getFilter() const { return _policy; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 46759fc287..fe385f3900 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1859,7 +1859,7 @@ ble_error_t GenericGap::setAdvertisingParameters( params.getPeerAddressType(), params.getPeerAddress(), channel_map, - params.getPolicyMode() + params.getFilter() ); } else { return setExtendedAdvertisingParameters(handle, params); @@ -1895,7 +1895,7 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( params.getOwnAddressType(), params.getPeerAddressType(), params.getPeerAddress(), - params.getPolicyMode(), + params.getFilter(), params.getTxPower(), params.getPrimaryPhy(), params.getSecondaryMaxSkip(), From 8d03d67ae8aee5beb5d9463e4d4ecbc1688cf953 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 22 Nov 2018 11:26:22 +0000 Subject: [PATCH 273/361] BLE: Improve ble::AdvertisingParameters documentation. --- .../ble/gap/AdvertisingParameters.h | 83 ++++++++++++++++--- 1 file changed, 70 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index d4f37e3cd8..11e303bf17 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -36,20 +36,75 @@ namespace ble { /** * Parameters defining the advertising process. * - * Advertising parameters for legacy advertising are a triplet of three value: + * @par Legacy advertising: + * + * Advertising parameters for legacy advertising are a mainly defined by a pair + * of values: * - The Advertising mode modelled after advertising_type_t. It defines * if the device is connectable and scannable. This value can be set at - * construction time, updated with setAdvertisingType() and queried by - * getAdvertisingType(). + * construction time, updated with setType() and queried by getType(). * - Time interval between advertisement. It can be set at construction time, - * updated by setInterval() and obtained from getInterval(). - * - Duration of the advertising process. As others, it can be set at - * construction time, modified by setTimeout() and retrieved by getTimeout(). + * updated by setPrimaryInterval() and obtained from getMinPrimaryInterval() + * and getMaxPrimaryInterval(). + * + * In addition, it is possible to adjust other parameters: + * - The advertising channels can be selected with setPrimaryChannels() and + * queried by getChannel37(), getChannel38() and getChannel39(). + * - The address type used by the local device can be set with setOwnAddressType() + * and queried by getOwnAddressType(). + * - The filter policy for scan and connection requests can be set with + * setFilter() and queried by getFilter(). + * + * For directed advertising, the address of the target can be set with the help + * of setPeer() and queried by getPeerAddress() and getPeerAddressType(). + * + * @par Extended advertising: + * + * To use extended advertising features, legacy advertising should be disabled + * first with setUseLegacyPDU(). + * + * Extended advertising add new features to BLE advertising: + * - Control the advertising power with setTxPower(). + * - Include the Tx power in advertising packet with includeTxPowerInHeader(). + * - Set a secondary phy_t channel with setPhy(). + * - Enable scan requests notification to let the application be aware of any + * incoming scan requests with setScanRequestNotification(). + * - Advertise anonymously with setAnonymousAdvertising() + * + * @par Fluent interface: + * + * This API is designed with usability in mind. It is perfectly legal to + * construct it and pass it in place. To achieve this the fluent interface pattern + * is used. Every setter returns a reference to the object modified and can be + * chained. + * + * @code + void setAdvertisingParameters(ble::Gap& gap) { + using namespace ble; + gap.setAdvertisingParameters( + LEGACY_ADVERTISING_HANDLE, + AdvertisingParameters() + .setType(advertising_type_t::ADV_CONNECTABLE_UNDIRECTED) + .setPrimaryInterval(millisecond_t(200), millisecond_t(500)) + .setOwnAddressType(own_address_type_t::RANDOM) + .setUseLegacyPDU(false) + .setPhy(phy_t::LE_1M, phy_t::LE_CODED) + ); + } + * @endcode + * + * @see ble::Gap::createAdvertisingSet(), ble::Gap::setAdvertisingParameters() */ class AdvertisingParameters { + /** + * Default minimum advertising interval. + */ static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MIN = 0x400; + /** + * Default maximum advertising interval. + */ static const uint32_t DEFAULT_ADVERTISING_INTERVAL_MAX = 0x800; /** @@ -65,10 +120,9 @@ public: * Construct an instance of GapAdvertisingParams. * * @param[in] advType Type of advertising. - * @param[in] minInterval Time interval between two advertisement in units of - * 0.625ms. - * @param[in] timeout Duration in seconds of the advertising process. A - * value of 0 indicate that there is no timeout of the advertising process. + * @param[in] minInterval, maxInterval Time interval between two advertisement. + * A range is provided to the LE subsystem so it can adjust the advertising + * interval with other transmission happening on the BLE radio. * * @note If value in input are out of range, they will be normalized. */ @@ -119,7 +173,7 @@ public: } /** - * Return advertising type. + * Return the advertising type. * * @return Advertising type. */ @@ -130,8 +184,9 @@ public: /** Set the advertising intervals on the primary channels. * - * @param min Minimum interval . - * @param max Maximum interval . + * @param[in] minInterval, maxInterval Time interval between two advertisement. + * A range is provided to the LE subsystem so it can adjust the advertising + * interval with other transmission happening on the BLE radio. * * @return reference to this object. */ @@ -370,6 +425,8 @@ public: * @param enable Enable callback if true. * * @return A reference to this object. + * + * @see ::ble::Gap::EventHandler::onScanRequest() */ AdvertisingParameters &setScanRequestNotification(bool enable = true) { From 1841f4e75e9a21c5d0a8c9d4bc3f3a54bbbfb039 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Thu, 22 Nov 2018 22:23:50 +0000 Subject: [PATCH 274/361] BLE: Document ble::ConnectionParameters. --- .../ble/gap/ConnectionParameters.h | 150 +++++++++++++++++- 1 file changed, 149 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 15ef1f0fb8..5d4c3f4f03 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -29,6 +29,62 @@ namespace ble { +/** + * Parameters defining the connection initiation process. + * + * The connection initiation process is divided in two different phases. First + * the initiating device scan for the peer it should connect. Once the peer has + * been found, it sends a connection request that contains the connection + * parameters. + * + * @par Scan parameters + * + * The scan parameters are defined by two durations: the scan interval and the + * scan window. The scan interval is the duration between two scan cycle and the + * scan window defines how long the device search during a scan cycle. + * + * The scan window and the scan interval can be set at construction time or by + * calling setScanParameters(). + * + * @par Connection parameters + * + * A Bluetooth connection is defined by three parameters: + * - Connection interval: The time between two connection events. A minimum + * and a maximum connection interval are requested to help the Bluetooth + * subsystem deal with concurrent radio processing. + * - Slave latency: Number of connection events that can be ignored by the + * slave. + * - Supervision timeout: Time after which the connection is considered lost + * if the connected devices haven't exchanged a single packet. It is important + * to note that even if the application doesn't send actual data, the Bluetooth + * controller takes care of sending empty data packets to maintain the + * connection alive. + * + * These parameters can be set at construction time or by calling the function + * setConnectionParameters(). + * + * @par Phy + * + * Bluetooth 5 have introduced the support of different physical layer to either + * increase the range or the throughput. Multiple phy can be configured + * independently for scanning and connecting. + * + * Legacy connection happens on the 1M phy (phy_t::LE_1M). It is the only phy + * that can be configured on legacy systems. + * + * The constructor, setScanParameters() and setConnectionParameters() accept + * a phy_t parameter that defines to which PHY the parameters set applies. + * + * @par Other parameters: + * + * It is possible to defined what type of address is used to establish the + * connection and whether or not if the whitelist should be used to find the peer + * to connect to. + * + * @note It is not possible to configure phy_t::LE_2M for scanning. + * + * @see ble::Gap::connect() + */ class ConnectionParameters { static const uint8_t MAX_PARAM_PHYS = 3; static const uint8_t LE_1M_INDEX = 0; @@ -36,6 +92,20 @@ class ConnectionParameters { static const uint8_t LE_CODED_INDEX = 2; public: + /** + * Create a ConnectionParameters object. + * + * @param scanInterval Interval between two scans. + * @param scanWindow Scan duration during a scan interval. + * @param minConnectionInterval Minimum value of the connection interval. + * @param maxConnectionInterval Maximum value of the connection interval. + * @param slaveLatency Maximum number of packets the slave can drop. + * @param connectionSupervisionTimeout Time after which the connection is + * considered lost if no data exchanged have taken place. + * @param phy The phy being configured. + * @param minEventLength Minimum duration of a connection event. + * @param maxEventLength Maximum duration of a connection event + */ ConnectionParameters( scan_interval_t scanInterval = scan_interval_t::min(), scan_window_t scanWindow = scan_window_t::min(), @@ -50,12 +120,38 @@ public: /* setters */ + /** + * Set the scan parameters for a given phy. + * + * @param scanInterval Interval between two scans. + * @param scanWindow Scan duration within a scan interval. + * @param phy PHY being configured. + * + * @note It is useless to configure the 2M phy as it is not used during + * scanning. + * + * @return A reference to this. + */ ConnectionParameters &setScanParameters( scan_interval_t scanInterval, scan_window_t scanWindow, phy_t phy = phy_t::LE_1M ); + /** + * Set the conenction parameters of a given PHY. + * + * @param minConnectionInterval Minimum connection interval. + * @param maxConnectionInterval Maximum connection interval. + * @param slaveLatency Maximum number of packets the slave can drop. + * @param connectionSupervisionTimeout Time after which the connection is + * considered lost if no data exchanged have taken place. + * @param phy The PHY being configured. + * @param minEventLength Minimum duration of a connection event. + * @param maxEventLength Maximum duration of a connection event. + * + * @return A reference to this. + */ ConnectionParameters &setConnectionParameters( conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, @@ -66,13 +162,24 @@ public: conn_event_length_t maxEventLength = conn_event_length_t::max() ); + /** + * Address type used by the local device to connect the peer. + * @param ownAddress Type of address used to initiate the connection. + * @return A reference to this. + */ ConnectionParameters &setOwnAddressType(own_address_type_t ownAddress) { _ownAddressType = ownAddress; - return *this; } + /** + * Set if the whitelist should be used to find the peer. + * + * @param filterPolicy The initiator filter to apply. + * + * @return A reference to this. + */ ConnectionParameters &setFilterPolicy(initiator_filter_policy_t filterPolicy) { _filterPolicy = filterPolicy; @@ -80,6 +187,15 @@ public: return *this; } + /** + * Enable or disable phys. + * + * @param phy1M true to enable the 1M PHY and false to disable it. + * @param phy2M true to enable the 2M PHY and false to disable it. + * @param phyCoded true to enable the CODED PHY and false to disable it. + * + * @return A reference to this. + */ ConnectionParameters &togglePhy(bool phy1M, bool phy2M, bool phyCoded) { handlePhyToggle(phy_t::LE_1M, phy1M); @@ -89,6 +205,13 @@ public: return *this; } + /** + * Disable an individual phy. + * + * @param phy The phy to disable. + * + * @return A reference to this. + */ ConnectionParameters &disablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, false); @@ -96,6 +219,13 @@ public: return *this; } + /** + * Enable an individual phy. + * + * @param phy The phy to enable. + * + * @return A reference to this. + */ ConnectionParameters &enablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, true); @@ -105,16 +235,30 @@ public: /* getters */ + /** + * Return the local address type used. + * + * @return The local address type to use. + */ own_address_type_t getOwnAddressType() const { return _ownAddressType; } + /** + * Return the initiator policy. + * + * @return The initiator policy. + */ initiator_filter_policy_t getFilterPolicy() const { return _filterPolicy; } + /** + * Return the number of phy enabled. + * @return The number of phy enabled. + */ uint8_t getNumberOfEnabledPhys() const { return ( @@ -124,6 +268,8 @@ public: ); } +#if !defined(DOXYGEN_ONLY) + uint8_t getPhySet() const { phy_set_t set( @@ -176,6 +322,8 @@ public: return &_maxEventLength[getFirstEnabledIndex()]; } +#endif + private: uint8_t getFirstEnabledIndex() const { From 49455dcc872e5014a3795e2c9c40b469b5e7c647 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 08:47:40 +0000 Subject: [PATCH 275/361] BLE: set the phy as first parameter in ble::ConnectionParameters. --- .../FEATURE_BLE/ble/gap/ConnectionParameters.h | 17 ++++++++--------- .../source/gap/ConnectionParameters.cpp | 18 ++++++++++-------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 5d4c3f4f03..ede218ede2 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -95,6 +95,7 @@ public: /** * Create a ConnectionParameters object. * + * @param phy The phy being configured. * @param scanInterval Interval between two scans. * @param scanWindow Scan duration during a scan interval. * @param minConnectionInterval Minimum value of the connection interval. @@ -102,30 +103,28 @@ public: * @param slaveLatency Maximum number of packets the slave can drop. * @param connectionSupervisionTimeout Time after which the connection is * considered lost if no data exchanged have taken place. - * @param phy The phy being configured. * @param minEventLength Minimum duration of a connection event. * @param maxEventLength Maximum duration of a connection event */ ConnectionParameters( + phy_t phy = phy_t::LE_1M, scan_interval_t scanInterval = scan_interval_t::min(), scan_window_t scanWindow = scan_window_t::min(), conn_interval_t minConnectionInterval = conn_interval_t::min(), conn_interval_t maxConnectionInterval = conn_interval_t::max(), slave_latency_t slaveLatency = slave_latency_t::min(), supervision_timeout_t connectionSupervisionTimeout = supervision_timeout_t::max(), - phy_t phy = phy_t::LE_1M, conn_event_length_t minEventLength = conn_event_length_t::min(), - conn_event_length_t maxEventLength = conn_event_length_t::max() - ); + conn_event_length_t maxEventLength = conn_event_length_t::max()); /* setters */ /** * Set the scan parameters for a given phy. * + * @param phy PHY being configured. * @param scanInterval Interval between two scans. * @param scanWindow Scan duration within a scan interval. - * @param phy PHY being configured. * * @note It is useless to configure the 2M phy as it is not used during * scanning. @@ -133,31 +132,31 @@ public: * @return A reference to this. */ ConnectionParameters &setScanParameters( + phy_t phy, scan_interval_t scanInterval, - scan_window_t scanWindow, - phy_t phy = phy_t::LE_1M + scan_window_t scanWindow ); /** * Set the conenction parameters of a given PHY. * + * @param phy The PHY being configured. * @param minConnectionInterval Minimum connection interval. * @param maxConnectionInterval Maximum connection interval. * @param slaveLatency Maximum number of packets the slave can drop. * @param connectionSupervisionTimeout Time after which the connection is * considered lost if no data exchanged have taken place. - * @param phy The PHY being configured. * @param minEventLength Minimum duration of a connection event. * @param maxEventLength Maximum duration of a connection event. * * @return A reference to this. */ ConnectionParameters &setConnectionParameters( + phy_t phy, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t connectionSupervisionTimeout, - phy_t phy = phy_t::LE_1M, conn_event_length_t minEventLength = conn_event_length_t::min(), conn_event_length_t maxEventLength = conn_event_length_t::max() ); diff --git a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp index d73cecdde7..bac775437f 100644 --- a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp +++ b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp @@ -19,13 +19,13 @@ namespace ble { ConnectionParameters::ConnectionParameters( + phy_t phy, scan_interval_t scanInterval, scan_window_t scanWindow, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t connectionSupervisionTimeout, - phy_t phy, conn_event_length_t minEventLength, conn_event_length_t maxEventLength ) : @@ -54,11 +54,12 @@ ConnectionParameters::ConnectionParameters( /* setters */ -ConnectionParameters& ConnectionParameters::setScanParameters( +ConnectionParameters & ConnectionParameters::setScanParameters( + phy_t phy, scan_interval_t scanInterval, - scan_window_t scanWindow, - phy_t phy -) { + scan_window_t scanWindow +) +{ uint8_t phy_index = handlePhyToggle(phy, true); if (phy_index < MAX_PARAM_PHYS) { @@ -69,15 +70,16 @@ ConnectionParameters& ConnectionParameters::setScanParameters( return *this; } -ConnectionParameters& ConnectionParameters::setConnectionParameters( +ConnectionParameters & ConnectionParameters::setConnectionParameters( + phy_t phy, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, slave_latency_t slaveLatency, supervision_timeout_t connectionSupervisionTimeout, - phy_t phy, conn_event_length_t minEventLength, conn_event_length_t maxEventLength -) { +) +{ uint8_t phy_index = handlePhyToggle(phy, true); if (phy_index < MAX_PARAM_PHYS) { From 6e4e733c1c6fe0bdf7133ee609ef0276ea943d27 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 09:12:39 +0000 Subject: [PATCH 276/361] BLE: Add code example for ble::ConnectionParameters. --- .../ble/gap/ConnectionParameters.h | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index ede218ede2..325264ec4c 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -81,6 +81,39 @@ namespace ble { * connection and whether or not if the whitelist should be used to find the peer * to connect to. * + * @par Example: + * + * Thanks to the fluent API it is easy to compose the connection parameters at + * instantiation point: + * + * @code + * + void do_connect(ble::Gap& gap, ble::target_peer_address_type_t addr_type, ble::address_t& address) + { + using namespace ble; + + gap.connect( + addr_type, + address, + ConnectionParameters() + .setScanParameters( + phy_t::LE_1M, + scan_interval_t(millisecond_t(500)), + scan_window_t(millisecond_t(250)) + ) + .setConnectionParameters( + phy_t::LE_1M, + conn_interval_t(millisecond_t(100)), + conn_interval_t(millisecond_t(200)), + slave_latency_t(0), + supervision_timeout_t(millisecond_t(1000)) + ) + .setOwnAddressType(own_address_type_t::RANDOM) + ); + } + * + * @endcode + * * @note It is not possible to configure phy_t::LE_2M for scanning. * * @see ble::Gap::connect() From 8fc62efbd83ab19d1e672800c64a6221bbf51249 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 09:47:50 +0000 Subject: [PATCH 277/361] BLE: Improve naming consistency of ble::Gap::EventHandler functions. --- features/FEATURE_BLE/ble/BLE.h | 4 ++-- features/FEATURE_BLE/ble/Gap.h | 2 +- features/FEATURE_BLE/ble/gap/Gap.h | 6 +++--- features/FEATURE_BLE/source/generic/GenericGap.cpp | 14 +++++++------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index 5b2ddc1dbc..ef4cfe9e58 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -1398,7 +1398,7 @@ public: * to ble.onDisconnection(callback) should be replaced with * ble.gap().onDisconnection(callback). */ - MBED_DEPRECATED("ble.gap().onDisconnection(callback)") + MBED_DEPRECATED("ble.gap().onDisconnectionComplete(callback)") void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback); /** @@ -1411,7 +1411,7 @@ public: * ble.gap().onDisconnection(callback). */ template - MBED_DEPRECATED("ble.gap().onDisconnection(callback)") + MBED_DEPRECATED("ble.gap().onDisconnectionComplete(callback)") void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t*)) { gap().onDisconnection(tptr, mptr); } diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 84a89a4022..010da0b09a 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -2622,7 +2622,7 @@ public: MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support. " - "Use EventHandler::onDisconnection() instead" + "Use EventHandler::onDisconnectionComplete() instead" ) void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) { diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 2cddf5db88..b86fa0f6a5 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -39,7 +39,7 @@ public: * * @param event Scan request event: @see ScanRequestEvent_t for details. */ - virtual void onScanRequest(const ScanRequestEvent_t &event) { } + virtual void onScanRequestReceived(const ScanRequestEvent_t &event) { } /** Called when advertising ends. * @@ -70,7 +70,7 @@ public: * * @param event Periodic advertisement event. */ - virtual void onPeriodicAdvertisingReportEvent( + virtual void onPeriodicAdvertisingReport( const PeriodicAdvertisingReportEvent &event ) { } @@ -92,7 +92,7 @@ public: const ConnectionParametersUpdateCompleteEvent &event ) { } - virtual void onDisconnection(const DisconnectionEvent &event) { } + virtual void onDisconnectionComplete(const DisconnectionEvent &event) { } /** * Function invoked when the current transmitter and receiver PHY have diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index fe385f3900..107ff57d38 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1303,7 +1303,7 @@ void GenericGap::processDisconnectionEvent( } if (_eventHandler) { - _eventHandler->onDisconnection( + _eventHandler->onDisconnectionComplete( DisconnectionEvent( handle, (disconnection_reason_t::type) reason @@ -2337,15 +2337,15 @@ void GenericGap::on_extended_advertising_report( address_type ? (peer_address_type_t::type) address_type->value() : peer_address_type_t::ANONYMOUS, - (BLEProtocol::AddressBytes_t&)address, + (BLEProtocol::AddressBytes_t &) address, primary_phy, - secondary_phy? *secondary_phy : phy_t::NONE, + secondary_phy ? *secondary_phy : phy_t::NONE, advertising_sid, tx_power, rssi, periodic_interval_t(periodic_advertising_interval), - (PeerAddressType_t::type)direct_address_type.value(), - (BLEProtocol::AddressBytes_t&)direct_address, + (PeerAddressType_t::type) direct_address_type.value(), + (BLEProtocol::AddressBytes_t &) direct_address, mbed::make_Span(data, data_length) ) ); @@ -2394,7 +2394,7 @@ void GenericGap::on_periodic_advertising_report( return; } - _eventHandler->onPeriodicAdvertisingReportEvent( + _eventHandler->onPeriodicAdvertisingReport( PeriodicAdvertisingReportEvent( sync_handle, tx_power, @@ -2449,7 +2449,7 @@ void GenericGap::on_scan_request_received( return; } - _eventHandler->onScanRequest( + _eventHandler->onScanRequestReceived( ScanRequestEvent_t( advertising_handle, (peer_address_type_t::type) scanner_address_type.value(), From 430777e20b1f8061fcbb51c50c755b6e158ff71a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 11:23:56 +0000 Subject: [PATCH 278/361] BLE: Update documentation of Gap::Events. --- features/FEATURE_BLE/ble/gap/Events.h | 94 ++++++++++++++++++++++++--- 1 file changed, 85 insertions(+), 9 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 2b7a8cfbc2..45205c6aa7 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -23,8 +23,11 @@ namespace ble { -/** Event generated when an advertising packet is seen during passive scanning - * or a scan response is received during active scanning. +/** + * Event generated when an advertising packet is seen during passive scanning + * or a scan response is received during active scanning. + * + * @see ble::Gap::EventHandler::onPeriodicAdvertisingReport() */ struct AdvertisingReportEvent { /** Create a advertising report event. @@ -156,7 +159,10 @@ private: mbed::Span advertisingData; }; -/** Event generated when a connection initiation end (successfully or not). +/** + * Event generated when a connection initiation end (successfully or not). + * + * @see ble::Gap::EventHandler::onConnectionComplete(). */ struct ConnectionCompleteEvent { /** Create a connection complete event. @@ -278,7 +284,10 @@ private: uint16_t masterClockAccuracy; }; -/** Event generated when we first receive a periodic advertisement. +/** + * Event generated when we first receive a periodic advertisement. + * + * @see ble::Gap::EventHandler::onPeriodicAdvertisingSyncEstablished(). */ struct PeriodicAdvertisingSyncEstablishedEvent { /** Create advertising sync event. @@ -370,7 +379,10 @@ private: clock_accuracy_t peerClockAccuracy; }; -/** Event generated when periodic advertising packet is received. +/** + * Event generated when periodic advertising packet is received. + * + * @see ble::Gap::EventHandler::onPeriodicAdvertisingReport(). */ struct PeriodicAdvertisingReportEvent { /** Create periodic advertising report event. @@ -432,7 +444,10 @@ private: mbed::Span payload; }; -/** Event generated when periodic advertising sync is lost. +/** + * Event generated when periodic advertising sync is lost. + * + * @see ble::Gap::EventHandler::onPeriodicAdvertisingSyncLoss(). */ struct PeriodicAdvertisingSyncLoss { /** Create periodic advertising sync loss event. @@ -454,11 +469,17 @@ private: periodic_sync_handle_t syncHandle; }; -/** Event generated when scan times out. +/** + * Event generated when scan times out. + * + * @see ble::Gap::EventHandler::onScanTimeout(). */ struct ScanTimeoutEvent { }; -/** Event produced when advertising ends. +/** + * Event produced when advertising ends. + * + * @see ble::Gap::EventHandler::onAdvertisingEnd(). */ struct AdvertisingEndEvent_t { /** Create advertising end event. @@ -510,7 +531,10 @@ private: bool connected; }; -/** Event produced when a peer requests a scan response from the advertiser. +/** + * Event produced when a peer requests a scan response from the advertiser. + * + * @see ble::Gap::EventHandler::onScanRequestReceived(). */ struct ScanRequestEvent_t { /** Create scan request event. @@ -552,17 +576,28 @@ private: const address_t &peerAddress; }; +/** + * Event produced when a disconnection is complete. + * + * @see ble::Gap::EventHandler::onDisconnectionComplete(). + */ struct DisconnectionEvent { DisconnectionEvent( connection_handle_t connectionHandle, const disconnection_reason_t &reason ) : connectionHandle(connectionHandle), reason(reason) { } + /** + * Get the handle of the connection that has expired. + */ connection_handle_t getConnectionHandle() const { return connectionHandle; } + /** + * Get the reason of the disconnection. + */ const disconnection_reason_t &getReason() const { return reason; @@ -573,6 +608,11 @@ private: ble::disconnection_reason_t reason; }; +/** + * Event received when a peer wants to change the connection parameters. + * + * @see ble::Gap::EventHandler::onUpdateConnectionParametersRequest(). + */ struct UpdateConnectionParametersRequestEvent { UpdateConnectionParametersRequestEvent( connection_handle_t connectionHandle, @@ -588,26 +628,41 @@ struct UpdateConnectionParametersRequestEvent { supervisionTimeout(supervision_timeout) { } + /** + * Get the connection handle. + */ connection_handle_t getConnectionHandle() const { return connectionHandle; } + /** + * Get the minimum connection interval requested. + */ const conn_interval_t &getMinConnectionInterval() const { return minConnectionInterval; } + /** + * Get the maximum connection interval requested. + */ const conn_interval_t &getMaxConnectionInterval() const { return maxConnectionInterval; } + /** + * Get the slave latency requested. + */ const slave_latency_t &getSlaveLatency() const { return slaveLatency; } + /** + * Get the supervision timeout requested. + */ const supervision_timeout_t &getSupervisionTimeout() const { return supervisionTimeout; @@ -621,6 +676,11 @@ private: ble::supervision_timeout_t supervisionTimeout; }; +/** + * Event received when connection parameters have been updated. + * + * @see ble::Gap::EventHandler::onConnectionParametersUpdateComplete(). + */ struct ConnectionParametersUpdateCompleteEvent { ConnectionParametersUpdateCompleteEvent( ble_error_t status, @@ -636,26 +696,42 @@ struct ConnectionParametersUpdateCompleteEvent { supervisionTimeout(supervisionTimeout) { } + /** + * Get The status of the operation. It is equal to BLE_ERROR_NONE in case of + * success. + */ ble_error_t getStatus() const { return status; } + /** + * Get the handle of the connection that has been updated. + */ connection_handle_t getConnectionHandle() const { return connectionHandle; } + /** + * Get the new connection interval. + */ const conn_interval_t &getConnectionInterval() const { return connectionInterval; } + /** + * Get the new slave latency. + */ const slave_latency_t &getSlaveLatency() const { return slaveLatency; } + /** + * Get the new supervision timeout. + */ const supervision_timeout_t &getSupervisionTimeout() const { return supervisionTimeout; From dea2ae9c1fc43b9530c3608deb57821a2b49c432 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 11:25:17 +0000 Subject: [PATCH 279/361] BLE: Exclude Gap Event constructors from documentation. --- features/FEATURE_BLE/ble/gap/Events.h | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 45205c6aa7..c4db81e4ce 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -30,6 +30,7 @@ namespace ble { * @see ble::Gap::EventHandler::onPeriodicAdvertisingReport() */ struct AdvertisingReportEvent { +#if !defined(DOXYGEN_ONLY) /** Create a advertising report event. * * @param type Type of advertising used. @@ -71,6 +72,7 @@ struct AdvertisingReportEvent { directAddressType(directAddressType), directAddress(directAddress), advertisingData(advertisingData) { } +#endif /** Get event type. */ const advertising_event_t &getType() const @@ -165,6 +167,7 @@ private: * @see ble::Gap::EventHandler::onConnectionComplete(). */ struct ConnectionCompleteEvent { +#if !defined(DOXYGEN_ONLY) /** Create a connection complete event. * * @param success BLE_ERROR_NONE if connection succeeded. @@ -203,6 +206,7 @@ struct ConnectionCompleteEvent { connectionLatency(connectionLatency), supervisionTimeout(supervisionTimeout), masterClockAccuracy(masterClockAccuracy) { } +#endif /** Get connection complete event status. */ ble_error_t getStatus() const @@ -290,6 +294,7 @@ private: * @see ble::Gap::EventHandler::onPeriodicAdvertisingSyncEstablished(). */ struct PeriodicAdvertisingSyncEstablishedEvent { +#if !defined(DOXYGEN_ONLY) /** Create advertising sync event. * * @param success BLE_ERROR_NONE if synchronisation was achieved. @@ -319,6 +324,7 @@ struct PeriodicAdvertisingSyncEstablishedEvent { peerPhy(peerPhy), advertisingInterval(advertisingInterval), peerClockAccuracy(peerClockAccuracy) { } +#endif /** Get sync establishment status. */ ble_error_t getStatus() const @@ -385,6 +391,7 @@ private: * @see ble::Gap::EventHandler::onPeriodicAdvertisingReport(). */ struct PeriodicAdvertisingReportEvent { +#if !defined(DOXYGEN_ONLY) /** Create periodic advertising report event. * * @param syncHandle Periodic advertising sync handle @@ -405,6 +412,7 @@ struct PeriodicAdvertisingReportEvent { rssi(rssi), dataStatus(dataStatus), payload(payload) { } +#endif /** Get periodic advertising sync handle. */ periodic_sync_handle_t getSyncHandle() const @@ -450,6 +458,7 @@ private: * @see ble::Gap::EventHandler::onPeriodicAdvertisingSyncLoss(). */ struct PeriodicAdvertisingSyncLoss { +#if !defined(DOXYGEN_ONLY) /** Create periodic advertising sync loss event. * * @param syncHandle Periodic advertising sync handle. @@ -458,6 +467,7 @@ struct PeriodicAdvertisingSyncLoss { periodic_sync_handle_t syncHandle ) : syncHandle(syncHandle) { } +#endif /** Get periodic sync handle. */ periodic_sync_handle_t getSyncHandle() const @@ -482,6 +492,7 @@ struct ScanTimeoutEvent { }; * @see ble::Gap::EventHandler::onAdvertisingEnd(). */ struct AdvertisingEndEvent_t { +#if !defined(DOXYGEN_ONLY) /** Create advertising end event. * * @param advHandle Advertising set handle. @@ -499,6 +510,7 @@ struct AdvertisingEndEvent_t { connection(connection), completed_events(completed_events), connected(connected) { } +#endif /** Get advertising handle. */ advertising_handle_t getAdvHandle() const @@ -537,6 +549,7 @@ private: * @see ble::Gap::EventHandler::onScanRequestReceived(). */ struct ScanRequestEvent_t { +#if !defined(DOXYGEN_ONLY) /** Create scan request event. * * @param advHandle Advertising handle. @@ -551,6 +564,7 @@ struct ScanRequestEvent_t { advHandle(advHandle), peerAddressType(peerAddressType), peerAddress(peerAddress) { } +#endif /** Get advertising handle. */ advertising_handle_t getAdvHandle() const @@ -582,10 +596,12 @@ private: * @see ble::Gap::EventHandler::onDisconnectionComplete(). */ struct DisconnectionEvent { +#if !defined(DOXYGEN_ONLY) DisconnectionEvent( connection_handle_t connectionHandle, const disconnection_reason_t &reason ) : connectionHandle(connectionHandle), reason(reason) { } +#endif /** * Get the handle of the connection that has expired. @@ -614,6 +630,7 @@ private: * @see ble::Gap::EventHandler::onUpdateConnectionParametersRequest(). */ struct UpdateConnectionParametersRequestEvent { +#if !defined(DOXYGEN_ONLY) UpdateConnectionParametersRequestEvent( connection_handle_t connectionHandle, const conn_interval_t &minConnectionInterval, @@ -627,6 +644,7 @@ struct UpdateConnectionParametersRequestEvent { slaveLatency(slaveLatency), supervisionTimeout(supervision_timeout) { } +#endif /** * Get the connection handle. @@ -682,6 +700,7 @@ private: * @see ble::Gap::EventHandler::onConnectionParametersUpdateComplete(). */ struct ConnectionParametersUpdateCompleteEvent { +#if !defined(DOXYGEN_ONLY) ConnectionParametersUpdateCompleteEvent( ble_error_t status, connection_handle_t connectionHandle, @@ -695,6 +714,7 @@ struct ConnectionParametersUpdateCompleteEvent { slaveLatency(slaveLatency), supervisionTimeout(supervisionTimeout) { } +#endif /** * Get The status of the operation. It is equal to BLE_ERROR_NONE in case of @@ -746,7 +766,6 @@ private: }; - } // namespace ble #endif //BLE_GAP_EVENTS_H From 70ec1cf641a39252ec32e68b569b47d5ab43eb3f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 12:19:01 +0000 Subject: [PATCH 280/361] BLE: Improve naming consistency of Gap event types. --- features/FEATURE_BLE/ble/gap/Events.h | 8 ++++---- features/FEATURE_BLE/ble/gap/Gap.h | 4 ++-- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index c4db81e4ce..d01233acfd 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -491,7 +491,7 @@ struct ScanTimeoutEvent { }; * * @see ble::Gap::EventHandler::onAdvertisingEnd(). */ -struct AdvertisingEndEvent_t { +struct AdvertisingEndEvent { #if !defined(DOXYGEN_ONLY) /** Create advertising end event. * @@ -500,7 +500,7 @@ struct AdvertisingEndEvent_t { * @param completed_events Number of events created during before advertising end. * @param connected True if connection has been established. */ - AdvertisingEndEvent_t( + AdvertisingEndEvent( advertising_handle_t advHandle, connection_handle_t connection, uint8_t completed_events, @@ -548,7 +548,7 @@ private: * * @see ble::Gap::EventHandler::onScanRequestReceived(). */ -struct ScanRequestEvent_t { +struct ScanRequestEvent { #if !defined(DOXYGEN_ONLY) /** Create scan request event. * @@ -556,7 +556,7 @@ struct ScanRequestEvent_t { * @param peerAddressType Peer address type. * @param peerAddress Peer address. */ - ScanRequestEvent_t( + ScanRequestEvent( advertising_handle_t advHandle, const peer_address_type_t &peerAddressType, const address_t &peerAddress diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index b86fa0f6a5..73f99b5ecf 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -39,13 +39,13 @@ public: * * @param event Scan request event: @see ScanRequestEvent_t for details. */ - virtual void onScanRequestReceived(const ScanRequestEvent_t &event) { } + virtual void onScanRequestReceived(const ScanRequestEvent &event) { } /** Called when advertising ends. * * @param event Advertising end event: @see AdvertisingEndEvent_t for details. */ - virtual void onAdvertisingEnd(const AdvertisingEndEvent_t &event) { } + virtual void onAdvertisingEnd(const AdvertisingEndEvent &event) { } /** Called when scanning reads an advertising packet during passive scan or receives * a scan response during an active scan. diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 107ff57d38..9aa61a0891 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2430,7 +2430,7 @@ void GenericGap::on_advertising_set_terminated( } _eventHandler->onAdvertisingEnd( - AdvertisingEndEvent_t( + AdvertisingEndEvent( advertising_handle, connection_handle, number_of_completed_extended_advertising_events, @@ -2450,7 +2450,7 @@ void GenericGap::on_scan_request_received( } _eventHandler->onScanRequestReceived( - ScanRequestEvent_t( + ScanRequestEvent( advertising_handle, (peer_address_type_t::type) scanner_address_type.value(), address From 1b734a46d2f1cb66131853748325be06b4f0cf0a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 13:55:08 +0000 Subject: [PATCH 281/361] BLE: Improve ble::Gap::EventHandler documentation. --- features/FEATURE_BLE/ble/gap/Gap.h | 148 +++++++++++++++++++++++++---- 1 file changed, 132 insertions(+), 16 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 73f99b5ecf..c23496fca8 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -35,63 +35,139 @@ public: * Definition of the general handler of Gap related events. */ struct EventHandler { - /** Called when a scanning device request a scan response. + /** + * Called when an advertising device receive a scan response. * - * @param event Scan request event: @see ScanRequestEvent_t for details. + * @param event Scan request event. + * + * @version: 5+. + * + * @see AdvertisingParameters::setScanRequestNotification(). */ virtual void onScanRequestReceived(const ScanRequestEvent &event) { } - /** Called when advertising ends. + /** + * Called when advertising ends. * - * @param event Advertising end event: @see AdvertisingEndEvent_t for details. + * Advertising ends when the process timeout or if it is stopped by the + * application or if the local device accepts a connection request. + * + * @param event Advertising end event. + * + * @see startAdvertising() + * @see stopAdvertising() + * @see onConnectionComplete() */ virtual void onAdvertisingEnd(const AdvertisingEndEvent &event) { } - /** Called when scanning reads an advertising packet during passive scan or receives - * a scan response during an active scan. + /** + * Called when a scanner receives an advertising or a scan response packet. * - * @param event Advertising report @see AdvertisingReportEvent_t for details. + * @param event Advertising report. + * + * @see startScan() */ virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { } - /** Called when scan times out. - */ - virtual void onScanTimeout(const ScanTimeoutEvent &) { } - - /** Called when first advertising packet in periodic advertising is received. + /** + * Called when scan times out. * - * @param event Periodic advertising sync event @see PeriodicAdvertisingSyncEstablishedEvent. + * @param event Associated event. + * + * @see startScan() + */ + virtual void onScanTimeout(const ScanTimeoutEvent & event) { } + + /** + * Called when first advertising packet in periodic advertising is received. + * + * @param event Periodic advertising sync event. + * + * @version: 5+. + * + * @see createSync() */ virtual void onPeriodicAdvertisingSyncEstablished( const PeriodicAdvertisingSyncEstablishedEvent &event ) { } - /** Called when a periodic advertising packet is received. + /** + * Called when a periodic advertising packet is received. * * @param event Periodic advertisement event. + * + * @version: 5+. + * + * @see createSync() */ virtual void onPeriodicAdvertisingReport( const PeriodicAdvertisingReportEvent &event ) { } + /** + * Called when a periodic advertising sync has been lost. + * + * @param event Details of the event. + * + * @version: 5+. + * + * @see createSync() + */ virtual void onPeriodicAdvertisingSyncLoss( const PeriodicAdvertisingSyncLoss &event ) { } - /** Called when connection attempt ends. + /** + * Called when connection attempt ends or an advertising device has been + * connected. * - * @param event Connection event @see ConnectionCompleteEvent_t for details. + * @see startAdvertising() + * @see connect() + * + * @param event Connection event. */ virtual void onConnectionComplete(const ConnectionCompleteEvent &event) { } + /** + * Called when the peer request connection parameters updates. + * + * Application must accept the update with acceptConnectionParametersUpdate() + * or reject it with rejectConnectionParametersUpdate(). + * + * @param event The connection parameters requested by the peer. + * + * @version 4.1+. + * + * @note This event is not generated if connection parameters update + * is managed by the middleware. + * + * @see manageConnectionParametersUpdateRequest() + * @see acceptConnectionParametersUpdate() + * @see rejectConnectionParametersUpdate() + */ virtual void onUpdateConnectionParametersRequest( const UpdateConnectionParametersRequestEvent &event ) { } + /** + * Called when connection parameters have been updated. + * + * @param event The new connection parameters. + * + * @see updateConnectionParameters() + * @see acceptConnectionParametersUpdate() + */ virtual void onConnectionParametersUpdateComplete( const ConnectionParametersUpdateCompleteEvent &event ) { } + /** + * Called when a connection has been disconnected. + * + * @param event Details of the event. + * + * @see disconnect() + */ virtual void onDisconnectionComplete(const DisconnectionEvent &event) { } /** @@ -107,6 +183,10 @@ public: * @param txPhy PHY used by the transmitter. * * @param rxPhy PHY used by the receiver. + * + * @see readPhy(). + * + * @version: 5+. */ virtual void onReadPhy( ble_error_t status, @@ -135,6 +215,10 @@ public: * ends have negotiated the best PHY according to their configuration and * capabilities. The PHY currently used are present in the txPhy and * rxPhy parameters. + * + * @see setPhy() + * + * @version: 5+. */ virtual void onPhyUpdateComplete( ble_error_t status, @@ -472,6 +556,17 @@ public: */ virtual ble_error_t cancelConnect(); + /** + * TODO + * @param connectionHandle + * @param minConnectionInterval + * @param maxConnectionInterval + * @param slaveLatency + * @param supervision_timeout + * @param minConnectionEventLength + * @param maxConnectionEventLength + * @return + */ virtual ble_error_t updateConnectionParameters( connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, @@ -482,10 +577,26 @@ public: conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) ); + /** + * TODO + * @param userManageConnectionUpdateRequest + * @return + */ virtual ble_error_t manageConnectionParametersUpdateRequest( bool userManageConnectionUpdateRequest ); + /** + * TODO + * @param connectionHandle + * @param minConnectionInterval + * @param maxConnectionInterval + * @param slaveLatency + * @param supervision_timeout + * @param minConnectionEventLength + * @param maxConnectionEventLength + * @return + */ virtual ble_error_t acceptConnectionParametersUpdate( connection_handle_t connectionHandle, conn_interval_t minConnectionInterval, @@ -496,6 +607,11 @@ public: conn_event_length_t maxConnectionEventLength = conn_event_length_t(0) ); + /** + * TODO + * @param connectionHandle + * @return + */ virtual ble_error_t rejectConnectionParametersUpdate( connection_handle_t connectionHandle ); From f64b37ba0dbc7954b49c4e7351e0639916aefade Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 14:28:34 +0000 Subject: [PATCH 282/361] BLE: Fix function braces opening in header files. --- features/FEATURE_BLE/ble/common/Bounded.h | 3 +- features/FEATURE_BLE/ble/common/Duration.h | 68 ++++++++++----- .../ble/gap/AdvertisingDataBuilder.h | 48 +++++++---- .../ble/gap/AdvertisingParameters.h | 3 +- .../ble/gap/ConnectionParameters.h | 6 +- features/FEATURE_BLE/ble/gap/Events.h | 39 ++++++--- features/FEATURE_BLE/ble/gap/Gap.h | 82 +++++++++++++------ features/FEATURE_BLE/ble/gap/ScanParameters.h | 9 +- features/FEATURE_BLE/ble/gap/Types.h | 75 +++++++++++------ features/FEATURE_BLE/ble/generic/GenericGap.h | 16 ++-- 10 files changed, 236 insertions(+), 113 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Bounded.h b/features/FEATURE_BLE/ble/common/Bounded.h index ea3041ab8e..87293e6808 100644 --- a/features/FEATURE_BLE/ble/common/Bounded.h +++ b/features/FEATURE_BLE/ble/common/Bounded.h @@ -56,7 +56,8 @@ struct Bounded { * * @return The current value. */ - Rep value() const { + Rep value() const + { return _value; } diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 83b138d9f4..f4bdd2f3eb 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -98,14 +98,18 @@ struct Duration { * * It is initialized with the minimum value acceptable. */ - Duration() : duration(Range::MIN) { } + Duration() : duration(Range::MIN) + { + } /** * Construct a Duration from an integer value. * * @param v The value of the duration in TN units. */ - explicit Duration(Rep v) : duration(clamp(v)) { } + explicit Duration(Rep v) : duration(clamp(v)) + { + } /** * Construct a Duration from another Duration. @@ -140,14 +144,16 @@ struct Duration { template explicit Duration(Duration other_ms, void* = NULL) : duration(clamp(((other_ms.value() * 1000) + TB - 1) / TB)) - { } + { + } /** * Return the duration in TB units. * * @return The duration in TB units. */ - Rep value() const { + Rep value() const + { return duration; } @@ -156,7 +162,8 @@ struct Duration { * * @return The duration in milliseconds. */ - uint32_t valueInMs() const { + uint32_t valueInMs() const + { return ((uint32_t)duration * TB) / 1000; } @@ -215,7 +222,8 @@ struct Duration { } private: - static Rep clamp(Rep in) { + static Rep clamp(Rep in) + { if (in < MIN) { return MIN; } else if (in > MAX) { @@ -255,7 +263,8 @@ typedef Duration second_t; * @return The converted duration. It is rounded up if precision is loss. */ template -DurationOut durationCast(Duration duration) { +DurationOut durationCast(Duration duration) +{ return DurationOut(((duration.value() * TBIn) + DurationOut::TIME_BASE - 1) / DurationOut::TIME_BASE); } @@ -286,7 +295,8 @@ template Duration operator+( Duration lhs, Duration rhs -) { +) +{ return Duration(lhs.value() + rhs.value()); } @@ -299,7 +309,8 @@ Duration operator+( * @return A duration that represents the multiplication of lhs with rhs. */ template -Duration operator*(Duration lhs, uint32_t rhs) { +Duration operator*(Duration lhs, uint32_t rhs) +{ return Duration(lhs.value() * rhs); } @@ -312,7 +323,8 @@ Duration operator*(Duration lhs, uint32_t * @return A duration that represents the multiplication of lhs with rhs. */ template -Duration operator*(uint32_t lhs, Duration rhs) { +Duration operator*(uint32_t lhs, Duration rhs) +{ return Duration(lhs * rhs.value()); } @@ -326,7 +338,8 @@ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, typename RepRHS, uint32_t TBRHS, typename RangeRHS, typename FRHS > -bool operator<(Duration lhs, Duration rhs) { +bool operator<(Duration lhs, Duration rhs) +{ return lhs.value() * lhs.TIME_BASE < rhs.value() * rhs.TIME_BASE; } @@ -337,7 +350,8 @@ bool operator<(Duration lhs, Duration -bool operator<(Duration lhs, Duration rhs) { +bool operator<(Duration lhs, Duration rhs) +{ return lhs.value() < rhs.value(); } @@ -354,7 +368,8 @@ template< bool operator<=( Duration lhs, Duration rhs -) { +) +{ return lhs.value() * lhs.TIME_BASE <= rhs.value() * rhs.TIME_BASE; } @@ -365,7 +380,8 @@ bool operator<=( * @return true if lhs is less than or equal to rhs and false otherwise. */ template -bool operator<=(Duration lhs, Duration rhs) { +bool operator<=(Duration lhs, Duration rhs) +{ return lhs.value() <= rhs.value(); } @@ -382,7 +398,8 @@ template< bool operator==( Duration lhs, Duration rhs -) { +) +{ return lhs.value() * lhs.TIME_BASE == rhs.value() * rhs.TIME_BASE; } @@ -393,7 +410,8 @@ bool operator==( * @return true if lhs is equal to rhs and false otherwise. */ template -bool operator==(Duration lhs, Duration rhs) { +bool operator==(Duration lhs, Duration rhs) +{ return lhs.value() == rhs.value(); } @@ -410,7 +428,8 @@ template< bool operator!=( Duration lhs, Duration rhs -) { +) +{ return !(lhs == rhs); } @@ -421,7 +440,8 @@ bool operator!=( * @return true if lhs is not equal to rhs and false otherwise. */ template -bool operator!=(Duration lhs, Duration rhs) { +bool operator!=(Duration lhs, Duration rhs) +{ return !(lhs == rhs); } @@ -438,7 +458,8 @@ template< bool operator>=( Duration lhs, Duration rhs -) { +) +{ return rhs <= lhs; } @@ -449,7 +470,8 @@ bool operator>=( * @return true if lhs is greater or equal to rhs and false otherwise. */ template -bool operator>=(Duration lhs, Duration rhs) { +bool operator>=(Duration lhs, Duration rhs) +{ return rhs <= lhs; } @@ -466,7 +488,8 @@ template< bool operator>( Duration lhs, Duration rhs -) { +) +{ return rhs < lhs; } @@ -477,7 +500,8 @@ bool operator>( * @return true if lhs is greater than rhs and false otherwise. */ template -bool operator>(Duration lhs, Duration rhs) { +bool operator>(Duration lhs, Duration rhs) +{ return rhs < lhs; } diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 80901cdecb..aa9ed15290 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -156,8 +156,9 @@ struct adv_data_type_t : SafeEnum { /** * Construct a new instance of adv_data_type_t. */ - adv_data_type_t(type value) : - SafeEnum(value) { } + adv_data_type_t(type value) : SafeEnum(value) + { + } }; @@ -181,9 +182,12 @@ struct adv_data_flags_t { static const uint8_t default_flags = BREDR_NOT_SUPPORTED | LE_GENERAL_DISCOVERABLE; /** Create from raw value */ - adv_data_flags_t(uint8_t value = 0) : _value(value) {}; + adv_data_flags_t(uint8_t value = 0) : _value(value) + { + } - adv_data_flags_t& setGeneralDiscoverable(bool enable = true) { + adv_data_flags_t& setGeneralDiscoverable(bool enable = true) + { _value &= ~0x03; if (enable) { _value |= LE_GENERAL_DISCOVERABLE; @@ -191,7 +195,8 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setLimitedDiscoverable(bool enable = true) { + adv_data_flags_t& setLimitedDiscoverable(bool enable = true) + { _value &= ~0x03; if (enable) { _value |= LE_LIMITED_DISCOVERABLE; @@ -199,7 +204,8 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setBredrNotSupported(bool enable = true) { + adv_data_flags_t& setBredrNotSupported(bool enable = true) + { _value &= ~BREDR_NOT_SUPPORTED; if (enable) { _value |= BREDR_NOT_SUPPORTED; @@ -207,7 +213,8 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setSimultaneousLeBredrC(bool enable = true) { + adv_data_flags_t& setSimultaneousLeBredrC(bool enable = true) + { _value &= ~SIMULTANEOUS_LE_BREDR_C; if (enable) { _value |= SIMULTANEOUS_LE_BREDR_C; @@ -215,7 +222,8 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setSimultaneousLeBredrH(bool enable = true) { + adv_data_flags_t& setSimultaneousLeBredrH(bool enable = true) + { _value &= ~SIMULTANEOUS_LE_BREDR_H; if (enable) { _value |= SIMULTANEOUS_LE_BREDR_H; @@ -223,31 +231,38 @@ struct adv_data_flags_t { return *this; } - bool getGeneralDiscoverable() { + bool getGeneralDiscoverable() + { return _value& LE_GENERAL_DISCOVERABLE; } - bool getlimitedDiscoverable() { + bool getlimitedDiscoverable() + { return _value& LE_LIMITED_DISCOVERABLE; } - bool getBrEdrNotSupported() { + bool getBrEdrNotSupported() + { return _value& BREDR_NOT_SUPPORTED; } - bool getSimultaneousLeBredrC() { + bool getSimultaneousLeBredrC() + { return _value& SIMULTANEOUS_LE_BREDR_C; } - bool getSimultaneousLeBredrH() { + bool getSimultaneousLeBredrH() + { return _value& SIMULTANEOUS_LE_BREDR_H; } - void clear() { + void clear() + { _value = 0; } - uint8_t value() { + uint8_t value() + { return _value; } @@ -519,8 +534,7 @@ struct adv_data_appearance_t : SafeEnum { /** * Construct a new instance of adv_data_appearance_t. */ - adv_data_appearance_t(type value) : - SafeEnum(value) { } + adv_data_appearance_t(type value) : SafeEnum(value) { } }; diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 11e303bf17..b4efcd3725 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -297,7 +297,8 @@ public: AdvertisingParameters &setPeer( const address_t &address, target_peer_address_type_t addressType - ) { + ) + { _peerAddress = address; _peerAddressType = addressType; return *this; diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 325264ec4c..d3d1658095 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -148,7 +148,8 @@ public: slave_latency_t slaveLatency = slave_latency_t::min(), supervision_timeout_t connectionSupervisionTimeout = supervision_timeout_t::max(), conn_event_length_t minEventLength = conn_event_length_t::min(), - conn_event_length_t maxEventLength = conn_event_length_t::max()); + conn_event_length_t maxEventLength = conn_event_length_t::max() + ); /* setters */ @@ -233,7 +234,6 @@ public: handlePhyToggle(phy_t::LE_1M, phy1M); handlePhyToggle(phy_t::LE_2M, phy2M); handlePhyToggle(phy_t::LE_CODED, phyCoded); - return *this; } @@ -247,7 +247,6 @@ public: ConnectionParameters &disablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, false); - return *this; } @@ -261,7 +260,6 @@ public: ConnectionParameters &enablePhy(phy_t phy = phy_t::LE_1M) { handlePhyToggle(phy, true); - return *this; } diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index d01233acfd..29c4a53231 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -71,7 +71,9 @@ struct AdvertisingReportEvent { periodicInterval(periodicInterval), directAddressType(directAddressType), directAddress(directAddress), - advertisingData(advertisingData) { } + advertisingData(advertisingData) + { + } #endif /** Get event type. */ @@ -205,7 +207,9 @@ struct ConnectionCompleteEvent { connectionInterval(connectionInterval), connectionLatency(connectionLatency), supervisionTimeout(supervisionTimeout), - masterClockAccuracy(masterClockAccuracy) { } + masterClockAccuracy(masterClockAccuracy) + { + } #endif /** Get connection complete event status. */ @@ -323,7 +327,9 @@ struct PeriodicAdvertisingSyncEstablishedEvent { peerAddress(peerAddress), peerPhy(peerPhy), advertisingInterval(advertisingInterval), - peerClockAccuracy(peerClockAccuracy) { } + peerClockAccuracy(peerClockAccuracy) + { + } #endif /** Get sync establishment status. */ @@ -411,7 +417,9 @@ struct PeriodicAdvertisingReportEvent { txPower(txPower), rssi(rssi), dataStatus(dataStatus), - payload(payload) { } + payload(payload) + { + } #endif /** Get periodic advertising sync handle. */ @@ -466,7 +474,9 @@ struct PeriodicAdvertisingSyncLoss { PeriodicAdvertisingSyncLoss( periodic_sync_handle_t syncHandle ) : - syncHandle(syncHandle) { } + syncHandle(syncHandle) + { + } #endif /** Get periodic sync handle. */ @@ -509,7 +519,9 @@ struct AdvertisingEndEvent { advHandle(advHandle), connection(connection), completed_events(completed_events), - connected(connected) { } + connected(connected) + { + } #endif /** Get advertising handle. */ @@ -563,7 +575,9 @@ struct ScanRequestEvent { ) : advHandle(advHandle), peerAddressType(peerAddressType), - peerAddress(peerAddress) { } + peerAddress(peerAddress) + { + } #endif /** Get advertising handle. */ @@ -600,7 +614,10 @@ struct DisconnectionEvent { DisconnectionEvent( connection_handle_t connectionHandle, const disconnection_reason_t &reason - ) : connectionHandle(connectionHandle), reason(reason) { } + ) : + connectionHandle(connectionHandle), reason(reason) + { + } #endif /** @@ -643,7 +660,8 @@ struct UpdateConnectionParametersRequestEvent { maxConnectionInterval(maxConnectionInterval), slaveLatency(slaveLatency), supervisionTimeout(supervision_timeout) - { } + { + } #endif /** @@ -713,7 +731,8 @@ struct ConnectionParametersUpdateCompleteEvent { connectionInterval(connectionInterval), slaveLatency(slaveLatency), supervisionTimeout(supervisionTimeout) - { } + { + } #endif /** diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index c23496fca8..6c7ed69edd 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -44,7 +44,9 @@ public: * * @see AdvertisingParameters::setScanRequestNotification(). */ - virtual void onScanRequestReceived(const ScanRequestEvent &event) { } + virtual void onScanRequestReceived(const ScanRequestEvent &event) + { + } /** * Called when advertising ends. @@ -58,7 +60,9 @@ public: * @see stopAdvertising() * @see onConnectionComplete() */ - virtual void onAdvertisingEnd(const AdvertisingEndEvent &event) { } + virtual void onAdvertisingEnd(const AdvertisingEndEvent &event) + { + } /** * Called when a scanner receives an advertising or a scan response packet. @@ -67,7 +71,9 @@ public: * * @see startScan() */ - virtual void onAdvertisingReport(const AdvertisingReportEvent &event) { } + virtual void onAdvertisingReport(const AdvertisingReportEvent &event) + { + } /** * Called when scan times out. @@ -76,7 +82,9 @@ public: * * @see startScan() */ - virtual void onScanTimeout(const ScanTimeoutEvent & event) { } + virtual void onScanTimeout(const ScanTimeoutEvent & event) + { + } /** * Called when first advertising packet in periodic advertising is received. @@ -89,7 +97,9 @@ public: */ virtual void onPeriodicAdvertisingSyncEstablished( const PeriodicAdvertisingSyncEstablishedEvent &event - ) { } + ) + { + } /** * Called when a periodic advertising packet is received. @@ -102,7 +112,9 @@ public: */ virtual void onPeriodicAdvertisingReport( const PeriodicAdvertisingReportEvent &event - ) { } + ) + { + } /** * Called when a periodic advertising sync has been lost. @@ -115,7 +127,9 @@ public: */ virtual void onPeriodicAdvertisingSyncLoss( const PeriodicAdvertisingSyncLoss &event - ) { } + ) + { + } /** * Called when connection attempt ends or an advertising device has been @@ -126,7 +140,9 @@ public: * * @param event Connection event. */ - virtual void onConnectionComplete(const ConnectionCompleteEvent &event) { } + virtual void onConnectionComplete(const ConnectionCompleteEvent &event) + { + } /** * Called when the peer request connection parameters updates. @@ -147,7 +163,9 @@ public: */ virtual void onUpdateConnectionParametersRequest( const UpdateConnectionParametersRequestEvent &event - ) { } + ) + { + } /** * Called when connection parameters have been updated. @@ -159,7 +177,9 @@ public: */ virtual void onConnectionParametersUpdateComplete( const ConnectionParametersUpdateCompleteEvent &event - ) { } + ) + { + } /** * Called when a connection has been disconnected. @@ -168,7 +188,9 @@ public: * * @see disconnect() */ - virtual void onDisconnectionComplete(const DisconnectionEvent &event) { } + virtual void onDisconnectionComplete(const DisconnectionEvent &event) + { + } /** * Function invoked when the current transmitter and receiver PHY have @@ -193,7 +215,9 @@ public: connection_handle_t connectionHandle, phy_t txPhy, phy_t rxPhy - ) { } + ) + { + } /** * Function invoked when the update process of the PHY has been completed. @@ -225,14 +249,18 @@ public: connection_handle_t connectionHandle, phy_t txPhy, phy_t rxPhy - ) { } + ) + { + } protected: /** * Prevent polymorphic deletion and avoid unnecessary virtual destructor * as the Gap class will never delete the instance it contains. */ - ~EventHandler() { } + ~EventHandler() + { + } }; /** @@ -714,10 +742,10 @@ protected: public: /** - * Privacy Configuration of the peripheral role. - * - * @note This configuration also applies to the broadcaster role configuration. - */ + * Privacy Configuration of the peripheral role. + * + * @note This configuration also applies to the broadcaster role configuration. + */ struct PeripheralPrivacyConfiguration_t { /** * Indicates if non resolvable random address should be used when the @@ -736,26 +764,26 @@ public: * Do not resolve the address of the initiator and accept the * connection request. */ - DO_NOT_RESOLVE, + DO_NOT_RESOLVE, /** * If a bond is present in the secure database and the address * resolution fail then reject the connection request with the error * code AUTHENTICATION_FAILLURE. */ - REJECT_NON_RESOLVED_ADDRESS, + REJECT_NON_RESOLVED_ADDRESS, /** * Perform the pairing procedure if the initiator resolvable * address failed the resolution process. */ - PERFORM_PAIRING_PROCEDURE, + PERFORM_PAIRING_PROCEDURE, /** * Perform the authentication procedure if the initiator resolvable * address failed the resolution process. */ - PERFORM_AUTHENTICATION_PROCEDURE + PERFORM_AUTHENTICATION_PROCEDURE }; /** @@ -789,14 +817,14 @@ public: /** * Do not resolve the address received in advertising packets. */ - DO_NOT_RESOLVE, + DO_NOT_RESOLVE, /** * Resolve the resolvable addresses in the advertising packet and * forward advertising packet to the application independently of * the address resolution procedure result. */ - RESOLVE_AND_FORWARD, + RESOLVE_AND_FORWARD, /** * Filter out packets containing a resolvable that cannot be resolved @@ -805,7 +833,7 @@ public: * @note Filtering is applied if the local device contains at least * one bond. */ - RESOLVE_AND_FILTER + RESOLVE_AND_FILTER }; /** @@ -906,7 +934,9 @@ protected: /** * Construct a Gap instance. */ - Gap() : _eventHandler(NULL) { } + Gap() : _eventHandler(NULL) + { + } /** * Event handler provided by the application. diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index bdd1dd6ff3..6d522fb534 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -64,7 +64,8 @@ public: phys(phy_set_t::PHY_SET_1M), phy_1m_configuration(scan_interval, scan_window, active_scanning), phy_coded_configuration() - { } + { + } ScanParameters( phy_configuration_t phy_1m_configuration, @@ -76,7 +77,8 @@ public: phys(phy_set_t::PHY_SET_1M), phy_1m_configuration(phy_1m_configuration), phy_coded_configuration() - { } + { + } ScanParameters( phy_configuration_t phy_1m_configuration, @@ -89,7 +91,8 @@ public: phys(true, false, true), phy_1m_configuration(phy_1m_configuration), phy_coded_configuration(phy_coded_configuration) - { } + { + } ScanParameters& set_own_address_type(own_address_type_t address) { diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 3e4a826a73..b3076f94c6 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -103,8 +103,9 @@ struct advertising_type_t : SafeEnum { /** * Construct a new advertising_type_t value. */ - advertising_type_t(type value) : - SafeEnum(value) { } + advertising_type_t(type value) : SafeEnum(value) + { + } }; @@ -120,17 +121,17 @@ struct advertising_data_status_t : SafeEnum(value) { } + advertising_data_status_t(type value) : SafeEnum(value) + { + } /** * Explicit constructor from a raw value. */ explicit advertising_data_status_t(uint8_t raw_value) : - SafeEnum( - static_cast(raw_value) - ) - { } + SafeEnum(static_cast(raw_value)) + { + } }; /** Properties of an advertising event. @@ -140,7 +141,9 @@ struct advertising_event_t { * * @param value */ - explicit advertising_event_t(uint8_t value) : value(value) { } + explicit advertising_event_t(uint8_t value) : value(value) + { + } /** Is advertising connectable. * @@ -277,7 +280,9 @@ struct advertising_filter_policy_t : SafeEnum /** * The whitelist is not used to determine which advertiser to connect to. */ - NO_FILTER, + NO_FILTER, /** * Whitelist is used to determine which advertiser to connect to. */ - USE_WHITE_LIST + USE_WHITE_LIST }; - initiator_filter_policy_t(type value) : SafeEnum(value) { } + initiator_filter_policy_t(type value) : SafeEnum(value) + { + } }; /** @@ -373,7 +380,9 @@ struct duplicates_filter_t : SafeEnum{ /** * Construct a new duplicates_filter_t value. */ - duplicates_filter_t(type value) : SafeEnum(value) { } + duplicates_filter_t(type value) : SafeEnum(value) + { + } }; /** @@ -412,7 +421,9 @@ struct own_address_type_t : SafeEnum { /** * Construct a new instance of own_address_type_t. */ - own_address_type_t(type value) : SafeEnum(value) { } + own_address_type_t(type value) : SafeEnum(value) + { + } }; struct target_peer_address_type_t : SafeEnum { @@ -423,13 +434,15 @@ struct target_peer_address_type_t : SafeEnum{ +struct clock_accuracy_t : SafeEnum { enum type { /** * 500 PPM @@ -476,7 +489,8 @@ struct clock_accuracy_t : SafeEnum{ * * @return Parts per million as a number. */ - uint16_t get_ppm() { + uint16_t get_ppm() + { switch(value()) { case PPM_500: return 500; case PPM_250: return 250; @@ -493,13 +507,17 @@ struct clock_accuracy_t : SafeEnum{ /** * Construct a new clock_accuracy_t value. */ - clock_accuracy_t(type value) : SafeEnum(value) { } + clock_accuracy_t(type value) : SafeEnum(value) + { + } /** * Construct a new clock_accuracy_t value from a raw value. * @param raw_value The value of the clock accuracy. */ - explicit clock_accuracy_t(uint8_t raw_value) : SafeEnum(raw_value) { } + explicit clock_accuracy_t(uint8_t raw_value) : SafeEnum(raw_value) + { + } }; /** @@ -546,13 +564,18 @@ struct connection_role_t :SafeEnum { /** * Construct a new instance of role_t. */ - connection_role_t(type value) : SafeEnum(value) { } + connection_role_t(type value) : SafeEnum(value) + { + } + /** * Explicit constructor from a raw value. * @param raw_value The role. */ - explicit connection_role_t(uint8_t raw_value) : SafeEnum(raw_value) { } + explicit connection_role_t(uint8_t raw_value) : SafeEnum(raw_value) + { + } }; /** @@ -604,7 +627,9 @@ struct local_disconnection_reason_t : SafeEnum { /** * Construct a new instance of disconnection_reason_t. */ - disconnection_reason_t(type value) : SafeEnum(value) { } + disconnection_reason_t(type value) : SafeEnum(value) + { + } }; diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index ecd38e24c0..e5147dfc43 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -732,19 +732,24 @@ private: template struct BitArray { - BitArray() : data() { } + BitArray() : data() + { + } - bool get(size_t index) const { + bool get(size_t index) const + { position p(index); return (data[p.byte_index] >> p.bit_index) & 0x01; } - void set(size_t index) { + void set(size_t index) + { position p(index); data[p.byte_index] |= (0x01 << p.bit_index); } - void clear(size_t index) { + void clear(size_t index) + { position p(index); data[p.byte_index] &= ~(0x01 << p.bit_index); } @@ -754,7 +759,8 @@ private: position(size_t bit_number) : byte_index(bit_number / 8), bit_index(bit_number % 8) - { } + { + } size_t byte_index; uint8_t bit_index; From b49870d8aecd1a2f353e0e1aac4de233c5fcf230 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 14:59:42 +0000 Subject: [PATCH 283/361] BLE: Fix code formating issues in Gap subsystem. --- features/FEATURE_BLE/ble/BLE.h | 198 +++++++----- features/FEATURE_BLE/ble/Gap.h | 214 ++++++------- .../ble/gap/AdvertisingDataBuilder.h | 41 +-- .../ble/gap/AdvertisingParameters.h | 4 +- .../ble/gap/ConnectionParameters.h | 2 +- features/FEATURE_BLE/ble/gap/Events.h | 20 ++ features/FEATURE_BLE/ble/gap/Gap.h | 12 +- features/FEATURE_BLE/ble/gap/ScanParameters.h | 10 +- features/FEATURE_BLE/ble/gap/Types.h | 43 +-- features/FEATURE_BLE/ble/generic/GenericGap.h | 25 +- features/FEATURE_BLE/ble/pal/GapTypes.h | 109 ++++--- features/FEATURE_BLE/ble/pal/PalGap.h | 82 ++--- .../source/gap/AdvertisingDataBuilder.cpp | 124 +++++--- .../source/gap/ConnectionParameters.cpp | 4 +- features/FEATURE_BLE/source/gap/Gap.cpp | 81 +++-- .../FEATURE_BLE/source/generic/GenericGap.cpp | 285 ++++++++++-------- 16 files changed, 741 insertions(+), 513 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index ef4cfe9e58..cd38d315b4 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -28,7 +28,9 @@ #ifdef YOTTA_CFG_MBED_OS #include "mbed-drivers/mbed_error.h" #else + #include "platform/mbed_error.h" + #endif #include "platform/mbed_toolchain.h" @@ -132,8 +134,7 @@ class BLEInstanceBase; * } * @endcode */ -class BLE -{ +class BLE { public: /** * Opaque type used to store the ID of a BLE instance. @@ -178,7 +179,8 @@ public: * * @return Instance id of this BLE instance. */ - InstanceID_t getInstanceID(void) const { + InstanceID_t getInstanceID(void) const + { return instanceID; } @@ -192,13 +194,13 @@ public: /** * The ble instance which have events to process. */ - BLE& ble; + BLE &ble; }; /** * Events to process event handler */ - typedef FunctionPointerWithContext + typedef FunctionPointerWithContext OnEventsToProcessCallback_t; /** @@ -209,7 +211,7 @@ public: * * @param on_event_cb Callback invoked when there are new events to process. */ - void onEventsToProcess(const OnEventsToProcessCallback_t& on_event_cb); + void onEventsToProcess(const OnEventsToProcessCallback_t &on_event_cb); /** * Process ALL pending events living in the BLE stack and return once all @@ -229,7 +231,7 @@ public: /** * Reference to the BLE object that has been initialized */ - BLE& ble; + BLE &ble; /** * Error status of the initialization. @@ -283,7 +285,8 @@ public: * @attention This should be called before using anything else in the BLE * API. */ - ble_error_t init(InitializationCompleteCallback_t completion_cb = NULL) { + ble_error_t init(InitializationCompleteCallback_t completion_cb = NULL) + { FunctionPointerWithContext callback(completion_cb); return initImplementation(callback); } @@ -299,7 +302,8 @@ public: * initialization is complete. */ template - ble_error_t init(T *object, void (T::*completion_cb)(InitializationCompleteCallbackContext *context)) { + ble_error_t init(T *object, void (T::*completion_cb)(InitializationCompleteCallbackContext *context)) + { FunctionPointerWithContext callback(object, completion_cb); return initImplementation(callback); } @@ -357,7 +361,7 @@ public: * * @return A reference to a GattServer object associated to this BLE instance. */ - GattServer& gattServer(); + GattServer &gattServer(); /** * A const alternative to gattServer(). @@ -365,7 +369,7 @@ public: * @return A const reference to a GattServer object associated to this BLE * instance. */ - const GattServer& gattServer() const; + const GattServer &gattServer() const; /** * Accessors to GattClient. All GattClient related functionality requires @@ -373,7 +377,7 @@ public: * * @return A reference to a GattClient object associated to this BLE instance. */ - GattClient& gattClient(); + GattClient &gattClient(); /** * A const alternative to gattClient(). @@ -381,7 +385,7 @@ public: * @return A const reference to a GattClient object associated to this BLE * instance. */ - const GattClient& gattClient() const; + const GattClient &gattClient() const; /** * Accessors to SecurityManager. All SecurityManager-related functionality @@ -390,7 +394,7 @@ public: * @return A reference to a SecurityManager object associated to this BLE * instance. */ - SecurityManager& securityManager(); + SecurityManager &securityManager(); /** * A const alternative to securityManager(). @@ -398,7 +402,7 @@ public: * @return A const reference to a SecurityManager object associated to this * BLE instance. */ - const SecurityManager& securityManager() const; + const SecurityManager &securityManager() const; /** * Translate error code into a printable string. @@ -407,7 +411,7 @@ public: * * @return A pointer to a const string describing the error. */ - static const char* errorToString(ble_error_t error); + static const char *errorToString(ble_error_t error); /* * Deprecation alert! @@ -471,7 +475,8 @@ public: MBED_DEPRECATED("Use ble.gap().getAddress(...)") ble_error_t getAddress( BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address - ) { + ) + { return gap().getAddress(typeP, address); } @@ -524,7 +529,8 @@ public: * ble.gap().getMinAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMinAdvertisingInterval(...)") - uint16_t getMinAdvertisingInterval(void) const { + uint16_t getMinAdvertisingInterval(void) const + { return gap().getMinAdvertisingInterval(); } @@ -537,7 +543,8 @@ public: * ble.gap().getMinNonConnectableAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMinNonConnectableAdvertisingInterval(...)") - uint16_t getMinNonConnectableAdvertisingInterval(void) const { + uint16_t getMinNonConnectableAdvertisingInterval(void) const + { return gap().getMinNonConnectableAdvertisingInterval(); } @@ -550,7 +557,8 @@ public: * ble.gap().getMaxAdvertisingInterval(...). */ MBED_DEPRECATED("Use ble.gap().getMaxAdvertisingInterval(...)") - uint16_t getMaxAdvertisingInterval(void) const { + uint16_t getMaxAdvertisingInterval(void) const + { return gap().getMaxAdvertisingInterval(); } @@ -801,10 +809,12 @@ public: * ble.gap().setScanParams(...). */ MBED_DEPRECATED("Use ble.gap().setScanParams(...)") - ble_error_t setScanParams(uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, - uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, - uint16_t timeout = 0, - bool activeScanning = false); + ble_error_t setScanParams( + uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX, + uint16_t window = GapScanningParams::SCAN_WINDOW_MAX, + uint16_t timeout = 0, + bool activeScanning = false + ); /** * Set up the scanInterval parameter for GAP scanning (observer mode). @@ -934,7 +944,8 @@ public: * ble.gap().stopScan(). */ MBED_DEPRECATED("Use ble.gap().stopScan()") - ble_error_t stopScan(void) { + ble_error_t stopScan(void) + { return gap().stopScan(); } @@ -958,10 +969,12 @@ public: * ble.gap().connect(...). */ MBED_DEPRECATED("Use ble.gap().connect(...)") - ble_error_t connect(const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t peerAddrType = BLEProtocol::AddressType::RANDOM_STATIC, - const Gap::ConnectionParams_t *connectionParams = NULL, - const GapScanningParams *scanParams = NULL); + ble_error_t connect( + const BLEProtocol::AddressBytes_t peerAddr, + BLEProtocol::AddressType_t peerAddrType = BLEProtocol::AddressType::RANDOM_STATIC, + const Gap::ConnectionParams_t *connectionParams = NULL, + const GapScanningParams *scanParams = NULL + ); /** * This call initiates the disconnection procedure, and its completion is @@ -1025,7 +1038,8 @@ public: * ble.gap().getPreferredConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().getPreferredConnectionParams(...)") - ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params) { + ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params) + { return gap().getPreferredConnectionParams(params); } @@ -1043,7 +1057,8 @@ public: * ble.gap().setPreferredConnectionParams(). */ MBED_DEPRECATED("Use ble.gap().setPreferredConnectionParams(...)") - ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params) { + ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params) + { return gap().setPreferredConnectionParams(params); } @@ -1076,7 +1091,8 @@ public: * ble.gap().setDeviceName(). */ MBED_DEPRECATED("Use ble.gap().setDeviceName(...)") - ble_error_t setDeviceName(const uint8_t *deviceName) { + ble_error_t setDeviceName(const uint8_t *deviceName) + { return gap().setDeviceName(deviceName); } @@ -1104,7 +1120,8 @@ public: * ble.gap().getDeviceName(). */ MBED_DEPRECATED("Use ble.gap().getDeviceName(...)") - ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) { + ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) + { return gap().getDeviceName(deviceName, lengthP); } @@ -1119,7 +1136,8 @@ public: * ble.gap().setAppearance(). */ MBED_DEPRECATED("Use ble.gap().setAppearance(...)") - ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) { + ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) + { return gap().setAppearance(appearance); } @@ -1134,7 +1152,8 @@ public: * ble.gap().getAppearance(). */ MBED_DEPRECATED("Use ble.gap().getAppearance(...)") - ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) { + ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) + { return gap().getAppearance(appearanceP); } @@ -1176,7 +1195,8 @@ public: * ble.gattServer().addService(). */ MBED_DEPRECATED("Use ble.gattServer().addService(...)") - ble_error_t addService(GattService &service) { + ble_error_t addService(GattService &service) + { return gattServer().addService(service); } @@ -1201,7 +1221,8 @@ public: * ble.gattServer().read(). */ MBED_DEPRECATED("Use ble.gattServer().read(...)") - ble_error_t readCharacteristicValue(GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) { + ble_error_t readCharacteristicValue(GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) + { return gattServer().read(attributeHandle, buffer, lengthP); } @@ -1232,7 +1253,13 @@ public: * ble.gattServer().read(). */ MBED_DEPRECATED("Use ble.gattServer().read(...)") - ble_error_t readCharacteristicValue(Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) { + ble_error_t readCharacteristicValue( + Gap::Handle_t connectionHandle, + GattAttribute::Handle_t attributeHandle, + uint8_t *buffer, + uint16_t *lengthP + ) + { return gattServer().read(connectionHandle, attributeHandle, buffer, lengthP); } @@ -1260,10 +1287,13 @@ public: * ble.gattServer().write(). */ MBED_DEPRECATED("Use ble.gattServer().write(...)") - ble_error_t updateCharacteristicValue(GattAttribute::Handle_t attributeHandle, - const uint8_t *value, - uint16_t size, - bool localOnly = false) { + ble_error_t updateCharacteristicValue( + GattAttribute::Handle_t attributeHandle, + const uint8_t *value, + uint16_t size, + bool localOnly = false + ) + { return gattServer().write(attributeHandle, value, size, localOnly); } @@ -1295,11 +1325,14 @@ public: * ble.gattServer().write(). */ MBED_DEPRECATED("Use ble.gattServer().write(...)") - ble_error_t updateCharacteristicValue(Gap::Handle_t connectionHandle, - GattAttribute::Handle_t attributeHandle, - const uint8_t *value, - uint16_t size, - bool localOnly = false) { + ble_error_t updateCharacteristicValue( + Gap::Handle_t connectionHandle, + GattAttribute::Handle_t attributeHandle, + const uint8_t *value, + uint16_t size, + bool localOnly = false + ) + { return gattServer().write(connectionHandle, attributeHandle, value, size, localOnly); } @@ -1324,10 +1357,13 @@ public: * ble.securityManager().init(...). */ MBED_DEPRECATED("Use ble.gattServer().write(...)") - ble_error_t initializeSecurity(bool enableBonding = true, - bool requireMITM = true, - SecurityManager::SecurityIOCapabilities_t iocaps = SecurityManager::IO_CAPS_NONE, - const SecurityManager::Passkey_t passkey = NULL) { + ble_error_t initializeSecurity( + bool enableBonding = true, + bool requireMITM = true, + SecurityManager::SecurityIOCapabilities_t iocaps = SecurityManager::IO_CAPS_NONE, + const SecurityManager::Passkey_t passkey = NULL + ) + { return securityManager().init(enableBonding, requireMITM, iocaps, passkey); } @@ -1345,7 +1381,8 @@ public: * ble.securityManager().getLinkSecurity(...). */ MBED_DEPRECATED("ble.securityManager().getLinkSecurity(...)") - ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP) { + ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP) + { return securityManager().getLinkSecurity(connectionHandle, securityStatusP); } @@ -1363,7 +1400,8 @@ public: * ble.securityManager().purgeAllBondingState(). */ MBED_DEPRECATED("ble.securityManager().purgeAllBondingState(...)") - ble_error_t purgeAllBondingState(void) { + ble_error_t purgeAllBondingState(void) + { return securityManager().purgeAllBondingState(); } @@ -1412,7 +1450,8 @@ public: */ template MBED_DEPRECATED("ble.gap().onDisconnectionComplete(callback)") - void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t*)) { + void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t *)) + { gap().onDisconnection(tptr, mptr); } @@ -1457,7 +1496,8 @@ public: * ble.gattServer().onDataSent(...). */ MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(void (*callback)(unsigned count)) { + void onDataSent(void (*callback)(unsigned count)) + { gattServer().onDataSent(callback); } @@ -1470,9 +1510,10 @@ public: * to ble.onDataSent(...) should be replaced with * ble.gattServer().onDataSent(...). */ - template + template MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(T * objPtr, void (T::*memberPtr)(unsigned count)) { + void onDataSent(T *objPtr, void (T::*memberPtr)(unsigned count)) + { gattServer().onDataSent(objPtr, memberPtr); } @@ -1497,7 +1538,8 @@ public: * ble.gattServer().onDataWritten(...). */ MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(void (*callback)(const GattWriteCallbackParams *eventDataP)) { + void onDataWritten(void (*callback)(const GattWriteCallbackParams *eventDataP)) + { gattServer().onDataWritten(callback); } @@ -1510,9 +1552,10 @@ public: * to ble.onDataWritten(...) should be replaced with * ble.gattServer().onDataWritten(...). */ - template + template MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(T * objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context)) { + void onDataWritten(T *objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context)) + { gattServer().onDataWritten(objPtr, memberPtr); } @@ -1541,7 +1584,8 @@ public: * ble.gattServer().onDataRead(...). */ MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(void (*callback)(const GattReadCallbackParams *eventDataP)) { + ble_error_t onDataRead(void (*callback)(const GattReadCallbackParams *eventDataP)) + { return gattServer().onDataRead(callback); } @@ -1554,9 +1598,10 @@ public: * to ble.onDataRead(...) should be replaced with * ble.gattServer().onDataRead(...). */ - template + template MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(T * objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context)) { + ble_error_t onDataRead(T *objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context)) + { return gattServer().onDataRead(objPtr, memberPtr); } @@ -1570,7 +1615,8 @@ public: * ble.gattServer().onUpdatesEnabled(callback). */ MBED_DEPRECATED("ble.gattServer().onUpdatesEnabled(...)") - void onUpdatesEnabled(GattServer::EventCallback_t callback) { + void onUpdatesEnabled(GattServer::EventCallback_t callback) + { gattServer().onUpdatesEnabled(callback); } @@ -1584,7 +1630,8 @@ public: * ble.gattServer().onUpdatesDisabled(callback). */ MBED_DEPRECATED("ble.gattServer().onUpdatesDisabled(...)") - void onUpdatesDisabled(GattServer::EventCallback_t callback) { + void onUpdatesDisabled(GattServer::EventCallback_t callback) + { gattServer().onUpdatesDisabled(callback); } @@ -1598,7 +1645,8 @@ public: * ble.gattServer().onConfirmationReceived(callback). */ MBED_DEPRECATED("ble.gattServer().onConfirmationReceived(...)") - void onConfirmationReceived(GattServer::EventCallback_t callback) { + void onConfirmationReceived(GattServer::EventCallback_t callback) + { gattServer().onConfirmationReceived(callback); } @@ -1615,7 +1663,8 @@ public: * ble.securityManager().onSecuritySetupInitiated(callback). */ MBED_DEPRECATED("ble.securityManager().onSecuritySetupInitiated(callback)") - void onSecuritySetupInitiated(SecurityManager::SecuritySetupInitiatedCallback_t callback) { + void onSecuritySetupInitiated(SecurityManager::SecuritySetupInitiatedCallback_t callback) + { securityManager().onSecuritySetupInitiated(callback); } @@ -1631,7 +1680,8 @@ public: * ble.securityManager().onSecuritySetupCompleted(callback). */ MBED_DEPRECATED("ble.securityManager().onSecuritySetupCompleted(callback)") - void onSecuritySetupCompleted(SecurityManager::SecuritySetupCompletedCallback_t callback) { + void onSecuritySetupCompleted(SecurityManager::SecuritySetupCompletedCallback_t callback) + { securityManager().onSecuritySetupCompleted(callback); } @@ -1649,7 +1699,8 @@ public: * ble.securityManager().onLinkSecured(callback). */ MBED_DEPRECATED("ble.securityManager().onLinkSecured(callback)") - void onLinkSecured(SecurityManager::LinkSecuredCallback_t callback) { + void onLinkSecured(SecurityManager::LinkSecuredCallback_t callback) + { securityManager().onLinkSecured(callback); } @@ -1663,7 +1714,8 @@ public: * ble.securityManager().onSecurityContextStored(callback). */ MBED_DEPRECATED("ble.securityManager().onSecurityContextStored(callback)") - void onSecurityContextStored(SecurityManager::HandleSpecificEvent_t callback) { + void onSecurityContextStored(SecurityManager::HandleSpecificEvent_t callback) + { securityManager().onSecurityContextStored(callback); } @@ -1680,7 +1732,8 @@ public: * ble.securityManager().onPasskeyDisplay(callback). */ MBED_DEPRECATED("ble.securityManager().onPasskeyDisplay(callback)") - void onPasskeyDisplay(SecurityManager::PasskeyDisplayCallback_t callback) { + void onPasskeyDisplay(SecurityManager::PasskeyDisplayCallback_t callback) + { return securityManager().onPasskeyDisplay(callback); } @@ -1708,7 +1761,8 @@ private: private: // Prevent copy construction and copy assignment of BLE. - BLE(const BLE&); + BLE(const BLE &); + BLE &operator=(const BLE &); private: diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 010da0b09a..73ca26617e 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -739,7 +739,7 @@ public: /** * Connection parameters. */ - const ConnectionParams_t *connectionParams; + const ConnectionParams_t *connectionParams; /** * Resolvable address used by the peer. @@ -865,13 +865,14 @@ public: DisconnectionReason_t reasonIn ) : handle(handleIn), reason(reasonIn) - {} + { + } }; /** * Number of microseconds in 1.25 milliseconds. */ - static const uint16_t UNIT_1_25_MS = 1250; + static const uint16_t UNIT_1_25_MS = 1250; /** * Convert milliseconds into 1.25ms units. @@ -924,7 +925,7 @@ public: * * @see Gap::onDisconnection(). */ - typedef FunctionPointerWithContext + typedef FunctionPointerWithContext DisconnectionEventCallback_t; /** @@ -932,7 +933,7 @@ public: * * @see Gap::onDisconnection(). */ - typedef CallChainOfFunctionPointersWithContext + typedef CallChainOfFunctionPointersWithContext DisconnectionEventCallbackChain_t; /** @@ -1033,7 +1034,7 @@ public: */ static ble_error_t getRandomAddressType( const BLEProtocol::AddressBytes_t address, - RandomAddressType_t* addressType + RandomAddressType_t *addressType ); /** @@ -1088,9 +1089,9 @@ public: * Use stopAdvertising(advertising_handle_t). */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use stopAdvertising(advertising_handle_t) instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use stopAdvertising(advertising_handle_t) instead." ) virtual ble_error_t stopAdvertising(void); @@ -1232,7 +1233,7 @@ public: virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) { /* Avoid compiler warnings about unused variables. */ - (void)params; + (void) params; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1254,9 +1255,10 @@ public: */ virtual ble_error_t setPreferredConnectionParams( const ConnectionParams_t *params - ) { + ) + { /* Avoid compiler warnings about unused variables. */ - (void)params; + (void) params; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1301,9 +1303,10 @@ public: * * @return BLE_ERROR_NONE if the device name was set correctly. */ - virtual ble_error_t setDeviceName(const uint8_t *deviceName) { + virtual ble_error_t setDeviceName(const uint8_t *deviceName) + { /* Avoid compiler warnings about unused variables. */ - (void)deviceName; + (void) deviceName; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1335,8 +1338,8 @@ public: virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) { /* avoid compiler warnings about unused variables */ - (void)deviceName; - (void)lengthP; + (void) deviceName; + (void) lengthP; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1353,7 +1356,7 @@ public: virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) { /* Avoid compiler warnings about unused variables. */ - (void)appearance; + (void) appearance; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1371,7 +1374,7 @@ public: virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) { /* Avoid compiler warnings about unused variables. */ - (void)appearanceP; + (void) appearanceP; /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -1390,9 +1393,9 @@ public: * See ble::AdvertisingParameters and setAdvertisingParameters. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "See ble::AdvertisingParameters and setAdvertisingParameters." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "See ble::AdvertisingParameters and setAdvertisingParameters." ) virtual ble_error_t setTxPower(int8_t txPower); @@ -1467,9 +1470,9 @@ public: * This setting is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "This setting is now part of ble::AdvertisingParameters." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "This setting is now part of ble::AdvertisingParameters." ) virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode); @@ -1518,8 +1521,8 @@ public: * @deprecated Deprecated since addition of extended advertising support. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." ) virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const; @@ -1586,9 +1589,9 @@ public: * isAdvertisingActive() and getConnectionCount(). */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use isAdvertisingActive() and getConnectionCount()." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use isAdvertisingActive() and getConnectionCount()." ) GapState_t getState(void) const; @@ -1601,9 +1604,9 @@ public: * This option is now part of ble::AdvertisingParameters. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "This option is now part of ble::AdvertisingParameters" + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "This option is now part of ble::AdvertisingParameters" ) void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType); @@ -1660,9 +1663,9 @@ public: * Use startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use startAdvertising(advertising_handle_t, adv_duration_t, uint8_t) instead." ) ble_error_t startAdvertising(void); @@ -1674,10 +1677,10 @@ public: * bool). */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use setAdvertisingPayload(ble::advertising_handle_t, mbed::Span," - "bool)." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setAdvertisingPayload(ble::advertising_handle_t, mbed::Span," + "bool)." ) void clearAdvertisingPayload(void); @@ -1703,9 +1706,9 @@ public: * Use ble::AdvertisingDataBuilder. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateAdvertisingPayload(uint8_t flags); @@ -1731,9 +1734,9 @@ public: * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app); @@ -1759,9 +1762,9 @@ public: * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power); @@ -1795,9 +1798,9 @@ public: * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len @@ -1831,9 +1834,9 @@ public: * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - " Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + " Use ble::AdvertisingDataBuilder instead." ) ble_error_t updateAdvertisingPayload( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len @@ -1852,9 +1855,9 @@ public: * Use ble::AdvertisingDataBuilder instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload); @@ -1866,8 +1869,8 @@ public: * @deprecated Deprecated since addition of extended advertising support. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." ) const GapAdvertisingData &getAdvertisingPayload(void) const; @@ -1885,9 +1888,9 @@ public: * Use createAdvertisingSet(). */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use ble::AdvertisingDataBuilder instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use ble::AdvertisingDataBuilder instead." ) ble_error_t accumulateScanResponse( GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len @@ -1903,9 +1906,9 @@ public: * Use setAdvertisingScanResponse(). */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Use setAdvertisingScanResponse() instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Use setAdvertisingScanResponse() instead." ) void clearScanResponse(void); @@ -1974,7 +1977,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setScanParameters(const ScanParameters &) instead." ) - ble_error_t setScanParams(const GapScanningParams& scanningParams); + ble_error_t setScanParams(const GapScanningParams &scanningParams); /** * Set the interval parameter used during scanning procedures. @@ -2157,9 +2160,9 @@ private: * Implement setAdvertisingPayload() and setAdvertisingScanResponse() instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Implement setAdvertisingPayload() and setAdvertisingScanResponse() instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Implement setAdvertisingPayload() and setAdvertisingScanResponse() instead." ) virtual ble_error_t setAdvertisingData( const GapAdvertisingData &advData, @@ -2181,10 +2184,10 @@ private: * instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support. " - "Implement startAdvertising(advertising_handle_t, adv_duration_t, uint8_t)" - "instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support. " + "Implement startAdvertising(advertising_handle_t, adv_duration_t, uint8_t)" + "instead." ) virtual ble_error_t startAdvertising(const GapAdvertisingParams ¶ms) = 0; @@ -2197,8 +2200,8 @@ public: * @deprecated Deprecated since addition of extended advertising support. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." ) GapAdvertisingParams &getAdvertisingParams(void); @@ -2210,8 +2213,8 @@ public: * @deprecated Deprecated since addition of extended advertising support. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." ) const GapAdvertisingParams &getAdvertisingParams(void) const; @@ -2224,9 +2227,9 @@ public: * Use setAdvertisingParameters() instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.11.0", - "Deprecated since addition of extended advertising support." - "Use setAdvertisingParameters() instead." + "mbed-os-5.11.0", + "Deprecated since addition of extended advertising support." + "Use setAdvertisingParameters() instead." ) void setAdvertisingParams(const GapAdvertisingParams &newParams); @@ -2269,7 +2272,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setEventHandler() instead." ) - TimeoutEventCallbackChain_t& onTimeout(); + TimeoutEventCallbackChain_t &onTimeout(); /** * Register a callback handling connection events. @@ -2305,7 +2308,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setEventHandler() instead." ) - void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)); + void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t *)); /** * Get the callchain of registered connection event handlers. @@ -2324,7 +2327,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setEventHandler() instead." ) - ConnectionEventCallbackChain_t& onConnection(); + ConnectionEventCallbackChain_t &onConnection(); /** * Register a callback handling disconnection events. @@ -2360,7 +2363,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setEventHandler() instead." ) - void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)); + void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t *)); /** * Get the callchain of registered disconnection event handlers. @@ -2379,7 +2382,7 @@ public: "Deprecated since addition of extended advertising support. " "Use setEventHandler() instead." ) - DisconnectionEventCallbackChain_t& onDisconnection(); + DisconnectionEventCallbackChain_t &onDisconnection(); /** * Set the radio-notification events handler. @@ -2416,7 +2419,7 @@ public: * @deprecated Deprecated since addition of extended advertising support. * Use setEventHandler() instead. */ - template + template MBED_DEPRECATED_SINCE( "mbed-os-5.11.0", "Deprecated since addition of extended advertising support. " @@ -2435,7 +2438,7 @@ public: * @note To unregister a shutdown event handler, use * onShutdown().detach(callback). */ - void onShutdown(const GapShutdownCallback_t& callback); + void onShutdown(const GapShutdownCallback_t &callback); /** * Register a Gap shutdown event handler. @@ -2443,7 +2446,7 @@ public: * @param[in] objPtr Instance used to invoke @p memberPtr. * @param[in] memberPtr Shutdown event handler to register. */ - template + template void onShutdown(T *objPtr, void (T::*memberPtr)(const Gap *)) { shutdownCallChain.add(objPtr, memberPtr); @@ -2458,7 +2461,7 @@ public: * * @return A reference to the shutdown event callback chain. */ - GapShutdownCallbackChain_t& onShutdown(); + GapShutdownCallbackChain_t &onShutdown(); public: /** @@ -2487,8 +2490,8 @@ public: /* Clear Gap state */ state.advertising = 0; - state.connected = 0; - connectionCount = 0; + state.connected = 0; + connectionCount = 0; /* Clear scanning state */ scanningActive = false; @@ -2502,7 +2505,7 @@ public: connectionCallChain.clear(); disconnectionCallChain.clear(); radioNotificationCallback = NULL; - onAdvertisementReport = NULL; + onAdvertisementReport = NULL; _eventHandler = NULL; return BLE_ERROR_NONE; @@ -2524,7 +2527,8 @@ protected: radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), - disconnectionCallChain() { + disconnectionCallChain() + { _advPayload.clear(); _scanResponse.clear(); } @@ -2591,9 +2595,9 @@ public: * instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." ) void processConnectionEvent( Handle_t handle, @@ -2692,9 +2696,9 @@ public: * instead. */ MBED_DEPRECATED_SINCE( - "mbed-os-5.9.0", - "The type BLEProtocol::AddressType_t is not suitable when privacy is " - "enabled. Use the overload that accepts a PeerAddressType_t instead." + "mbed-os-5.9.0", + "The type BLEProtocol::AddressType_t is not suitable when privacy is " + "enabled. Use the overload that accepts a PeerAddressType_t instead." ) void processAdvertisementReport( const BLEProtocol::AddressBytes_t peerAddr, @@ -2810,7 +2814,8 @@ private: private: /* Disallow copy and assignment. */ Gap(const Gap &); - Gap& operator=(const Gap &); + + Gap &operator=(const Gap &); }; /** @@ -2832,7 +2837,8 @@ template ble_error_t Gap::startScan( T *object, void (T::*callbackMember)(const AdvertisementCallbackParams_t *params) -) { +) +{ ble_error_t err = BLE_ERROR_NONE; if (object && callbackMember) { if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) { @@ -2846,18 +2852,18 @@ ble_error_t Gap::startScan( template -void Gap::onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) +void Gap::onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t *)) { connectionCallChain.add(tptr, mptr); } template -void Gap::onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) +void Gap::onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t *)) { disconnectionCallChain.add(tptr, mptr); } -template +template void Gap::onRadioNotification(T *tptr, void (T::*mptr)(bool)) { radioNotificationCallback.attach(tptr, mptr); diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index aa9ed15290..05af4b2a82 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -174,7 +174,7 @@ struct adv_data_flags_t { enum { LE_LIMITED_DISCOVERABLE = 0x01, /**< Discoverable for a limited period of time.*/ LE_GENERAL_DISCOVERABLE = 0x02, /**< Discoverable at any moment. */ - BREDR_NOT_SUPPORTED = 0x04, /**< LE only and does not support Bluetooth Enhanced DataRate. */ + BREDR_NOT_SUPPORTED = 0x04, /**< LE only and does not support Bluetooth Enhanced DataRate. */ SIMULTANEOUS_LE_BREDR_C = 0x08, /**< Not relevant - dual mode only. */ SIMULTANEOUS_LE_BREDR_H = 0x10 /**< Not relevant - dual mode only. */ }; @@ -186,7 +186,7 @@ struct adv_data_flags_t { { } - adv_data_flags_t& setGeneralDiscoverable(bool enable = true) + adv_data_flags_t &setGeneralDiscoverable(bool enable = true) { _value &= ~0x03; if (enable) { @@ -195,7 +195,7 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setLimitedDiscoverable(bool enable = true) + adv_data_flags_t &setLimitedDiscoverable(bool enable = true) { _value &= ~0x03; if (enable) { @@ -204,7 +204,7 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setBredrNotSupported(bool enable = true) + adv_data_flags_t &setBredrNotSupported(bool enable = true) { _value &= ~BREDR_NOT_SUPPORTED; if (enable) { @@ -213,7 +213,7 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setSimultaneousLeBredrC(bool enable = true) + adv_data_flags_t &setSimultaneousLeBredrC(bool enable = true) { _value &= ~SIMULTANEOUS_LE_BREDR_C; if (enable) { @@ -222,7 +222,7 @@ struct adv_data_flags_t { return *this; } - adv_data_flags_t& setSimultaneousLeBredrH(bool enable = true) + adv_data_flags_t &setSimultaneousLeBredrH(bool enable = true) { _value &= ~SIMULTANEOUS_LE_BREDR_H; if (enable) { @@ -233,27 +233,27 @@ struct adv_data_flags_t { bool getGeneralDiscoverable() { - return _value& LE_GENERAL_DISCOVERABLE; + return _value & LE_GENERAL_DISCOVERABLE; } bool getlimitedDiscoverable() { - return _value& LE_LIMITED_DISCOVERABLE; + return _value & LE_LIMITED_DISCOVERABLE; } bool getBrEdrNotSupported() { - return _value& BREDR_NOT_SUPPORTED; + return _value & BREDR_NOT_SUPPORTED; } bool getSimultaneousLeBredrC() { - return _value& SIMULTANEOUS_LE_BREDR_C; + return _value & SIMULTANEOUS_LE_BREDR_C; } bool getSimultaneousLeBredrH() { - return _value& SIMULTANEOUS_LE_BREDR_H; + return _value & SIMULTANEOUS_LE_BREDR_H; } void clear() @@ -534,12 +534,13 @@ struct adv_data_appearance_t : SafeEnum { /** * Construct a new instance of adv_data_appearance_t. */ - adv_data_appearance_t(type value) : SafeEnum(value) { } + adv_data_appearance_t(type value) : SafeEnum(value) + { + } }; -class AdvertisingDataBuilder -{ +class AdvertisingDataBuilder { public: /** Advertising data needs a user provided buffer to store the data. * @@ -554,7 +555,7 @@ public: * @param buffer_size Size of the buffer. * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. */ - AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size); + AdvertisingDataBuilder(uint8_t *buffer, size_t buffer_size); /** * Get the subspan of the buffer containing valid data. @@ -724,7 +725,7 @@ public: * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. * @retval BLE_ERROR_INVALID_PARAM if size of data is too big too fit in an individual data field. */ - ble_error_t setName(const char* name, bool complete = true); + ble_error_t setName(const char *name, bool complete = true); /** * Add manufacturer specific data to the advertising payload. @@ -835,7 +836,7 @@ private: * element being the length of the field followed by the value of the field. * NULL if the field is not present in the payload. */ - uint8_t* findField(adv_data_type_t type); + uint8_t *findField(adv_data_type_t type); /** * Get field size (includes type and size bytes) @@ -874,7 +875,7 @@ private: */ ble_error_t appendToField( mbed::Span fieldData, - uint8_t* field + uint8_t *field ); /** @@ -893,7 +894,7 @@ private: ble_error_t replaceField( adv_data_type_t advDataType, mbed::Span fieldData, - uint8_t* field + uint8_t *field ); /** @@ -903,7 +904,7 @@ private: * * @return BLE_ERROR_NONE on success. */ - ble_error_t removeField(uint8_t* field); + ble_error_t removeField(uint8_t *field); /** * Add a list of UUIDs to given types. diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index b4efcd3725..001ca51320 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -190,8 +190,8 @@ public: * * @return reference to this object. */ - AdvertisingParameters& setPrimaryInterval( - adv_interval_t min , adv_interval_t max + AdvertisingParameters &setPrimaryInterval( + adv_interval_t min, adv_interval_t max ) { _minInterval = min; diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index d3d1658095..faa469bcd3 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -407,7 +407,7 @@ private: uint8_t phyToIndex(phy_t phy) const { uint8_t index; - switch(phy.value()) { + switch (phy.value()) { case phy_t::LE_1M: index = 0; break; diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 29c4a53231..da9cebf70d 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -31,6 +31,7 @@ namespace ble { */ struct AdvertisingReportEvent { #if !defined(DOXYGEN_ONLY) + /** Create a advertising report event. * * @param type Type of advertising used. @@ -74,6 +75,7 @@ struct AdvertisingReportEvent { advertisingData(advertisingData) { } + #endif /** Get event type. */ @@ -170,6 +172,7 @@ private: */ struct ConnectionCompleteEvent { #if !defined(DOXYGEN_ONLY) + /** Create a connection complete event. * * @param success BLE_ERROR_NONE if connection succeeded. @@ -210,6 +213,7 @@ struct ConnectionCompleteEvent { masterClockAccuracy(masterClockAccuracy) { } + #endif /** Get connection complete event status. */ @@ -299,6 +303,7 @@ private: */ struct PeriodicAdvertisingSyncEstablishedEvent { #if !defined(DOXYGEN_ONLY) + /** Create advertising sync event. * * @param success BLE_ERROR_NONE if synchronisation was achieved. @@ -330,6 +335,7 @@ struct PeriodicAdvertisingSyncEstablishedEvent { peerClockAccuracy(peerClockAccuracy) { } + #endif /** Get sync establishment status. */ @@ -398,6 +404,7 @@ private: */ struct PeriodicAdvertisingReportEvent { #if !defined(DOXYGEN_ONLY) + /** Create periodic advertising report event. * * @param syncHandle Periodic advertising sync handle @@ -420,6 +427,7 @@ struct PeriodicAdvertisingReportEvent { payload(payload) { } + #endif /** Get periodic advertising sync handle. */ @@ -467,6 +475,7 @@ private: */ struct PeriodicAdvertisingSyncLoss { #if !defined(DOXYGEN_ONLY) + /** Create periodic advertising sync loss event. * * @param syncHandle Periodic advertising sync handle. @@ -477,6 +486,7 @@ struct PeriodicAdvertisingSyncLoss { syncHandle(syncHandle) { } + #endif /** Get periodic sync handle. */ @@ -503,6 +513,7 @@ struct ScanTimeoutEvent { }; */ struct AdvertisingEndEvent { #if !defined(DOXYGEN_ONLY) + /** Create advertising end event. * * @param advHandle Advertising set handle. @@ -522,6 +533,7 @@ struct AdvertisingEndEvent { connected(connected) { } + #endif /** Get advertising handle. */ @@ -562,6 +574,7 @@ private: */ struct ScanRequestEvent { #if !defined(DOXYGEN_ONLY) + /** Create scan request event. * * @param advHandle Advertising handle. @@ -578,6 +591,7 @@ struct ScanRequestEvent { peerAddress(peerAddress) { } + #endif /** Get advertising handle. */ @@ -611,6 +625,7 @@ private: */ struct DisconnectionEvent { #if !defined(DOXYGEN_ONLY) + DisconnectionEvent( connection_handle_t connectionHandle, const disconnection_reason_t &reason @@ -618,6 +633,7 @@ struct DisconnectionEvent { connectionHandle(connectionHandle), reason(reason) { } + #endif /** @@ -648,6 +664,7 @@ private: */ struct UpdateConnectionParametersRequestEvent { #if !defined(DOXYGEN_ONLY) + UpdateConnectionParametersRequestEvent( connection_handle_t connectionHandle, const conn_interval_t &minConnectionInterval, @@ -662,6 +679,7 @@ struct UpdateConnectionParametersRequestEvent { supervisionTimeout(supervision_timeout) { } + #endif /** @@ -719,6 +737,7 @@ private: */ struct ConnectionParametersUpdateCompleteEvent { #if !defined(DOXYGEN_ONLY) + ConnectionParametersUpdateCompleteEvent( ble_error_t status, connection_handle_t connectionHandle, @@ -733,6 +752,7 @@ struct ConnectionParametersUpdateCompleteEvent { supervisionTimeout(supervisionTimeout) { } + #endif /** diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 6c7ed69edd..eb3ba3fea4 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -82,7 +82,7 @@ public: * * @see startScan() */ - virtual void onScanTimeout(const ScanTimeoutEvent & event) + virtual void onScanTimeout(const ScanTimeoutEvent &event) { } @@ -729,12 +729,16 @@ protected: /** Can only be called if use_non_deprecated_scan_api() hasn't been called. * This guards against mixed use of deprecated and nondeprecated API. */ - virtual void useVersionOneAPI() const { } + virtual void useVersionOneAPI() const + { + } /** Can only be called if use_deprecated_scan_api() hasn't been called. * This guards against mixed use of deprecated and nondeprecated API. */ - virtual void useVersionTwoAPI() const { } + virtual void useVersionTwoAPI() const + { + } /* -------- soon to be deprecated API -------- */ @@ -842,7 +846,7 @@ public: */ ResolutionStrategy resolution_strategy; }; - + static const PeripheralPrivacyConfiguration_t default_peripheral_privacy_configuration; diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 6d522fb534..83908b1108 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -94,7 +94,7 @@ public: { } - ScanParameters& set_own_address_type(own_address_type_t address) + ScanParameters &set_own_address_type(own_address_type_t address) { own_address_type = address; return *this; @@ -105,7 +105,7 @@ public: return own_address_type; } - ScanParameters& set_scanning_filter_policy(scanning_filter_policy_t filter_policy) + ScanParameters &set_scanning_filter_policy(scanning_filter_policy_t filter_policy) { scanning_filter_policy = filter_policy; return *this; @@ -116,7 +116,7 @@ public: return scanning_filter_policy; } - ScanParameters& set_scanning_phys(bool enable_1m, bool enable_coded) + ScanParameters &set_scanning_phys(bool enable_1m, bool enable_coded) { phys.set_1m(enable_1m); phys.set_coded(enable_coded); @@ -128,7 +128,7 @@ public: return phys; } - ScanParameters& set_1m_phy_configuration( + ScanParameters &set_1m_phy_configuration( scan_interval_t interval, scan_window_t window, bool active_scanning @@ -146,7 +146,7 @@ public: return phy_1m_configuration; } - ScanParameters& set_coded_phy_configuration( + ScanParameters &set_coded_phy_configuration( scan_interval_t interval, scan_window_t window, bool active_scanning diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index b3076f94c6..d8f7c54e82 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -111,7 +111,7 @@ struct advertising_type_t : SafeEnum { /** Used to indicate if the packet is complete and if it's truncated. */ -struct advertising_data_status_t : SafeEnum{ +struct advertising_data_status_t : SafeEnum { enum type { COMPLETE = 0x00, /**< Advertising payload complete. */ INCOMPLETE_MORE_DATA = 0x01, /**< Partial advertising payload, more to come. */ @@ -330,7 +330,9 @@ struct scanning_filter_policy_t : SafeEnum { /** * Construct a new instance of scanning_filter_policy_t. */ - scanning_filter_policy_t(type value) : SafeEnum(value) { } + scanning_filter_policy_t(type value) : SafeEnum(value) + { + } }; /** @@ -359,7 +361,7 @@ struct initiator_filter_policy_t : SafeEnum * * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. */ -struct duplicates_filter_t : SafeEnum{ +struct duplicates_filter_t : SafeEnum { enum type { /** * Disable duplicate filtering. @@ -442,7 +444,7 @@ struct target_peer_address_type_t : SafeEnum { +struct clock_accuracy_t : SafeEnum { enum type { /** * 500 PPM @@ -491,16 +493,25 @@ struct clock_accuracy_t : SafeEnum { */ uint16_t get_ppm() { - switch(value()) { - case PPM_500: return 500; - case PPM_250: return 250; - case PPM_150: return 150; - case PPM_100: return 100; - case PPM_75: return 75; - case PPM_50: return 50; - case PPM_30: return 30; - case PPM_20: return 20; - default: return 0; + switch (value()) { + case PPM_500: + return 500; + case PPM_250: + return 250; + case PPM_150: + return 150; + case PPM_100: + return 100; + case PPM_75: + return 75; + case PPM_50: + return 50; + case PPM_30: + return 30; + case PPM_20: + return 20; + default: + return 0; } } @@ -527,7 +538,7 @@ struct clock_accuracy_t : SafeEnum { * * @attention A device can fulfill different roles concurrently. */ -struct connection_role_t :SafeEnum { +struct connection_role_t : SafeEnum { /** struct scoped enum wrapped by the class */ enum type { /** @@ -684,8 +695,6 @@ struct disconnection_reason_t : SafeEnum { }; - - } // namespace ble #endif //BLE_GAP_TYPES_H diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index e5147dfc43..a499966c04 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -42,14 +42,16 @@ namespace generic { * * @attention: Not part of the public interface of BLE API. */ -class GenericGap : public ::Gap, - public pal::ConnectionEventMonitor, - public pal::Gap::EventHandler { +class GenericGap : + public ::Gap, + public pal::ConnectionEventMonitor, + public pal::Gap::EventHandler { public: /* TODO: move to config */ static const uint8_t MAX_ADVERTISING_SETS = 15; static const size_t MAX_HCI_DATA_LENGTH = 251; + /** * Construct a GenericGap. * @@ -341,18 +343,18 @@ public: * @see Gap::setPreferredPhys */ virtual ble_error_t setPreferredPhys( - const phy_set_t* txPhys, - const phy_set_t* rxPhys + const phy_set_t *txPhys, + const phy_set_t *rxPhys ); /** * @see Gap::setPhy */ virtual ble_error_t setPhy( - Handle_t connection, - const phy_set_t* txPhys, - const phy_set_t* rxPhys, - CodedSymbolPerBit_t codedSymbol + Handle_t connection, + const phy_set_t *txPhys, + const phy_set_t *rxPhys, + CodedSymbolPerBit_t codedSymbol ); virtual ble_error_t disconnect( @@ -603,7 +605,7 @@ private: void update_random_address(); - bool getUnresolvableRandomAddress(ble::address_t& address); + bool getUnresolvableRandomAddress(ble::address_t &address); void on_address_rotation_timeout(); @@ -707,8 +709,9 @@ private: uint16_t connection_latency, uint16_t supervision_timeout ); + private: - pal::EventQueue& _event_queue; + pal::EventQueue &_event_queue; pal::Gap &_pal_gap; pal::GenericAccessService &_gap_service; pal::SecurityManager &_pal_sm; diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index 7a59a53b17..c00d50a970 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -63,11 +63,14 @@ struct connection_peer_address_type_t : * Construct a new connection_peer_address_type_t instance. */ connection_peer_address_type_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } explicit connection_peer_address_type_t(uint8_t raw_value) : SafeEnum(raw_value) - { } + { + } }; @@ -87,7 +90,9 @@ struct whitelist_address_type_t : SafeEnum { * Construct a new whitelist_address_type_t instance. */ whitelist_address_type_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } }; @@ -113,11 +118,14 @@ struct advertising_channel_map_t : SafeEnum * Construct a new advertising_channel_map_t instance. */ advertising_channel_map_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } advertising_channel_map_t(bool ch37, bool ch38, bool ch39) : SafeEnum(ch37 | (ch38 << 1) | (ch39 << 2)) - { } + { + } }; @@ -206,13 +214,17 @@ struct hci_error_code_t : SafeEnum { * Construct a new hci_error_code_t instance. */ hci_error_code_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } /** * Construct a new hci_error_code_t from a raw value. */ explicit hci_error_code_t(uint8_t raw_value) : - SafeEnum(static_cast(raw_value)) { } + SafeEnum(static_cast(raw_value)) + { + } }; @@ -233,7 +245,8 @@ struct advertising_data_t { * * @param input_value Reference to the array containing the advertising data */ - advertising_data_t(const uint8_t (&input_value)[31]) { + advertising_data_t(const uint8_t (&input_value)[31]) + { memcpy(value, input_value, sizeof(value)); } @@ -244,7 +257,8 @@ struct advertising_data_t { * * @param len Length of the buffer. */ - advertising_data_t(const uint8_t* input_value, size_t len) { + advertising_data_t(const uint8_t *input_value, size_t len) + { const size_t actual_len = std::min(len, sizeof(value)); memcpy(value, input_value, actual_len); memset(value + actual_len, 0x00, sizeof(value) - actual_len); @@ -254,8 +268,9 @@ struct advertising_data_t { * Equal operator between two advertising data. */ friend bool operator==( - const advertising_data_t& lhs, const advertising_data_t& rhs - ) { + const advertising_data_t &lhs, const advertising_data_t &rhs + ) + { return memcmp(lhs.value, rhs.value, sizeof(lhs.value)) == 0; } @@ -263,29 +278,33 @@ struct advertising_data_t { * Non equal operator between two advertising data. */ friend bool operator!=( - const advertising_data_t& lhs, const advertising_data_t& rhs - ) { + const advertising_data_t &lhs, const advertising_data_t &rhs + ) + { return !(lhs == rhs); } /** * Subscript operator used to access the content of the advertising data. */ - uint8_t operator[](uint8_t i) const { + uint8_t operator[](uint8_t i) const + { return value[i]; } /** * Return a pointer to the advertising data buffer. */ - const uint8_t* data() const { + const uint8_t *data() const + { return value; } /** * Return (fixed) size of advertising data. */ - uint8_t size() const { + uint8_t size() const + { return sizeof(value); } @@ -329,7 +348,9 @@ struct received_advertising_type_t : * Construct a new received_advertising_type_t value. */ received_advertising_type_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } }; /** @@ -352,7 +373,8 @@ struct advertising_event_properties_t { use_legacy_pdu(false), omit_advertiser_address(false), include_tx_power(false) - { } + { + } /** * Construct an advertising_event_properties_t with all fields defined by @@ -383,7 +405,8 @@ struct advertising_event_properties_t { use_legacy_pdu(use_legacy_pdu), omit_advertiser_address(omit_advertisser_address), include_tx_power(include_tx_power) - { } + { + } /** * Construct an advertising_event_property_t from a legacy advertising_type_t. @@ -469,7 +492,8 @@ struct advertising_event_properties_t { * Construct the value expected by a BT controller. * @return All fields in a uint16_t understandable by BT stacks. */ - uint16_t value() { + uint16_t value() + { uint16_t result = 0; result |= connectable << 0; result |= scannable << 1; @@ -522,7 +546,7 @@ typedef ble::rssi_t rssi_t; * Description of an advertising fragment. */ struct advertising_fragment_description_t : - SafeEnum{ + SafeEnum { enum type { /** @@ -562,7 +586,9 @@ struct advertising_fragment_description_t : * Construct a new advertising_fragment_description_t value. */ advertising_fragment_description_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } }; typedef ble::duplicates_filter_t duplicates_filter_t; @@ -575,41 +601,52 @@ typedef ble::periodic_sync_handle_t sync_handle_t; typedef ble::advertising_data_status_t advertising_data_status_t; struct extended_advertising_report_event_type_t { - extended_advertising_report_event_type_t(uint8_t value) : value(value) { } + extended_advertising_report_event_type_t(uint8_t value) : value(value) + { + } - bool connectable() { + bool connectable() + { return static_cast(value & (1 << 0)); } - bool scannable_advertising() { + bool scannable_advertising() + { return static_cast(value & (1 << 1)); } - bool directed_advertising() { + bool directed_advertising() + { return static_cast(value & (1 << 2)); } - bool scan_response() { + bool scan_response() + { return static_cast(value & (1 << 3)); } - bool legacy_advertising() { + bool legacy_advertising() + { return static_cast(value & (1 << 4)); } - advertising_data_status_t data_status() { + advertising_data_status_t data_status() + { return static_cast((value >> 5) & 0x03); } - bool complete() { + bool complete() + { return data_status() == advertising_data_status_t::COMPLETE; } - bool more_data_to_come() { + bool more_data_to_come() + { return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; } - bool truncated() { + bool truncated() + { return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; } @@ -651,9 +688,13 @@ struct direct_address_type_t : SafeEnum { * Construct a new direct_address_type_t instance. */ direct_address_type_t(type value) : - SafeEnum(value) { } + SafeEnum(value) + { + } - explicit direct_address_type_t(uint8_t raw_value) : SafeEnum(raw_value) { } + explicit direct_address_type_t(uint8_t raw_value) : SafeEnum(raw_value) + { + } }; typedef ble::clock_accuracy_t clock_accuracy_t; diff --git a/features/FEATURE_BLE/ble/pal/PalGap.h b/features/FEATURE_BLE/ble/pal/PalGap.h index 391ef0a959..0a9a017ae3 100644 --- a/features/FEATURE_BLE/ble/pal/PalGap.h +++ b/features/FEATURE_BLE/ble/pal/PalGap.h @@ -294,7 +294,7 @@ struct Gap { * @return BLE_ERROR_NONE if the request has been successfully sent or the * appropriate error otherwise. */ - virtual ble_error_t set_random_address(const address_t& address) = 0; + virtual ble_error_t set_random_address(const address_t &address) = 0; /** * Set the random device address used by an advertising set. @@ -316,7 +316,7 @@ struct Gap { * @note See Bluetooth 5 Vol 2, Part E: 7.8.52 LE Set Advertising Set Random * Address Command */ - virtual ble_error_t set_advertising_set_random_address( + virtual ble_error_t set_advertising_set_random_address( advertising_handle_t advertising_handle, const address_t &address ) = 0; @@ -384,7 +384,7 @@ struct Gap { advertising_type_t advertising_type, own_address_type_t own_address_type, advertising_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, advertising_channel_map_t advertising_channel_map, advertising_filter_policy_t advertising_filter_policy ) = 0; @@ -518,7 +518,7 @@ struct Gap { */ virtual ble_error_t set_advertising_data( uint8_t advertising_data_length, - const advertising_data_t& advertising_data + const advertising_data_t &advertising_data ) = 0; /** @@ -611,7 +611,7 @@ struct Gap { */ virtual ble_error_t set_scan_response_data( uint8_t scan_response_data_length, - const advertising_data_t& scan_response_data + const advertising_data_t &scan_response_data ) = 0; /** @@ -727,9 +727,9 @@ struct Gap { virtual ble_error_t extended_advertising_enable( bool enable, uint8_t number_of_sets, - const advertising_handle_t* handles, - const uint16_t* durations, - const uint8_t* max_extended_advertising_events + const advertising_handle_t *handles, + const uint16_t *durations, + const uint8_t *max_extended_advertising_events ) = 0; /** @@ -1159,7 +1159,7 @@ struct Gap { uint16_t scan_window, initiator_policy_t initiator_policy, connection_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, own_address_type_t own_address_type, uint16_t connection_interval_min, uint16_t connection_interval_max, @@ -1252,14 +1252,14 @@ struct Gap { peer_address_type_t peer_address_type, const address_t &peer_address, phy_set_t initiating_phys, - const uint16_t* scan_intervals, - const uint16_t* scan_windows, - const uint16_t* connection_intervals_min, - const uint16_t* connection_intervals_max, - const uint16_t* connection_latencies, - const uint16_t* supervision_timeouts, - const uint16_t* minimum_connection_event_lengths, - const uint16_t* maximum_connection_event_lengths + const uint16_t *scan_intervals, + const uint16_t *scan_windows, + const uint16_t *connection_intervals_min, + const uint16_t *connection_intervals_max, + const uint16_t *connection_latencies, + const uint16_t *supervision_timeouts, + const uint16_t *minimum_connection_event_lengths, + const uint16_t *maximum_connection_event_lengths ) = 0; /** @@ -1524,7 +1524,7 @@ struct Gap { * @return true if privacy is supported, false otherwise. * * @note: See Bluetooth 5 Vol 3 Part C: 10.7 Privacy feature. - */ + */ virtual bool is_privacy_supported() = 0; /** Enable or disable private addresses resolution @@ -1549,7 +1549,7 @@ struct Gap { virtual bool is_feature_supported( controller_supported_features_t feature ) = 0; - + /** * @see Gap::readPhy */ @@ -1559,18 +1559,18 @@ struct Gap { * @see Gap::setPreferredPhys */ virtual ble_error_t set_preferred_phys( - const phy_set_t& tx_phys, - const phy_set_t& rx_phys + const phy_set_t &tx_phys, + const phy_set_t &rx_phys ) = 0; /** * @see Gap::setPhy */ virtual ble_error_t set_phy( - connection_handle_t connection, - const phy_set_t& tx_phys, - const phy_set_t& rx_phys, - coded_symbol_per_bit_t coded_symbol + connection_handle_t connection, + const phy_set_t &tx_phys, + const phy_set_t &rx_phys, + coded_symbol_per_bit_t coded_symbol ) = 0; /** @@ -1580,7 +1580,7 @@ struct Gap { * LE subsystem. * It accept a single parameter in input: The event received. */ - void when_gap_event_received(mbed::Callback cb) + void when_gap_event_received(mbed::Callback cb) { _gap_event_cb = cb; } @@ -1593,11 +1593,13 @@ public: * @param[in] event_handler the new event handler interface implementation. Memory * owned by caller who is responsible for updating this pointer if interface changes. */ - void set_event_handler(EventHandler *event_handler) { + void set_event_handler(EventHandler *event_handler) + { _pal_event_handler = event_handler; } - EventHandler* get_event_handler() { + EventHandler *get_event_handler() + { return _pal_event_handler; } @@ -1605,9 +1607,13 @@ protected: EventHandler *_pal_event_handler; protected: - Gap() : _pal_event_handler(NULL) { } + Gap() : _pal_event_handler(NULL) + { + } - virtual ~Gap() { } + virtual ~Gap() + { + } /** * Implementation shall call this function whenever the LE subsystem @@ -1615,7 +1621,7 @@ protected: * * @param gap_event The event to emit to higher layer. */ - void emit_gap_event(const GapEvent& gap_event) + void emit_gap_event(const GapEvent &gap_event) { if (_gap_event_cb) { _gap_event_cb(gap_event); @@ -1629,9 +1635,10 @@ public: * @see BLUETOOTH SPECIFICATION Version 5.0 | Vol 2, Part E - 7.8.49 */ static uint8_t create_all_phys_value( - const phy_set_t& tx_phys, - const phy_set_t& rx_phys - ) { + const phy_set_t &tx_phys, + const phy_set_t &rx_phys + ) + { /* if phy set is empty set corresponding all_phys bit to 1 */ uint8_t all_phys = 0; if (tx_phys.value() == 0) { @@ -1647,12 +1654,13 @@ private: /** * Callback called when an event is emitted by the LE subsystem. */ - mbed::Callback _gap_event_cb; + mbed::Callback _gap_event_cb; private: // Disallow copy construction and copy assignment. - Gap(const Gap&); - Gap& operator=(const Gap&); + Gap(const Gap &); + + Gap &operator=(const Gap &); }; } // namespace pal diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp index 4b8e86e1b4..a16bfe15d6 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -20,22 +20,26 @@ namespace ble { AdvertisingDataBuilder::AdvertisingDataBuilder(mbed::Span buffer) : _buffer(buffer), - _payload_length(0) { + _payload_length(0) +{ } -AdvertisingDataBuilder::AdvertisingDataBuilder(uint8_t* buffer, size_t buffer_size) : +AdvertisingDataBuilder::AdvertisingDataBuilder(uint8_t *buffer, size_t buffer_size) : _buffer(buffer, buffer_size), - _payload_length(0) { + _payload_length(0) +{ } -mbed::Span AdvertisingDataBuilder::getAdvertisingData() const { +mbed::Span AdvertisingDataBuilder::getAdvertisingData() const +{ return _buffer.first(_payload_length); } ble_error_t AdvertisingDataBuilder::addData( adv_data_type_t advDataType, mbed::Span fieldData -) { +) +{ if (findField(advDataType)) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } else { @@ -46,8 +50,9 @@ ble_error_t AdvertisingDataBuilder::addData( ble_error_t AdvertisingDataBuilder::replaceData( adv_data_type_t advDataType, mbed::Span fieldData -) { - uint8_t* field = findField(advDataType); +) +{ + uint8_t *field = findField(advDataType); if (field) { return replaceField(advDataType, fieldData, field); @@ -59,8 +64,9 @@ ble_error_t AdvertisingDataBuilder::replaceData( ble_error_t AdvertisingDataBuilder::appendData( adv_data_type_t advDataType, mbed::Span fieldData -) { - uint8_t* field = findField(advDataType); +) +{ + uint8_t *field = findField(advDataType); if (field) { return appendToField(fieldData, field); @@ -71,8 +77,9 @@ ble_error_t AdvertisingDataBuilder::appendData( ble_error_t AdvertisingDataBuilder::removeData( adv_data_type_t advDataType -) { - uint8_t* field = findField(advDataType); +) +{ + uint8_t *field = findField(advDataType); if (field) { return removeField(field); @@ -84,8 +91,9 @@ ble_error_t AdvertisingDataBuilder::removeData( ble_error_t AdvertisingDataBuilder::addOrReplaceData( adv_data_type_t advDataType, mbed::Span fieldData -) { - uint8_t* field = findField(advDataType); +) +{ + uint8_t *field = findField(advDataType); if (field) { return replaceField(advDataType, fieldData, field); @@ -97,8 +105,9 @@ ble_error_t AdvertisingDataBuilder::addOrReplaceData( ble_error_t AdvertisingDataBuilder::addOrAppendData( adv_data_type_t advDataType, mbed::Span fieldData -) { - uint8_t* field = findField(advDataType); +) +{ + uint8_t *field = findField(advDataType); if (field) { return appendToField(fieldData, field); @@ -107,39 +116,44 @@ ble_error_t AdvertisingDataBuilder::addOrAppendData( } } -void AdvertisingDataBuilder::clear() { +void AdvertisingDataBuilder::clear() +{ memset(_buffer.data(), 0, _buffer.size()); _payload_length = 0; } ble_error_t AdvertisingDataBuilder::setAppearance( adv_data_appearance_t appearance -) { +) +{ uint8_t appearence_byte = appearance.value(); - mbed::Span appearance_span((const uint8_t*) &appearence_byte, 2); + mbed::Span appearance_span((const uint8_t *) &appearence_byte, 2); return addOrReplaceData(adv_data_type_t::APPEARANCE, appearance_span); } ble_error_t AdvertisingDataBuilder::setFlags( adv_data_flags_t flags -) { +) +{ uint8_t flags_byte = flags.value(); - mbed::Span flags_span((const uint8_t*) &flags_byte, 1); + mbed::Span flags_span((const uint8_t *) &flags_byte, 1); return addOrReplaceData(adv_data_type_t::FLAGS, flags_span); } ble_error_t AdvertisingDataBuilder::setTxPowerAdvertised( advertising_power_t txPower -) { - mbed::Span power_span((const uint8_t*) &txPower, 1); +) +{ + mbed::Span power_span((const uint8_t *) &txPower, 1); return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, power_span); } ble_error_t AdvertisingDataBuilder::setName( - const char* name, + const char *name, bool complete -) { - mbed::Span power_span((const uint8_t*)name, strlen(name)); +) +{ + mbed::Span power_span((const uint8_t *) name, strlen(name)); if (complete) { return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); @@ -150,7 +164,8 @@ ble_error_t AdvertisingDataBuilder::setName( ble_error_t AdvertisingDataBuilder::setManufacturerSpecificData( mbed::Span data -) { +) +{ if (data.size() < 2) { return BLE_ERROR_INVALID_PARAM; } @@ -160,34 +175,37 @@ ble_error_t AdvertisingDataBuilder::setManufacturerSpecificData( ble_error_t AdvertisingDataBuilder::setAdvertisingInterval( adv_interval_t interval -) { +) +{ if (interval.value() > 0xFFFF) { return BLE_ERROR_INVALID_PARAM; } return addOrReplaceData( adv_data_type_t::ADVERTISING_INTERVAL, - mbed::make_Span((const uint8_t*)interval.storage(), 2) + mbed::make_Span((const uint8_t *) interval.storage(), 2) ); } ble_error_t AdvertisingDataBuilder::setConnectionIntervalPreference( conn_interval_t min, conn_interval_t max -) { - uint32_t interval = max.value(); +) +{ + uint32_t interval = max.value(); interval = interval << 16; interval |= min.value(); return addOrReplaceData( adv_data_type_t::SLAVE_CONNECTION_INTERVAL_RANGE, - mbed::make_Span((const uint8_t*)&interval, 4) + mbed::make_Span((const uint8_t *) &interval, 4) ); } ble_error_t AdvertisingDataBuilder::setServiceData( UUID service, mbed::Span data -) { +) +{ if (service.getLen() + data.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -232,7 +250,8 @@ ble_error_t AdvertisingDataBuilder::setServiceData( ble_error_t AdvertisingDataBuilder::setLocalServiceList( mbed::Span data, bool complete -) { +) +{ adv_data_type_t short_type = complete ? adv_data_type_t::COMPLETE_LIST_16BIT_SERVICE_IDS : adv_data_type_t::INCOMPLETE_LIST_16BIT_SERVICE_IDS; @@ -246,7 +265,8 @@ ble_error_t AdvertisingDataBuilder::setLocalServiceList( ble_error_t AdvertisingDataBuilder::setRequestedServiceList( mbed::Span data -) { +) +{ adv_data_type_t short_type = adv_data_type_t::LIST_16BIT_SOLICITATION_IDS; adv_data_type_t long_type = adv_data_type_t::LIST_128BIT_SOLICITATION_IDS; @@ -256,21 +276,22 @@ ble_error_t AdvertisingDataBuilder::setRequestedServiceList( ble_error_t AdvertisingDataBuilder::getData( mbed::Span &data, adv_data_type_t advDataType -) { +) +{ uint8_t *field = findField(advDataType); if (field) { uint8_t data_length = field[0] - 1 /* skip type */; - data = mbed::make_Span((const uint8_t*)(field + 2 /* skip type and length */), data_length); + data = mbed::make_Span((const uint8_t *) (field + 2 /* skip type and length */), data_length); return BLE_ERROR_NONE; } else { return BLE_ERROR_NOT_FOUND; } } -uint8_t* AdvertisingDataBuilder::findField(adv_data_type_t type) +uint8_t *AdvertisingDataBuilder::findField(adv_data_type_t type) { /* Scan through advertisement data */ - for (uint8_t idx = 0; idx < _payload_length; ) { + for (uint8_t idx = 0; idx < _payload_length;) { uint8_t fieldType = _buffer[idx + 1]; if (fieldType == type) { @@ -284,7 +305,8 @@ uint8_t* AdvertisingDataBuilder::findField(adv_data_type_t type) return NULL; } -uint8_t AdvertisingDataBuilder::getFieldSize(adv_data_type_t type) { +uint8_t AdvertisingDataBuilder::getFieldSize(adv_data_type_t type) +{ uint8_t *field = findField(type); if (field) { return field[0] + 1; @@ -296,7 +318,8 @@ uint8_t AdvertisingDataBuilder::getFieldSize(adv_data_type_t type) { ble_error_t AdvertisingDataBuilder::addField( adv_data_type_t advDataType, mbed::Span fieldData -) { +) +{ if (fieldData.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -323,8 +346,9 @@ ble_error_t AdvertisingDataBuilder::addField( ble_error_t AdvertisingDataBuilder::appendToField( mbed::Span fieldData, - uint8_t* field -) { + uint8_t *field +) +{ if (fieldData.size() + field[0] > 0xFF /* field[0] already includes the type byte */) { return BLE_ERROR_INVALID_PARAM; } @@ -335,8 +359,8 @@ ble_error_t AdvertisingDataBuilder::appendToField( /* get the size of bytes in the payload after the field */ size_t remainder_size = _payload_length - - (field - _buffer.data()) - /* length of all data before the field */ - (old_data_length + 1) /* length of the old field */; + (field - _buffer.data()) - /* length of all data before the field */ + (old_data_length + 1) /* length of the old field */; /* move data after the field to fit new data */ if (remainder_size) { @@ -363,8 +387,9 @@ ble_error_t AdvertisingDataBuilder::appendToField( ble_error_t AdvertisingDataBuilder::replaceField( adv_data_type_t advDataType, mbed::Span fieldData, - uint8_t* field -) { + uint8_t *field +) +{ if (fieldData.size() > 0xFE) { return BLE_ERROR_INVALID_PARAM; } @@ -389,7 +414,7 @@ ble_error_t AdvertisingDataBuilder::replaceField( } } -ble_error_t AdvertisingDataBuilder::removeField(uint8_t* field) +ble_error_t AdvertisingDataBuilder::removeField(uint8_t *field) { /* stored length + the byte containing length */ uint8_t old_field_length = field[0] + 1; @@ -405,7 +430,8 @@ ble_error_t AdvertisingDataBuilder::setUUIDData( mbed::Span data, adv_data_type_t shortType, adv_data_type_t longType -) { +) +{ ble_error_t status = BLE_ERROR_NONE; /* first count all the bytes we need to store all the UUIDs */ @@ -426,7 +452,7 @@ ble_error_t AdvertisingDataBuilder::setUUIDData( /* calculate total size including headers for types */ size_t total_size = size_long + (!!size_long) * 2 + - size_short + (!!size_short) * 2; + size_short + (!!size_short) * 2; /* count all the bytes of existing data */ size_t old_size = getFieldSize(shortType) + getFieldSize(longType); diff --git a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp index bac775437f..e999e78778 100644 --- a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp +++ b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp @@ -54,7 +54,7 @@ ConnectionParameters::ConnectionParameters( /* setters */ -ConnectionParameters & ConnectionParameters::setScanParameters( +ConnectionParameters &ConnectionParameters::setScanParameters( phy_t phy, scan_interval_t scanInterval, scan_window_t scanWindow @@ -70,7 +70,7 @@ ConnectionParameters & ConnectionParameters::setScanParameters( return *this; } -ConnectionParameters & ConnectionParameters::setConnectionParameters( +ConnectionParameters &ConnectionParameters::setConnectionParameters( phy_t phy, conn_interval_t minConnectionInterval, conn_interval_t maxConnectionInterval, diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 7b685f4545..d61cec786f 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -53,7 +53,8 @@ ble_error_t Gap::destroyAdvertisingSet(advertising_handle_t handle) ble_error_t Gap::setAdvertisingParameters( advertising_handle_t handle, const AdvertisingParameters ¶ms -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -62,7 +63,8 @@ ble_error_t Gap::setAdvertisingPayload( advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -71,7 +73,8 @@ ble_error_t Gap::setAdvertisingScanResponse( advertising_handle_t handle, mbed::Span response, bool minimiseFragmentation -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -80,7 +83,8 @@ ble_error_t Gap::startAdvertising( advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -91,7 +95,8 @@ ble_error_t Gap::stopAdvertising(advertising_handle_t handle) return BLE_ERROR_NOT_IMPLEMENTED; } -bool Gap::isAdvertisingActive(advertising_handle_t handle) { +bool Gap::isAdvertisingActive(advertising_handle_t handle) +{ return false; } @@ -100,7 +105,8 @@ ble_error_t Gap::setPeriodicAdvertisingParameters( periodic_interval_t periodicAdvertisingIntervalMin, periodic_interval_t periodicAdvertisingIntervalMax, bool advertiseTxPower -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -108,7 +114,8 @@ ble_error_t Gap::setPeriodicAdvertisingParameters( ble_error_t Gap::setPeriodicAdvertisingPayload( advertising_handle_t handle, mbed::Span payload -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -131,7 +138,7 @@ bool Gap::isPeriodicAdvertisingActive(advertising_handle_t handle) return false; } -ble_error_t Gap::setScanParameters(const ScanParameters& params) +ble_error_t Gap::setScanParameters(const ScanParameters ¶ms) { useVersionTwoAPI(); /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -142,7 +149,8 @@ ble_error_t Gap::startScan( duplicates_filter_t filtering, scan_duration_t duration, scan_period_t period -) { +) +{ useVersionTwoAPI(); /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; @@ -161,7 +169,8 @@ ble_error_t Gap::createSync( uint8_t sid, slave_latency_t maxPacketSkip, sync_timeout_t timeout -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -169,7 +178,8 @@ ble_error_t Gap::createSync( ble_error_t Gap::createSync( slave_latency_t maxPacketSkip, sync_timeout_t timeout -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -180,7 +190,8 @@ ble_error_t Gap::cancelCreateSync() return BLE_ERROR_NOT_IMPLEMENTED; } -ble_error_t Gap::terminateSync(periodic_sync_handle_t handle) { +ble_error_t Gap::terminateSync(periodic_sync_handle_t handle) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -189,7 +200,8 @@ ble_error_t Gap::addDeviceToPeriodicAdvertiserList( peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -198,7 +210,8 @@ ble_error_t Gap::removeDeviceFromPeriodicAdvertiserList( peer_address_type_t peerAddressType, const address_t &peerAddress, advertising_sid_t sid -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -219,12 +232,14 @@ ble_error_t Gap::connect( target_peer_address_type_t peerAddressType, const address_t &peerAddress, const ConnectionParameters &connectionParams -) { +) +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } -ble_error_t Gap::cancelConnect() { +ble_error_t Gap::cancelConnect() +{ /* Requesting action from porter(s): override this API if this capability is supported. */ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -237,13 +252,15 @@ ble_error_t Gap::updateConnectionParameters( supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::manageConnectionParametersUpdateRequest( bool userManageConnectionUpdateRequest -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -255,20 +272,23 @@ ble_error_t Gap::acceptConnectionParametersUpdate( supervision_timeout_t supervision_timeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::rejectConnectionParametersUpdate( connection_handle_t connectionHandle -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::disconnect( connection_handle_t connectionHandle, local_disconnection_reason_t reason -) { +) +{ // Forward to the old implementation for now. return BLE_ERROR_NOT_IMPLEMENTED; } @@ -281,7 +301,8 @@ ble_error_t Gap::readPhy(connection_handle_t connection) ble_error_t Gap::setPreferredPhys( const phy_set_t *txPhys, const phy_set_t *rxPhys -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -290,7 +311,8 @@ ble_error_t Gap::setPhy( const phy_set_t *txPhys, const phy_set_t *rxPhys, coded_symbol_per_bit_t codedSymbol -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } @@ -313,29 +335,32 @@ ble_error_t Gap::enablePrivacy(bool enable) ble_error_t Gap::setPeripheralPrivacyConfiguration( const PeripheralPrivacyConfiguration_t *configuration -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::getPeripheralPrivacyConfiguration( PeripheralPrivacyConfiguration_t *configuration -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::setCentralPrivacyConfiguration( const CentralPrivacyConfiguration_t *configuration -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::getCentralPrivacyConfiguration( CentralPrivacyConfiguration_t *configuration -) { +) +{ return BLE_ERROR_NOT_IMPLEMENTED; } - } // namespace ble diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9aa61a0891..b42863ee59 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -68,7 +68,8 @@ static const mbed_error_status_t mixed_scan_api_error = * Return true if value is included in the range [lower_bound : higher_bound] */ template -static bool is_in_range(T value, T lower_bound, T higher_bound) { +static bool is_in_range(T value, T lower_bound, T higher_bound) +{ if (value < lower_bound || value > higher_bound) { return false; } @@ -78,7 +79,7 @@ static bool is_in_range(T value, T lower_bound, T higher_bound) { /* * Return true if the scan parameters are valid or false otherwise. */ -static bool is_scan_params_valid(const GapScanningParams* params) +static bool is_scan_params_valid(const GapScanningParams *params) { if (params == NULL) { return false; @@ -98,7 +99,7 @@ static bool is_scan_params_valid(const GapScanningParams* params) /* * Return true if the connection parameters are valid or false otherwise. */ -static bool is_connection_params_valid(const ::Gap::ConnectionParams_t* params) +static bool is_connection_params_valid(const ::Gap::ConnectionParams_t *params) { if (params == NULL) { return false; @@ -121,7 +122,7 @@ static bool is_connection_params_valid(const ::Gap::ConnectionParams_t* params) } uint16_t max_connection_interval_ms = - ((uint32_t)params->maxConnectionInterval * 125) / 100; + ((uint32_t) params->maxConnectionInterval * 125) / 100; uint16_t min_connection_supervision_timeout = ((1 + params->slaveLatency) * max_connection_interval_ms * 2) / 10; @@ -141,7 +142,7 @@ static bool is_connection_params_valid(const ::Gap::ConnectionParams_t* params) * timeout to be equal to 0xFFFF. When it is the case that value can be * interpreted as "non specific". */ -static bool is_preferred_connection_params_valid(const ::Gap::ConnectionParams_t* params) +static bool is_preferred_connection_params_valid(const ::Gap::ConnectionParams_t *params) { if (params == NULL) { return false; @@ -169,12 +170,12 @@ static bool is_preferred_connection_params_valid(const ::Gap::ConnectionParams_t return false; } - if (params->maxConnectionInterval == 0xFFFF) { + if (params->maxConnectionInterval == 0xFFFF) { return true; } uint16_t max_connection_interval_ms = - ((uint32_t)params->maxConnectionInterval * 125) / 100; + ((uint32_t) params->maxConnectionInterval * 125) / 100; uint16_t min_connection_supervision_timeout = ((1 + params->slaveLatency) * max_connection_interval_ms * 2) / 10; @@ -188,7 +189,7 @@ static bool is_preferred_connection_params_valid(const ::Gap::ConnectionParams_t /** * Check if random bytes of an address are valid. */ -static bool is_prand_valid(const uint8_t* bytes, size_t len) +static bool is_prand_valid(const uint8_t *bytes, size_t len) { // at least one bit of the random part of the static address shall be // equal to 0 and at least one bit of the random part of the static @@ -252,7 +253,8 @@ static bool is_random_static_address(const BLEProtocol::AddressBytes_t address) */ static bool is_random_private_non_resolvable_address( const BLEProtocol::AddressBytes_t address -) { +) +{ // top two msb bits shall be equal to 0b00. if ((address[5] & 0xC0) != 0x00) { return false; @@ -266,7 +268,8 @@ static bool is_random_private_non_resolvable_address( */ static bool is_random_private_resolvable_address( const BLEProtocol::AddressBytes_t address -) { +) +{ // top two msb bits shall be equal to 0b01. if ((address[5] & 0xC0) != 0x40) { return false; @@ -317,14 +320,14 @@ static bool is_disconnection_reason_valid(::Gap::DisconnectionReason_t reason) /* * Return true if the whitelist in input is valid or false otherwise. */ -static bool is_whitelist_valid(const ::Gap::Whitelist_t& whitelist) +static bool is_whitelist_valid(const ::Gap::Whitelist_t &whitelist) { if (whitelist.size > whitelist.capacity) { return false; } for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& address = whitelist.addresses[i]; + const BLEProtocol::Address_t &address = whitelist.addresses[i]; if (address.type != BLEProtocol::AddressType::PUBLIC && address.type != BLEProtocol::AddressType::RANDOM_STATIC ) { @@ -344,10 +347,11 @@ static bool is_whitelist_valid(const ::Gap::Whitelist_t& whitelist) * Return true if device is present in the whitelist. */ static bool is_in_whitelist( - const BLEProtocol::Address_t& device, const ::Gap::Whitelist_t& whitelist -) { + const BLEProtocol::Address_t &device, const ::Gap::Whitelist_t &whitelist +) +{ for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& potential_device = whitelist.addresses[i]; + const BLEProtocol::Address_t &potential_device = whitelist.addresses[i]; if (potential_device.type != device.type) { continue; @@ -365,10 +369,11 @@ static bool is_in_whitelist( */ static pal::whitelist_address_type_t to_whitelist_address_type( BLEProtocol::AddressType_t address_type -) { - return (address_type == BLEProtocol::AddressType::PUBLIC) ? - pal::whitelist_address_type_t::PUBLIC_DEVICE_ADDRESS : - pal::whitelist_address_type_t::RANDOM_DEVICE_ADDRESS; +) +{ + return (address_type == BLEProtocol::AddressType::PUBLIC) ? + pal::whitelist_address_type_t::PUBLIC_DEVICE_ADDRESS : + pal::whitelist_address_type_t::RANDOM_DEVICE_ADDRESS; } /* @@ -376,17 +381,18 @@ static pal::whitelist_address_type_t to_whitelist_address_type( */ static peer_address_type_t to_peer_address_type( LegacyAddressType_t address_type -) { - return (address_type == LegacyAddressType::PUBLIC) ? - peer_address_type_t::PUBLIC : - peer_address_type_t::RANDOM; +) +{ + return (address_type == LegacyAddressType::PUBLIC) ? + peer_address_type_t::PUBLIC : + peer_address_type_t::RANDOM; } /* * Return true if the advertising parameters are valid. */ -static bool is_advertising_params_valid(const GapAdvertisingParams& params) +static bool is_advertising_params_valid(const GapAdvertisingParams ¶ms) { if (is_in_range(params.getIntervalInADVUnits(), advertising_interval_min, advertising_interval_max) == false) { return false; @@ -402,10 +408,10 @@ static bool is_advertising_params_valid(const GapAdvertisingParams& params) } // end of anonymous namespace GenericGap::GenericGap( - pal::EventQueue& event_queue, - pal::Gap& pal_gap, - pal::GenericAccessService& generic_access_service, - pal::SecurityManager& pal_sm + pal::EventQueue &event_queue, + pal::Gap &pal_gap, + pal::GenericAccessService &generic_access_service, + pal::SecurityManager &pal_sm ) : _event_queue(event_queue), _pal_gap(pal_gap), _gap_service(generic_access_service), @@ -449,14 +455,16 @@ GenericGap::~GenericGap() bool GenericGap::isFeatureSupported( controller_supported_features_t feature -) { +) +{ return _pal_gap.is_feature_supported(feature); } ble_error_t GenericGap::setAddress( LegacyAddressType_t type, const Address_t address -) { +) +{ switch (type) { case LegacyAddressType::PUBLIC: // The public address cannot be set, just set the type to public @@ -495,7 +503,8 @@ ble_error_t GenericGap::setAddress( ble_error_t GenericGap::getAddress( LegacyAddressType_t *type, Address_t address -) { +) +{ *type = _address_type; ble::address_t address_value; @@ -564,7 +573,8 @@ ble_error_t GenericGap::connect( PeerAddressType_t peerAddrType, const ConnectionParams_t *connectionParams, const GapScanningParams *scanParams -) { +) +{ if (connectionParams == NULL) { connectionParams = &default_connection_params; } @@ -604,9 +614,10 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( const Address_t peerAddr, LegacyAddressType_t peerAddrType, - const ConnectionParams_t* connectionParams, - const GapScanningParams* scanParams -) { + const ConnectionParams_t *connectionParams, + const GapScanningParams *scanParams +) +{ return connect( peerAddr, to_peer_address_type(peerAddrType), @@ -620,7 +631,8 @@ ble_error_t GenericGap::connect( target_peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ConnectionParameters &connectionParams -) { +) +{ if (!connectionParams.getNumberOfEnabledPhys()) { return BLE_ERROR_INVALID_PARAM; } @@ -635,9 +647,9 @@ ble_error_t GenericGap::connect( return _pal_gap.extended_create_connection( connectionParams.getFilterPolicy(), connectionParams.getOwnAddressType(), - (peer_address_type_t::type)peerAddressType.value(), + (peer_address_type_t::type) peerAddressType.value(), peerAddress, - (phy_set_t)connectionParams.getPhySet(), + (phy_set_t) connectionParams.getPhySet(), connectionParams.getScanIntervalArray(), connectionParams.getScanWindowArray(), connectionParams.getMinConnectionIntervalArray(), @@ -649,7 +661,8 @@ ble_error_t GenericGap::connect( ); } -ble_error_t GenericGap::manageConnectionParametersUpdateRequest(bool flag) { +ble_error_t GenericGap::manageConnectionParametersUpdateRequest(bool flag) +{ _user_manage_connection_parameter_requests = flag; return BLE_ERROR_NONE; } @@ -662,7 +675,8 @@ ble_error_t GenericGap::updateConnectionParameters( supervision_timeout_t supervisionTimeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength -) { +) +{ if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { return BLE_ERROR_INVALID_PARAM; } @@ -686,7 +700,8 @@ ble_error_t GenericGap::acceptConnectionParametersUpdate( supervision_timeout_t supervisionTimeout, conn_event_length_t minConnectionEventLength, conn_event_length_t maxConnectionEventLength -) { +) +{ if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { return BLE_ERROR_INVALID_PARAM; } @@ -704,7 +719,8 @@ ble_error_t GenericGap::acceptConnectionParametersUpdate( ble_error_t GenericGap::rejectConnectionParametersUpdate( connection_handle_t connectionHandle -) { +) +{ return _pal_gap.reject_connection_parameter_request( connectionHandle, pal::hci_error_code_t::UNACCEPTABLE_CONNECTION_PARAMETERS @@ -716,27 +732,30 @@ ble_error_t GenericGap::cancelConnect() return _pal_gap.cancel_connection_creation(); } -ble_error_t GenericGap::readPhy(Handle_t connection) { +ble_error_t GenericGap::readPhy(Handle_t connection) +{ return _pal_gap.read_phy(connection); } ble_error_t GenericGap::setPreferredPhys( - const phy_set_t* txPhys, - const phy_set_t* rxPhys -) { - phy_set_t tx_phys(txPhys? txPhys->value() : 0); - phy_set_t rx_phys(rxPhys? rxPhys->value() : 0); + const phy_set_t *txPhys, + const phy_set_t *rxPhys +) +{ + phy_set_t tx_phys(txPhys ? txPhys->value() : 0); + phy_set_t rx_phys(rxPhys ? rxPhys->value() : 0); return _pal_gap.set_preferred_phys(tx_phys, rx_phys); } ble_error_t GenericGap::setPhy( Handle_t connection, - const phy_set_t* txPhys, - const phy_set_t* rxPhys, + const phy_set_t *txPhys, + const phy_set_t *rxPhys, CodedSymbolPerBit_t codedSymbol -) { - phy_set_t tx_phys(txPhys? txPhys->value() : 0); - phy_set_t rx_phys(rxPhys? rxPhys->value() : 0); +) +{ + phy_set_t tx_phys(txPhys ? txPhys->value() : 0); + phy_set_t rx_phys(rxPhys ? rxPhys->value() : 0); return _pal_gap.set_phy(connection, tx_phys, rx_phys, codedSymbol); } @@ -746,7 +765,8 @@ void GenericGap::on_read_phy( Handle_t connection_handle, phy_t tx_phy, phy_t rx_phy -) { +) +{ ble_error_t status = BLE_ERROR_NONE; if (pal::hci_error_code_t::SUCCESS != hci_status) { status = BLE_ERROR_UNSPECIFIED; @@ -762,7 +782,8 @@ void GenericGap::on_phy_update_complete( Handle_t connection_handle, phy_t tx_phy, phy_t rx_phy -) { +) +{ ble_error_t status = BLE_ERROR_NONE; if (pal::hci_error_code_t::SUCCESS != hci_status) { status = BLE_ERROR_UNSPECIFIED; @@ -776,7 +797,8 @@ void GenericGap::on_phy_update_complete( ble_error_t GenericGap::disconnect( connection_handle_t connectionHandle, local_disconnection_reason_t reason -) { +) +{ return _pal_gap.disconnect(connectionHandle, reason); } @@ -821,7 +843,7 @@ ble_error_t GenericGap::getPreferredConnectionParams(ConnectionParams_t *params) ble_error_t GenericGap::setPreferredConnectionParams(const ConnectionParams_t *params) { - if(is_preferred_connection_params_valid(params) == false) { + if (is_preferred_connection_params_valid(params) == false) { return BLE_ERROR_PARAM_OUT_OF_RANGE; } @@ -894,7 +916,7 @@ uint8_t GenericGap::getMaxWhitelistSize(void) const ble_error_t GenericGap::getWhitelist(Whitelist_t &whitelist) const { - if(initialize_whitelist() == false) { + if (initialize_whitelist() == false) { return BLE_ERROR_INVALID_STATE; } @@ -916,7 +938,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) return BLE_ERROR_INVALID_PARAM; } - if(initialize_whitelist() == false) { + if (initialize_whitelist() == false) { return BLE_ERROR_INVALID_STATE; } @@ -926,7 +948,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // first evict devices not in the existing whitelist for (size_t i = 0; i < _whitelist.size; ++i) { - const BLEProtocol::Address_t& device = _whitelist.addresses[i]; + const BLEProtocol::Address_t &device = _whitelist.addresses[i]; if (is_in_whitelist(device, whitelist) == false) { ble_error_t err = _pal_gap.remove_device_from_whitelist( @@ -937,7 +959,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // try to restore the whitelist to its initial state if (err) { for (size_t j = 0; j < i; ++j) { - const BLEProtocol::Address_t& device = _whitelist.addresses[j]; + const BLEProtocol::Address_t &device = _whitelist.addresses[j]; if (is_in_whitelist(device, whitelist) == false) { _pal_gap.add_device_to_whitelist( @@ -953,7 +975,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // second add devices which were not in the initial whitelist for (size_t i = 0; i < whitelist.size; ++i) { - const BLEProtocol::Address_t& device = whitelist.addresses[i]; + const BLEProtocol::Address_t &device = whitelist.addresses[i]; if (is_in_whitelist(device, _whitelist) == false) { ble_error_t err = _pal_gap.add_device_to_whitelist( @@ -965,7 +987,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) if (err) { // first remove the devices added for (size_t j = 0; j < i; ++j) { - const BLEProtocol::Address_t& device = whitelist.addresses[j]; + const BLEProtocol::Address_t &device = whitelist.addresses[j]; if (is_in_whitelist(device, _whitelist) == false) { _pal_gap.remove_device_from_whitelist( @@ -977,7 +999,7 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) // second add the devices of the initial list evicted for (size_t i = 0; i < _whitelist.size; ++i) { - const BLEProtocol::Address_t& device = _whitelist.addresses[i]; + const BLEProtocol::Address_t &device = _whitelist.addresses[i]; if (is_in_whitelist(device, whitelist) == false) { _pal_gap.add_device_to_whitelist( @@ -1065,8 +1087,7 @@ ble_error_t GenericGap::startRadioScan(const GapScanningParams &scanningParams) pal::own_address_type_t own_address_type = get_own_address_type(CENTRAL_SCAN /* central, can use non resolvable address for scan requests */); - if(_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) - { + if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) { // Use non-resolvable static random address set_random_address_rotation(true); } @@ -1108,13 +1129,12 @@ ble_error_t GenericGap::initRadioNotification(void) ble_error_t GenericGap::enablePrivacy(bool enable) { - if(enable == _privacy_enabled) { + if (enable == _privacy_enabled) { // No change return BLE_ERROR_NONE; } - if(enable && !_pal_gap.is_privacy_supported()) - { + if (enable && !_pal_gap.is_privacy_supported()) { // Privacy is not supported by the implementation return BLE_ERROR_NOT_IMPLEMENTED; } @@ -1182,7 +1202,7 @@ ble_error_t GenericGap::setAdvertisingData(const GapAdvertisingData &advData, co ); } -ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams& params) +ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) { if (is_advertising_params_valid(params) == false) { return BLE_ERROR_INVALID_PARAM; @@ -1191,14 +1211,13 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams& params) // We can only use non resolvable addresses if the device is non connectable AddressUseType_t address_use_type = ((params.getAdvertisingType() == GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED) || - (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED)) ? + (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED)) ? PERIPHERAL_NON_CONNECTABLE : PERIPHERAL_CONNECTABLE; pal::own_address_type_t own_address_type = get_own_address_type(address_use_type); - if(_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) - { + if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) { // Use non-resolvable static random address set_random_address_rotation(true); } @@ -1263,7 +1282,8 @@ void GenericGap::processConnectionEvent( const ConnectionParams_t *connectionParams, const uint8_t *peerResolvableAddr, const uint8_t *localResolvableAddr -) { +) +{ if (_connection_event_handler) { _connection_event_handler->on_connected( handle, @@ -1294,7 +1314,8 @@ BLE_DEPRECATED_API_USE_END() void GenericGap::processDisconnectionEvent( Handle_t handle, DisconnectionReason_t reason -) { +) +{ if (_connection_event_handler) { _connection_event_handler->on_disconnected( handle, @@ -1359,31 +1380,31 @@ BLE_DEPRECATED_API_USE_BEGIN() BLE_DEPRECATED_API_USE_END() } -void GenericGap::on_gap_event_received(const pal::GapEvent& e) +void GenericGap::on_gap_event_received(const pal::GapEvent &e) { switch (e.type.value()) { case pal::GapEventType::ADVERTISING_REPORT: - on_advertising_report(static_cast(e)); + on_advertising_report(static_cast(e)); break; case pal::GapEventType::CONNECTION_COMPLETE: - on_connection_complete(static_cast(e)); + on_connection_complete(static_cast(e)); break; case pal::GapEventType::CONNECTION_UPDATE: - on_connection_update(static_cast(e)); + on_connection_update(static_cast(e)); break; case pal::GapEventType::DISCONNECTION_COMPLETE: - on_disconnection_complete(static_cast(e)); + on_disconnection_complete(static_cast(e)); break; case pal::GapEventType::REMOTE_CONNECTION_PARAMETER_REQUEST: - on_connection_parameter_request(static_cast(e)); + on_connection_parameter_request(static_cast(e)); break; case pal::GapEventType::UNEXPECTED_ERROR: - on_unexpected_error(static_cast(e)); + on_unexpected_error(static_cast(e)); break; default: @@ -1391,13 +1412,13 @@ void GenericGap::on_gap_event_received(const pal::GapEvent& e) } } -void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent& e) +void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent &e) { for (size_t i = 0; i < e.size(); ++i) { pal::GapAdvertisingReportEvent::advertising_t advertising = e[i]; // Check if the address hasn't been resolved - if(_privacy_enabled && + if (_privacy_enabled && _central_privacy_configuration.resolution_strategy == CentralPrivacyConfiguration_t::RESOLVE_AND_FILTER && advertising.address_type == pal::connection_peer_address_type_t::RANDOM_ADDRESS && is_random_private_resolvable_address(advertising.address.data()) @@ -1425,7 +1446,7 @@ BLE_DEPRECATED_API_USE_END() } } -void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent& e) +void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent &e) { if (e.status != pal::hci_error_code_t::SUCCESS) { // for now notify user that the connection failled by issuing a timeout @@ -1454,7 +1475,7 @@ BLE_DEPRECATED_API_USE_END() } if (random_address_type == RandomAddressType_t::RESOLVABLE_PRIVATE) { - switch(_peripheral_privacy_configuration.resolution_strategy) { + switch (_peripheral_privacy_configuration.resolution_strategy) { case PeripheralPrivacyConfiguration_t::REJECT_NON_RESOLVED_ADDRESS: // Reject connection request - the user will get notified through a callback _pal_gap.disconnect( @@ -1514,17 +1535,17 @@ BLE_DEPRECATED_API_USE_END() ); // Now starts pairing or authentication procedures if required - if(needs_pairing) { + if (needs_pairing) { SecurityManager &sm = createBLEInstance()->getSecurityManager(); // Request authentication to start pairing procedure sm.requestAuthentication(e.connection_handle); - } else if(needs_authentication) { + } else if (needs_authentication) { // TODO: GAP Authentication != Security Manager authentication // Needs to be implemented } } -void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEvent& e) +void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEvent &e) { if (e.status == pal::hci_error_code_t::SUCCESS) { processDisconnectionEvent( @@ -1536,7 +1557,7 @@ void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEv } } -void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionParameterRequestEvent& e) +void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionParameterRequestEvent &e) { // intern behavior, accept all new parameter requests // TODO: expose an API so user code can accept or reject such request @@ -1551,13 +1572,13 @@ void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionP ); } -void GenericGap::on_connection_update(const pal::GapConnectionUpdateEvent& e) +void GenericGap::on_connection_update(const pal::GapConnectionUpdateEvent &e) { // TODO: add feature in interface to notify the user that the connection // has been updated. } -void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent& e) +void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent &e) { // TODO: add feature in interface to notify the user that the connection // has been updated. @@ -1565,16 +1586,16 @@ void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent& e) pal::own_address_type_t GenericGap::get_own_address_type(AddressUseType_t address_use_type) { - if(_privacy_enabled) { + if (_privacy_enabled) { bool use_non_resolvable_address = false; - if(address_use_type == CENTRAL_SCAN) { + if (address_use_type == CENTRAL_SCAN) { use_non_resolvable_address = _central_privacy_configuration.use_non_resolvable_random_address; } else if (address_use_type == PERIPHERAL_NON_CONNECTABLE) { use_non_resolvable_address = _peripheral_privacy_configuration.use_non_resolvable_random_address; } // An non resolvable private address should be generated - if(use_non_resolvable_address) { + if (use_non_resolvable_address) { return pal::own_address_type_t::RANDOM_ADDRESS; } @@ -1606,7 +1627,7 @@ bool GenericGap::initialize_whitelist() const return false; } - _whitelist.addresses = new (std::nothrow) BLEProtocol::Address_t[whitelist_capacity] ; + _whitelist.addresses = new(std::nothrow) BLEProtocol::Address_t[whitelist_capacity]; if (_whitelist.addresses == NULL) { return false; } @@ -1622,7 +1643,7 @@ ble_error_t GenericGap::update_address_resolution_setting() // Only disable if privacy is disabled or resolution is not requested in either central or peripheral mode bool enable = true; - if(!_privacy_enabled) { + if (!_privacy_enabled) { enable = false; } else if( (_peripheral_privacy_configuration.resolution_strategy == PeripheralPrivacyConfiguration_t::DO_NOT_RESOLVE) @@ -1635,13 +1656,13 @@ ble_error_t GenericGap::update_address_resolution_setting() void GenericGap::set_random_address_rotation(bool enable) { - if(enable == _random_address_rotating) { + if (enable == _random_address_rotating) { return; } _random_address_rotating = enable; - if(enable) { + if (enable) { // Set first address update_random_address(); @@ -1650,8 +1671,7 @@ void GenericGap::set_random_address_rotation(bool enable) mbed::callback(this, &GenericGap::on_address_rotation_timeout), 15 * 60 * 1000000U ); - } - else { + } else { // Stop ticker _address_rotation_ticker.detach(); @@ -1664,8 +1684,7 @@ void GenericGap::set_random_address_rotation(bool enable) void GenericGap::update_random_address() { - if(!_random_address_rotating) - { + if (!_random_address_rotating) { // This event might have been queued before we disabled address rotation return; } @@ -1681,7 +1700,7 @@ void GenericGap::update_random_address() /* ignore the error, if it fails to cycle because it's connectable */ _pal_gap.set_advertising_set_random_address( - (advertising_handle_t)i, + (advertising_handle_t) i, address ); } @@ -1706,7 +1725,8 @@ void GenericGap::update_random_address() _address = address; } -bool GenericGap::getUnresolvableRandomAddress(ble::address_t& address) { +bool GenericGap::getUnresolvableRandomAddress(ble::address_t &address) +{ do { byte_array_t<8> random_data; @@ -1723,8 +1743,7 @@ bool GenericGap::getUnresolvableRandomAddress(ble::address_t& address) { // Copy to address - will copy first 6 bytes address = ble::address_t(random_data.data()); - if(!is_random_private_non_resolvable_address(address.data())) - { + if (!is_random_private_non_resolvable_address(address.data())) { // If address is invalid, which is unlikely (all 0s or all 1s), try again // If implementation is faulty, we'll get stuck here continue; @@ -1732,7 +1751,8 @@ bool GenericGap::getUnresolvableRandomAddress(ble::address_t& address) { // Address is valid break; - } while(true); + } + while (true); return true; } @@ -1794,7 +1814,8 @@ ble_error_t GenericGap::createAdvertisingSet( return BLE_ERROR_NO_MEM; } -ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) { +ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) +{ if (is_extended_advertising_available()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1831,7 +1852,8 @@ ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) { ble_error_t GenericGap::setAdvertisingParameters( advertising_handle_t handle, const AdvertisingParameters ¶ms -) { +) +{ if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -1909,7 +1931,8 @@ ble_error_t GenericGap::setAdvertisingPayload( advertising_handle_t handle, mbed::Span payload, bool minimiseFragmentation -) { +) +{ return setAdvertisingData(handle, payload, minimiseFragmentation, false); } @@ -1917,7 +1940,8 @@ ble_error_t GenericGap::setAdvertisingScanResponse( advertising_handle_t handle, mbed::Span response, bool minimiseFragmentation -) { +) +{ return setAdvertisingData(handle, response, minimiseFragmentation, true); } @@ -1926,12 +1950,13 @@ ble_error_t GenericGap::setAdvertisingData( mbed::Span payload, bool minimiseFragmentation, bool scan_response -) { +) +{ // type declarations typedef pal::advertising_fragment_description_t op_t; typedef ble_error_t (pal::Gap::*legacy_set_data_fn_t)( - uint8_t , - const pal::advertising_data_t& + uint8_t, + const pal::advertising_data_t & ); typedef ble_error_t (pal::Gap::*set_data_fn_t)( advertising_handle_t advertising_handle, @@ -2020,7 +2045,8 @@ ble_error_t GenericGap::startAdvertising( advertising_handle_t handle, adv_duration_t maxDuration, uint8_t maxEvents -) { +) +{ ble_error_t error = BLE_ERROR_NONE; if (handle >= getMaxAdvertisingSetNumber()) { @@ -2082,7 +2108,8 @@ ble_error_t GenericGap::startAdvertising( return error; } -ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) { +ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) +{ if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2112,7 +2139,8 @@ ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) { ); } -bool GenericGap::isAdvertisingActive(advertising_handle_t handle) { +bool GenericGap::isAdvertisingActive(advertising_handle_t handle) +{ if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2289,7 +2317,8 @@ void GenericGap::on_enhanced_connection_complete( uint16_t connection_latency, uint16_t supervision_timeout, pal::clock_accuracy_t master_clock_accuracy -) { +) +{ if (!_eventHandler) { return; } @@ -2297,9 +2326,9 @@ void GenericGap::on_enhanced_connection_complete( _eventHandler->onConnectionComplete( ConnectionCompleteEvent( (status == pal::hci_error_code_t::SUCCESS) ? BLE_ERROR_NONE : BLE_ERROR_INTERNAL_STACK_FAILURE, - (connection_handle_t)connection_handle, + (connection_handle_t) connection_handle, own_role, - (peer_address_type_t::type)peer_address_type.value(), + (peer_address_type_t::type) peer_address_type.value(), peer_address, local_resolvable_private_address, peer_resolvable_private_address, @@ -2464,7 +2493,8 @@ void GenericGap::on_connection_update_complete( uint16_t connection_interval, uint16_t connection_latency, uint16_t supervision_timeout -) { +) +{ if (!_eventHandler) { return; } @@ -2486,7 +2516,8 @@ void GenericGap::on_remote_connection_parameter( uint16_t connection_interval_max, uint16_t connection_latency, uint16_t supervision_timeout -) { +) +{ if (_user_manage_connection_parameter_requests) { // ignore for now as it is _pal_gap.accept_connection_parameter_request( @@ -2569,8 +2600,7 @@ ble_error_t GenericGap::startScan( { useVersionTwoAPI(); - if(_privacy_enabled && _central_privacy_configuration.use_non_resolvable_random_address) - { + if (_privacy_enabled && _central_privacy_configuration.use_non_resolvable_random_address) { set_random_address_rotation(true); } @@ -2642,7 +2672,8 @@ ble_error_t GenericGap::createSync( ble_error_t GenericGap::createSync( slave_latency_t maxPacketSkip, sync_timeout_t timeout -) { +) +{ if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2704,7 +2735,7 @@ ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( peer_address_type_t peerAddressType, - const ble::address_t &peerAddress, + const ble::address_t &peerAddress, advertising_sid_t sid ) { From e9637c419ab70059f58dc6807afb08846d903f00 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 15:29:43 +0000 Subject: [PATCH 284/361] BLE: Remove ble::clamp as it is not used anywhere. --- features/FEATURE_BLE/ble/BLETypes.h | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 4e956fda21..96f0ce6d86 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -33,16 +33,6 @@ namespace ble { -/* replace with std::clamp when it arrives */ -template -void clamp(T& value, const R& min, const R& max) { - if (value > max) { - value = max; - } else if (value < min) { - value = min; - } -} - /** Special advertising set handle used for the legacy advertising set. */ static const advertising_handle_t LEGACY_ADVERTISING_HANDLE = 0x00; From 2a08549b8d43c7ef6765f28e0792d54388adfc18 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 15:41:08 +0000 Subject: [PATCH 285/361] BLE: rename ble::Forever into ble::Value. --- features/FEATURE_BLE/ble/common/Duration.h | 13 +++++++------ features/FEATURE_BLE/ble/gap/Types.h | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index f4bdd2f3eb..240ff72dbc 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -68,13 +68,14 @@ struct DefaultRange { }; /** - * Represent the forever value that can be used in Duration. + * Represent an integral compile time value that can be used in Duration. * + * @tparam T Type of the integral value. * @tparam V The integer value representing a never ending duration. */ -template -struct Forever { - static const uint32_t VALUE = V; +template +struct Value { + static const T VALUE = V; }; /** @@ -513,8 +514,8 @@ const uint32_t Range::MIN; template const uint32_t Range::MAX; -template -const uint32_t Forever::VALUE; +template +const T Value::VALUE; template const uint32_t Duration::TIME_BASE; diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index d8f7c54e82..39b49d791c 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -25,8 +25,8 @@ namespace ble { /* BLE units, using microseconds as the common denominator */ typedef Duration > adv_interval_t; -typedef Duration, Forever<0x0000> > adv_duration_t; -typedef Duration, Forever<0x0000> > scan_duration_t; +typedef Duration, Value > adv_duration_t; +typedef Duration, Value > scan_duration_t; typedef Duration > scan_period_t; typedef Duration > scan_interval_t; typedef Duration > scan_window_t; From d32354a7a612c55a5a3e73ba22b7ec4ecfda78a4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 17:02:09 +0000 Subject: [PATCH 286/361] BLE: Fix compiler warning about unused variable. --- features/FEATURE_BLE/source/Gap.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/Gap.cpp index bd6c353f16..5ce1f0fbcd 100644 --- a/features/FEATURE_BLE/source/Gap.cpp +++ b/features/FEATURE_BLE/source/Gap.cpp @@ -234,7 +234,6 @@ void Gap::getPermittedTxPowerValues( ) { /* Avoid compiler warnings about unused variables. */ (void)valueArrayPP; - (void)countP; /* Requesting action from porter(s): override this API if this capability is supported. */ From 27dd08431e48c86ec2d305c1e6ea6d03993aeaca Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 17:22:34 +0000 Subject: [PATCH 287/361] BLE: remove ble::pal::extended_advertising_report_event_type_t as it is not used. --- features/FEATURE_BLE/ble/pal/GapTypes.h | 54 ------------------------- 1 file changed, 54 deletions(-) diff --git a/features/FEATURE_BLE/ble/pal/GapTypes.h b/features/FEATURE_BLE/ble/pal/GapTypes.h index c00d50a970..688a09cc71 100644 --- a/features/FEATURE_BLE/ble/pal/GapTypes.h +++ b/features/FEATURE_BLE/ble/pal/GapTypes.h @@ -600,60 +600,6 @@ typedef ble::periodic_sync_handle_t sync_handle_t; typedef ble::advertising_data_status_t advertising_data_status_t; -struct extended_advertising_report_event_type_t { - extended_advertising_report_event_type_t(uint8_t value) : value(value) - { - } - - bool connectable() - { - return static_cast(value & (1 << 0)); - } - - bool scannable_advertising() - { - return static_cast(value & (1 << 1)); - } - - bool directed_advertising() - { - return static_cast(value & (1 << 2)); - } - - bool scan_response() - { - return static_cast(value & (1 << 3)); - } - - bool legacy_advertising() - { - return static_cast(value & (1 << 4)); - } - - advertising_data_status_t data_status() - { - return static_cast((value >> 5) & 0x03); - } - - bool complete() - { - return data_status() == advertising_data_status_t::COMPLETE; - } - - bool more_data_to_come() - { - return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; - } - - bool truncated() - { - return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; - } - -private: - uint8_t value; -}; - struct direct_address_type_t : SafeEnum { enum type { /** From 76416b2f47ed59dc789c82e379c11665e854031a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 17:28:26 +0000 Subject: [PATCH 288/361] BLE: Improve implementation readability of ble::advertising_event_t --- features/FEATURE_BLE/ble/gap/Types.h | 37 +++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 39b49d791c..c267d2dab3 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -137,6 +137,27 @@ struct advertising_data_status_t : SafeEnum /** Properties of an advertising event. */ struct advertising_event_t { + +private: + // Implementation note: The object is constructed from the field Event_Type + // of an LE Extended Advertising. + // Indexes and functions of bits are defined in BLUETOOTH SPECIFICATION + // Version 5.0 | Vol 2, Part E - + // Section 7.7.65.13 LE Extended Advertising report Event + enum { + CONNECTABLE_BIT = 0, + SCANNABLE_ADVERTISING_BIT = 1, + DIRECTED_ADVERTISING_BIT = 2, + SCAN_RESPONSE_BIT = 3, + LEGACY_PDU_BIT = 4, + DATA_STATUS_INDEX = 5, + DATA_STATUS_MASK = 0x03 + }; + +public: + +#if !defined(DOXYGEN_ONLY) + /** Create based on a raw value. * * @param value @@ -145,13 +166,15 @@ struct advertising_event_t { { } +#endif + /** Is advertising connectable. * * @return True if connectable. */ bool connectable() const { - return static_cast(value & (1 << 0)); + return static_cast(value & (1 << CONNECTABLE_BIT)); } /** Is advertising scannable. @@ -160,7 +183,7 @@ struct advertising_event_t { */ bool scannable_advertising() const { - return static_cast(value & (1 << 1)); + return static_cast(value & (1 << SCANNABLE_ADVERTISING_BIT)); } /** Is advertising directed. @@ -169,7 +192,7 @@ struct advertising_event_t { */ bool directed_advertising() const { - return static_cast(value & (1 << 2)); + return static_cast(value & (1 << DIRECTED_ADVERTISING_BIT)); } /** Is this a scan response. @@ -178,7 +201,7 @@ struct advertising_event_t { */ bool scan_response() const { - return static_cast(value & (1 << 3)); + return static_cast(value & (1 << SCAN_RESPONSE_BIT)); } /** Is this legacy advertising. @@ -187,7 +210,7 @@ struct advertising_event_t { */ bool legacy_advertising() const { - return static_cast(value & (1 << 4)); + return static_cast(value & (1 << LEGACY_PDU_BIT)); } /** Payload completeness status. @@ -196,7 +219,9 @@ struct advertising_event_t { */ advertising_data_status_t data_status() const { - return static_cast((value >> 5) & 0x03); + return static_cast( + (value >> DATA_STATUS_INDEX) & DATA_STATUS_MASK + ); } /** Is payload complete. From 30c6432b5dfcac1ebf55ec0560b32837f00c06d6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 17:33:06 +0000 Subject: [PATCH 289/361] BLE: Address code formating issue in CordioPalGap implementation. --- .../TARGET_CORDIO/source/CordioPalGap.cpp | 214 +++++++++++------- 1 file changed, 128 insertions(+), 86 deletions(-) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp index d2034d4fd0..1179fa776e 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalGap.cpp @@ -25,29 +25,35 @@ namespace cordio { bool Gap::is_feature_supported( ble::controller_supported_features_t feature -) { +) +{ return (HciGetLeSupFeat() & (1 << feature.value())); } -ble_error_t Gap::initialize() { +ble_error_t Gap::initialize() +{ return BLE_ERROR_NONE; } -ble_error_t Gap::terminate() { +ble_error_t Gap::terminate() +{ return BLE_ERROR_NONE; } -address_t Gap::get_device_address() { +address_t Gap::get_device_address() +{ return address_t(HciGetBdAddr()); } -address_t Gap::get_random_address() { +address_t Gap::get_random_address() +{ return device_random_address; } -ble_error_t Gap::set_random_address(const address_t& address) { +ble_error_t Gap::set_random_address(const address_t &address) +{ device_random_address = address; - DmDevSetRandAddr(const_cast(address.data())); + DmDevSetRandAddr(const_cast(address.data())); return BLE_ERROR_NONE; } @@ -57,10 +63,11 @@ ble_error_t Gap::set_advertising_parameters( advertising_type_t advertising_type, own_address_type_t own_address_type, advertising_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, advertising_channel_map_t advertising_channel_map, advertising_filter_policy_t advertising_filter_policy -) { +) +{ DmAdvSetInterval( DM_ADV_HANDLE_DEFAULT, advertising_interval_min, @@ -83,7 +90,7 @@ ble_error_t Gap::set_advertising_parameters( DM_ADV_HANDLE_DEFAULT, advertising_type.value(), peer_address_type.value(), - const_cast(peer_address.data()) + const_cast(peer_address.data()) ); return BLE_ERROR_NONE; @@ -91,40 +98,43 @@ ble_error_t Gap::set_advertising_parameters( ble_error_t Gap::set_advertising_data( uint8_t advertising_data_length, - const advertising_data_t& advertising_data -) { + const advertising_data_t &advertising_data +) +{ DmAdvSetData( DM_ADV_HANDLE_DEFAULT, HCI_ADV_DATA_OP_COMP_FRAG, DM_DATA_LOC_ADV, advertising_data_length, - const_cast(advertising_data.data()) + const_cast(advertising_data.data()) ); return BLE_ERROR_NONE; } ble_error_t Gap::set_scan_response_data( uint8_t scan_response_data_length, - const advertising_data_t& scan_response_data -) { + const advertising_data_t &scan_response_data +) +{ DmAdvSetData( DM_ADV_HANDLE_DEFAULT, HCI_ADV_DATA_OP_COMP_FRAG, DM_DATA_LOC_SCAN, scan_response_data_length, - const_cast(scan_response_data.data()) + const_cast(scan_response_data.data()) ); return BLE_ERROR_NONE; } -ble_error_t Gap::advertising_enable(bool enable) { +ble_error_t Gap::advertising_enable(bool enable) +{ if (enable) { - uint8_t adv_handles[] = { DM_ADV_HANDLE_DEFAULT }; - uint16_t adv_durations[] = { /* infinite */ 0 }; - uint8_t max_ea_events[] = { 0 }; + uint8_t adv_handles[] = {DM_ADV_HANDLE_DEFAULT}; + uint16_t adv_durations[] = { /* infinite */ 0}; + uint8_t max_ea_events[] = {0}; DmAdvStart(1, adv_handles, adv_durations, max_ea_events); } else { - uint8_t adv_handles[] = { DM_ADV_HANDLE_DEFAULT }; + uint8_t adv_handles[] = {DM_ADV_HANDLE_DEFAULT}; DmAdvStop(1, adv_handles); } return BLE_ERROR_NONE; @@ -136,7 +146,8 @@ ble_error_t Gap::set_scan_parameters( uint16_t scan_window, own_address_type_t own_address_type, scanning_filter_policy_t filter_policy -) { +) +{ use_active_scanning = active_scanning; DmScanSetInterval(HCI_INIT_PHY_LE_1M_BIT, &scan_interval, &scan_window); DmScanSetAddrType(own_address_type.value()); @@ -150,7 +161,8 @@ ble_error_t Gap::set_scan_parameters( ble_error_t Gap::scan_enable( bool enable, bool filter_duplicates -) { +) +{ if (enable) { uint8_t scanType = use_active_scanning ? DM_SCAN_TYPE_ACTIVE : DM_SCAN_TYPE_PASSIVE; DmScanStart( @@ -172,7 +184,7 @@ ble_error_t Gap::create_connection( uint16_t scan_window, initiator_policy_t initiator_policy, connection_peer_address_type_t peer_address_type, - const address_t& peer_address, + const address_t &peer_address, own_address_type_t own_address_type, uint16_t connection_interval_min, uint16_t connection_interval_max, @@ -180,7 +192,8 @@ ble_error_t Gap::create_connection( uint16_t supervision_timeout, uint16_t minimum_connection_event_length, uint16_t maximum_connection_event_length -) { +) +{ DmConnSetScanInterval(scan_interval, scan_window); DmDevSetFilterPolicy(DM_FILT_POLICY_MODE_INIT, initiator_policy.value()); DmConnSetAddrType(own_address_type.value()); @@ -199,7 +212,7 @@ ble_error_t Gap::create_connection( DM_CLIENT_ID_APP, HCI_INIT_PHY_LE_1M_BIT, peer_address_type.value(), - const_cast(peer_address.data()) + const_cast(peer_address.data()) ); if (connection_id == DM_CONN_ID_NONE) { @@ -209,7 +222,8 @@ ble_error_t Gap::create_connection( return BLE_ERROR_NONE; } -ble_error_t Gap::cancel_connection_creation() { +ble_error_t Gap::cancel_connection_creation() +{ DmConnClose( DM_CLIENT_ID_APP, /* connection handle - invalid */ DM_CONN_ID_NONE, @@ -218,11 +232,13 @@ ble_error_t Gap::cancel_connection_creation() { return BLE_ERROR_NONE; } -uint8_t Gap::read_white_list_capacity() { +uint8_t Gap::read_white_list_capacity() +{ return HciGetWhiteListSize(); } -ble_error_t Gap::clear_whitelist() { +ble_error_t Gap::clear_whitelist() +{ DmDevWhiteListClear(); return BLE_ERROR_NONE; } @@ -230,10 +246,11 @@ ble_error_t Gap::clear_whitelist() { ble_error_t Gap::add_device_to_whitelist( whitelist_address_type_t address_type, address_t address -) { +) +{ DmDevWhiteListAdd( address_type.value(), - const_cast(address.data()) + const_cast(address.data()) ); return BLE_ERROR_NONE; } @@ -241,10 +258,11 @@ ble_error_t Gap::add_device_to_whitelist( ble_error_t Gap::remove_device_from_whitelist( whitelist_address_type_t address_type, address_t address -) { +) +{ DmDevWhiteListRemove( address_type.value(), - const_cast(address.data()) + const_cast(address.data()) ); return BLE_ERROR_NONE; } @@ -257,7 +275,8 @@ ble_error_t Gap::connection_parameters_update( uint16_t supervision_timeout, uint16_t minimum_connection_event_length, uint16_t maximum_connection_event_length -) { +) +{ if (DmConnCheckIdle(connection) != 0) { return BLE_ERROR_INVALID_STATE; } @@ -286,7 +305,8 @@ ble_error_t Gap::accept_connection_parameter_request( uint16_t supervision_timeout, uint16_t minimum_connection_event_length, uint16_t maximum_connection_event_length -) { +) +{ hciConnSpec_t connection_spec = { interval_min, interval_max, @@ -302,7 +322,8 @@ ble_error_t Gap::accept_connection_parameter_request( ble_error_t Gap::reject_connection_parameter_request( connection_handle_t connection_handle, hci_error_code_t rejection_reason -) { +) +{ DmRemoteConnParamReqNegReply( connection_handle, rejection_reason.value() @@ -313,7 +334,8 @@ ble_error_t Gap::reject_connection_parameter_request( ble_error_t Gap::disconnect( connection_handle_t connection, disconnection_reason_t disconnection_reason -) { +) +{ DmConnClose( DM_CLIENT_ID_APP, connection, @@ -322,19 +344,22 @@ ble_error_t Gap::disconnect( return BLE_ERROR_NONE; } -bool Gap::is_privacy_supported() { +bool Gap::is_privacy_supported() +{ // We only support controller-based privacy, so return whether the controller supports it return HciLlPrivacySupported(); } ble_error_t Gap::set_address_resolution( bool enable -) { +) +{ DmPrivSetAddrResEnable(enable); return BLE_ERROR_NONE; } -ble_error_t Gap::read_phy(connection_handle_t connection) { +ble_error_t Gap::read_phy(connection_handle_t connection) +{ if (is_feature_supported(controller_supported_features_t::LE_2M_PHY) || is_feature_supported(controller_supported_features_t::LE_CODED_PHY)) { DmReadPhy(connection); @@ -344,9 +369,10 @@ ble_error_t Gap::read_phy(connection_handle_t connection) { } ble_error_t Gap::set_preferred_phys( - const phy_set_t& tx_phys, - const phy_set_t& rx_phys -) { + const phy_set_t &tx_phys, + const phy_set_t &rx_phys +) +{ DmSetDefaultPhy( create_all_phys_value(tx_phys, rx_phys), tx_phys.value(), @@ -358,10 +384,11 @@ ble_error_t Gap::set_preferred_phys( ble_error_t Gap::set_phy( connection_handle_t connection, - const phy_set_t& tx_phys, - const phy_set_t& rx_phys, + const phy_set_t &tx_phys, + const phy_set_t &rx_phys, coded_symbol_per_bit_t coded_symbol -) { +) +{ /* if phy set is empty set corresponding all_phys bit to 1 */ uint8_t all_phys = 0; if (tx_phys.value() == 0) { @@ -383,7 +410,8 @@ ble_error_t Gap::set_phy( } // singleton of the ARM Cordio client -Gap& Gap::get_gap() { +Gap &Gap::get_gap() +{ static Gap _gap; return _gap; } @@ -391,53 +419,56 @@ Gap& Gap::get_gap() { /** * Callback which handle wsfMsgHdr_t and forward them to emit_gap_event. */ -void Gap::gap_handler(const wsfMsgHdr_t* msg) { - typedef bool (*event_handler_t)(const wsfMsgHdr_t* msg); +void Gap::gap_handler(const wsfMsgHdr_t *msg) +{ + typedef bool (*event_handler_t)(const wsfMsgHdr_t *msg); if (msg == NULL) { return; } - connection_handle_t handle = (connection_handle_t)msg->param; + connection_handle_t handle = (connection_handle_t) msg->param; EventHandler *handler = get_gap()._pal_event_handler; - switch(msg->event) { + switch (msg->event) { case DM_PHY_READ_IND: { if (!handler) { break; } - const hciLeReadPhyCmdCmplEvt_t* evt = (const hciLeReadPhyCmdCmplEvt_t*)msg; + const hciLeReadPhyCmdCmplEvt_t *evt = (const hciLeReadPhyCmdCmplEvt_t *) msg; handler->on_read_phy( - (hci_error_code_t::type)msg->status, + (hci_error_code_t::type) msg->status, handle, - (ble::phy_t::type)evt->txPhy, - (ble::phy_t::type)evt->rxPhy + (ble::phy_t::type) evt->txPhy, + (ble::phy_t::type) evt->rxPhy ); - } break; + } + break; case DM_PHY_UPDATE_IND: { if (!handler) { break; } - const hciLePhyUpdateEvt_t* evt = (const hciLePhyUpdateEvt_t*)msg; + const hciLePhyUpdateEvt_t *evt = (const hciLePhyUpdateEvt_t *) msg; handler->on_phy_update_complete( - (hci_error_code_t::type)msg->status, + (hci_error_code_t::type) msg->status, handle, - (ble::phy_t::type)evt->txPhy, - (ble::phy_t::type)evt->rxPhy + (ble::phy_t::type) evt->txPhy, + (ble::phy_t::type) evt->rxPhy ); - } break; + } + break; case DM_PER_ADV_SYNC_EST_IND: { if (!handler) { break; } - const hciLePerAdvSyncEstEvt_t* evt = (const hciLePerAdvSyncEstEvt_t*) msg; + const hciLePerAdvSyncEstEvt_t *evt = (const hciLePerAdvSyncEstEvt_t *) msg; handler->on_periodic_advertising_sync_established( hci_error_code_t(evt->status), @@ -449,14 +480,15 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->perAdvInterval, clock_accuracy_t(evt->clockAccuracy) ); - } break; + } + break; case DM_PER_ADV_REPORT_IND: { if (!handler) { break; } - const hciLePerAdvReportEvt_t* evt = (const hciLePerAdvReportEvt_t*) msg; + const hciLePerAdvReportEvt_t *evt = (const hciLePerAdvReportEvt_t *) msg; handler->on_periodic_advertising_report( evt->syncHandle, @@ -466,16 +498,18 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->len, evt->pData ); - } break; + } + break; case DM_PER_ADV_SYNC_LOST_IND: { if (!handler) { break; } - const hciLePerAdvSyncLostEvt_t* evt = (const hciLePerAdvSyncLostEvt_t*) msg; + const hciLePerAdvSyncLostEvt_t *evt = (const hciLePerAdvSyncLostEvt_t *) msg; handler->on_periodic_advertising_sync_loss(evt->syncHandle); - } break; + } + break; case DM_CONN_OPEN_IND: { if (!handler) { @@ -483,7 +517,7 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { } // TODO: filter with old event ... - const hciLeConnCmplEvt_t* evt = (const hciLeConnCmplEvt_t*) msg; + const hciLeConnCmplEvt_t *evt = (const hciLeConnCmplEvt_t *) msg; handler->on_enhanced_connection_complete( hci_error_code_t(evt->status), evt->handle, @@ -497,56 +531,60 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->supTimeout, clock_accuracy_t(evt->clockAccuracy) ); - } break; + } + break; case DM_SCAN_REQ_RCVD_IND: { if (!handler) { break; } - const hciLeScanReqRcvdEvt_t* evt = (const hciLeScanReqRcvdEvt_t*) msg; + const hciLeScanReqRcvdEvt_t *evt = (const hciLeScanReqRcvdEvt_t *) msg; handler->on_scan_request_received( evt->advHandle, connection_peer_address_type_t(evt->scanAddrType), evt->scanAddr ); - } break; + } + break; case DM_ADV_SET_STOP_IND: { if (!handler) { break; } - const hciLeAdvSetTermEvt_t* evt = (const hciLeAdvSetTermEvt_t*) msg; + const hciLeAdvSetTermEvt_t *evt = (const hciLeAdvSetTermEvt_t *) msg; handler->on_advertising_set_terminated( hci_error_code_t(evt->status), evt->advHandle, evt->handle, evt->numComplEvts ); - } break; + } + break; case DM_EXT_SCAN_STOP_IND: { if (!handler) { break; } - const hciLeScanTimeoutEvt_t* evt = (const hciLeScanTimeoutEvt_t*) msg; + const hciLeScanTimeoutEvt_t *evt = (const hciLeScanTimeoutEvt_t *) msg; handler->on_scan_timeout(); - } break; + } + break; case DM_EXT_SCAN_REPORT_IND: { if (!handler) { break; } - const hciLeExtAdvReportEvt_t* evt = (const hciLeExtAdvReportEvt_t*) msg; + const hciLeExtAdvReportEvt_t *evt = (const hciLeExtAdvReportEvt_t *) msg; connection_peer_address_type_t addr_type(evt->addrType); phy_t sec_phy(evt->secPhy); handler->on_extended_advertising_report( advertising_event_t(evt->eventType), - (evt->addrType == HCI_ADDR_TYPE_ANONYMOUS) ? NULL : &addr_type, + (evt->addrType == HCI_ADDR_TYPE_ANONYMOUS) ? NULL : &addr_type, evt->addr, phy_t(evt->priPhy), evt->secPhy == HCI_ADV_RPT_PHY_SEC_NONE ? NULL : &sec_phy, @@ -559,14 +597,15 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->len, evt->pData ); - } break; + } + break; case DM_CONN_UPDATE_IND: { if (!handler) { break; } - const hciLeConnUpdateCmplEvt_t* evt = (const hciLeConnUpdateCmplEvt_t*) msg; + const hciLeConnUpdateCmplEvt_t *evt = (const hciLeConnUpdateCmplEvt_t *) msg; handler->on_connection_update_complete( (hci_error_code_t::type) evt->status, evt->hdr.param, @@ -574,14 +613,15 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->connLatency, evt->supTimeout ); - } break; + } + break; case DM_REM_CONN_PARAM_REQ_IND: { if (!handler) { break; } - const hciLeRemConnParamReqEvt_t* evt = (const hciLeRemConnParamReqEvt_t*) msg; + const hciLeRemConnParamReqEvt_t *evt = (const hciLeRemConnParamReqEvt_t *) msg; handler->on_remote_connection_parameter( evt->hdr.param, evt->intervalMin, @@ -589,7 +629,8 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { evt->latency, evt->timeout ); - } break; + } + break; } // all handlers are stored in a static array @@ -605,7 +646,7 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { // traverse all handlers and execute them with the event in input. // exit if an handler has handled the event. - for(size_t i = 0; i < (sizeof(handlers)/sizeof(handlers[0])); ++i) { + for (size_t i = 0; i < (sizeof(handlers) / sizeof(handlers[0])); ++i) { if (handlers[i](msg)) { return; } @@ -616,9 +657,10 @@ void Gap::gap_handler(const wsfMsgHdr_t* msg) { * T shall define a can_convert and convert function and a type */ template -bool Gap::event_handler(const wsfMsgHdr_t* msg) { +bool Gap::event_handler(const wsfMsgHdr_t *msg) +{ if (T::can_convert(msg)) { - get_gap().emit_gap_event(T::convert((const typename T::type*)msg)); + get_gap().emit_gap_event(T::convert((const typename T::type *) msg)); return true; } return false; @@ -789,7 +831,7 @@ ble_error_t Gap::extended_advertising_enable( ) { if (enable) { - uint16_t* durations_ms = new uint16_t[number_of_sets]; + uint16_t *durations_ms = new uint16_t[number_of_sets]; for (size_t i = 0; i < number_of_sets; ++i) { uint32_t r = durations[i] * 10; durations_ms[i] = r > 0xFFFF ? 0xFFFF : r; From eda3bfb0e3c548caca98764e1af5fc4c1a525abb Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:25:12 +0000 Subject: [PATCH 290/361] BLE: Explain magic constant in ble::Gap implementation. --- features/FEATURE_BLE/source/gap/Gap.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index d61cec786f..659c33adbc 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -26,13 +26,14 @@ bool Gap::isFeatureSupported(controller_supported_features_t feature) uint8_t Gap::getMaxAdvertisingSetNumber() { /* Requesting action from porter(s): override this API if this capability is supported. */ + // There is at least one advertising set available: the legacy advertising set return 1; } uint8_t Gap::getMaxAdvertisingDataLength() { /* Requesting action from porter(s): override this API if this capability is supported. */ - return 0x1F; + return LEGACY_ADVERTISING_MAX_SIZE; } ble_error_t Gap::createAdvertisingSet( From ce2460a92a6783db8135d39506a32b10f0f1a040 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:25:49 +0000 Subject: [PATCH 291/361] BLE: expose representation type and pointer to the inner storage in SafeEnum. --- features/FEATURE_BLE/ble/SafeEnum.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/features/FEATURE_BLE/ble/SafeEnum.h b/features/FEATURE_BLE/ble/SafeEnum.h index eed1b8b7e1..a56d6ba32d 100644 --- a/features/FEATURE_BLE/ble/SafeEnum.h +++ b/features/FEATURE_BLE/ble/SafeEnum.h @@ -107,6 +107,10 @@ namespace ble { */ template struct SafeEnum { + /** + * Type of the representation. + */ + typedef LayoutType representation_t; /** * Construction of an enumeration value. @@ -197,6 +201,14 @@ struct SafeEnum { return _value; } + /** + * Return a pointer to the inner storage. + */ + const LayoutType* storage() const + { + return &_value; + } + private: LayoutType _value; }; From 6c09b6c465113f3e54bd06a70613bd638fc57c1a Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:26:10 +0000 Subject: [PATCH 292/361] BLE: Expose representation type in ble::Duration. --- features/FEATURE_BLE/ble/common/Duration.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 240ff72dbc..416c0ba7a4 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -94,6 +94,11 @@ template< typename Forever = void* > struct Duration { + /** + * Type of the actual representation. + */ + typedef Rep representation_t; + /** * Construct a default Duration. * From 643fad0162335e4e9209c3006a5ae40871f74a15 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:27:47 +0000 Subject: [PATCH 293/361] BLE: Improve code by explaining or textually defining constants --- .../source/gap/AdvertisingDataBuilder.cpp | 95 +++++++++++++------ 1 file changed, 66 insertions(+), 29 deletions(-) diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp index a16bfe15d6..8274f19e9a 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -16,8 +16,47 @@ #include "ble/gap/AdvertisingDataBuilder.h" +// Implementation notes +// Advertising data are organized as follow: +// - byte 0: Size of the rest of the field +// - byte 1: type of the field +// - byte 2 to the last byte: field value. +// An advertising data can contain at most a single instance of a field type. + +#define FIELD_TYPE_INDEX 1 +#define COMPANY_IDENTIFIER_SIZE 2 + +// A field is represented by a type and a value. The size of the field +// must fit in a byte therefore, the size of DATA cannot be larger than +// 0xFE +#define MAX_DATA_FIELD_SIZE 0xFE + +#define FIELD_HEADER_SIZE 2 + namespace ble { +namespace { + +mbed::Span as_span(const int8_t& v) { + return mbed::Span(reinterpret_cast(&v), sizeof(v)); +} + +mbed::Span as_span(const uint8_t& v) { + return mbed::Span(static_cast(&v), sizeof(v)); +} + +template +mbed::Span as_span(const Duration& d) { + return mbed::Span(reinterpret_cast(d.storage()), sizeof(d.value())); +} + +template +mbed::Span as_span(const SafeEnum& v) { + return mbed::Span(reinterpret_cast(v.storage()), sizeof(v.value())); +} + +} + AdvertisingDataBuilder::AdvertisingDataBuilder(mbed::Span buffer) : _buffer(buffer), _payload_length(0) @@ -126,26 +165,20 @@ ble_error_t AdvertisingDataBuilder::setAppearance( adv_data_appearance_t appearance ) { - uint8_t appearence_byte = appearance.value(); - mbed::Span appearance_span((const uint8_t *) &appearence_byte, 2); - return addOrReplaceData(adv_data_type_t::APPEARANCE, appearance_span); + return addOrReplaceData(adv_data_type_t::APPEARANCE, as_span(appearance)); } -ble_error_t AdvertisingDataBuilder::setFlags( - adv_data_flags_t flags -) +ble_error_t AdvertisingDataBuilder::setFlags(adv_data_flags_t flags) { uint8_t flags_byte = flags.value(); - mbed::Span flags_span((const uint8_t *) &flags_byte, 1); - return addOrReplaceData(adv_data_type_t::FLAGS, flags_span); + return addOrReplaceData(adv_data_type_t::FLAGS, as_span(flags_byte)); } ble_error_t AdvertisingDataBuilder::setTxPowerAdvertised( advertising_power_t txPower ) { - mbed::Span power_span((const uint8_t *) &txPower, 1); - return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, power_span); + return addOrReplaceData(adv_data_type_t::TX_POWER_LEVEL, as_span(txPower)); } ble_error_t AdvertisingDataBuilder::setName( @@ -153,12 +186,12 @@ ble_error_t AdvertisingDataBuilder::setName( bool complete ) { - mbed::Span power_span((const uint8_t *) name, strlen(name)); + mbed::Span name_span((const uint8_t *) name, strlen(name)); if (complete) { - return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, power_span); + return addOrReplaceData(adv_data_type_t::COMPLETE_LOCAL_NAME, name_span); } else { - return addOrReplaceData(adv_data_type_t::SHORTENED_LOCAL_NAME, power_span); + return addOrReplaceData(adv_data_type_t::SHORTENED_LOCAL_NAME, name_span); } } @@ -166,7 +199,8 @@ ble_error_t AdvertisingDataBuilder::setManufacturerSpecificData( mbed::Span data ) { - if (data.size() < 2) { + // manufacturer specific data should at least contain the vendor ID. + if (data.size() < COMPANY_IDENTIFIER_SIZE) { return BLE_ERROR_INVALID_PARAM; } @@ -177,13 +211,15 @@ ble_error_t AdvertisingDataBuilder::setAdvertisingInterval( adv_interval_t interval ) { + // Note: Advertising interval in advertisement MUST be represented in a 16bit + // value. if (interval.value() > 0xFFFF) { return BLE_ERROR_INVALID_PARAM; } return addOrReplaceData( adv_data_type_t::ADVERTISING_INTERVAL, - mbed::make_Span((const uint8_t *) interval.storage(), 2) + as_span(interval) ); } @@ -192,12 +228,13 @@ ble_error_t AdvertisingDataBuilder::setConnectionIntervalPreference( conn_interval_t max ) { - uint32_t interval = max.value(); - interval = interval << 16; - interval |= min.value(); + uint8_t interval[2 * sizeof(conn_interval_t::representation_t)]; + memcpy(interval, max.storage(), sizeof(max.value())); + memcpy(interval + sizeof(max.value()), min.storage(), sizeof(min.value())); + return addOrReplaceData( adv_data_type_t::SLAVE_CONNECTION_INTERVAL_RANGE, - mbed::make_Span((const uint8_t *) &interval, 4) + interval ); } @@ -206,14 +243,14 @@ ble_error_t AdvertisingDataBuilder::setServiceData( mbed::Span data ) { - if (service.getLen() + data.size() > 0xFE) { + if (service.getLen() + data.size() > MAX_DATA_FIELD_SIZE) { return BLE_ERROR_INVALID_PARAM; } adv_data_type_t short_type = adv_data_type_t::SERVICE_DATA_16BIT_ID; adv_data_type_t long_type = adv_data_type_t::SERVICE_DATA_128BIT_ID; - size_t total_size = data.size() + service.getLen() + 2; + size_t total_size = FIELD_HEADER_SIZE + service.getLen() + data.size(); size_t old_size = getFieldSize( (service.shortOrLong() == UUID::UUID_TYPE_SHORT) ? short_type : long_type ); @@ -281,7 +318,7 @@ ble_error_t AdvertisingDataBuilder::getData( uint8_t *field = findField(advDataType); if (field) { uint8_t data_length = field[0] - 1 /* skip type */; - data = mbed::make_Span((const uint8_t *) (field + 2 /* skip type and length */), data_length); + data = mbed::make_Span((const uint8_t *) (field + FIELD_HEADER_SIZE), data_length); return BLE_ERROR_NONE; } else { return BLE_ERROR_NOT_FOUND; @@ -292,7 +329,7 @@ uint8_t *AdvertisingDataBuilder::findField(adv_data_type_t type) { /* Scan through advertisement data */ for (uint8_t idx = 0; idx < _payload_length;) { - uint8_t fieldType = _buffer[idx + 1]; + uint8_t fieldType = _buffer[idx + FIELD_TYPE_INDEX]; if (fieldType == type) { return _buffer.data() + idx; @@ -309,7 +346,7 @@ uint8_t AdvertisingDataBuilder::getFieldSize(adv_data_type_t type) { uint8_t *field = findField(type); if (field) { - return field[0] + 1; + return field[0] + 1 /* field size is not included so we add it */; } else { return 0; } @@ -320,17 +357,17 @@ ble_error_t AdvertisingDataBuilder::addField( mbed::Span fieldData ) { - if (fieldData.size() > 0xFE) { + if (fieldData.size() > MAX_DATA_FIELD_SIZE) { return BLE_ERROR_INVALID_PARAM; } /* Make sure we don't exceed the buffer size */ - if (_payload_length + fieldData.size() + 2 > _buffer.size()) { + if (_payload_length + fieldData.size() + FIELD_HEADER_SIZE > _buffer.size()) { return BLE_ERROR_BUFFER_OVERFLOW; } /* Field length (includes field ID byte) */ - _buffer[_payload_length] = fieldData.size() + 1; + _buffer[_payload_length] = fieldData.size() + /* type */ 1; ++_payload_length; /* Field ID. */ @@ -390,7 +427,7 @@ ble_error_t AdvertisingDataBuilder::replaceField( uint8_t *field ) { - if (fieldData.size() > 0xFE) { + if (fieldData.size() > MAX_DATA_FIELD_SIZE) { return BLE_ERROR_INVALID_PARAM; } @@ -446,7 +483,7 @@ ble_error_t AdvertisingDataBuilder::setUUIDData( } } - if ((size_long * 8 > 0xFE) || (size_short * 2 > 0xFE)) { + if ((size_long * 8 > MAX_DATA_FIELD_SIZE) || (size_short * 2 > MAX_DATA_FIELD_SIZE)) { return BLE_ERROR_INVALID_PARAM; } From 6cb76458462716455e211bf9fdda7bd67dbb5697 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:28:09 +0000 Subject: [PATCH 294/361] BLE: Improve NULL check in ble::AdvertisingDataBuilder implementation. --- .../source/gap/AdvertisingDataBuilder.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp index 8274f19e9a..1f72f0c6d0 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -79,7 +79,7 @@ ble_error_t AdvertisingDataBuilder::addData( mbed::Span fieldData ) { - if (findField(advDataType)) { + if (findField(advDataType) != NULL) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } else { return addField(advDataType, fieldData); @@ -93,11 +93,11 @@ ble_error_t AdvertisingDataBuilder::replaceData( { uint8_t *field = findField(advDataType); - if (field) { - return replaceField(advDataType, fieldData, field); - } else { + if (field == NULL) { return BLE_ERROR_NOT_FOUND; } + + return replaceField(advDataType, fieldData, field); } ble_error_t AdvertisingDataBuilder::appendData( @@ -107,11 +107,11 @@ ble_error_t AdvertisingDataBuilder::appendData( { uint8_t *field = findField(advDataType); - if (field) { - return appendToField(fieldData, field); - } else { + if (field == NULL) { return BLE_ERROR_NOT_FOUND; } + + return appendToField(fieldData, field); } ble_error_t AdvertisingDataBuilder::removeData( @@ -120,11 +120,11 @@ ble_error_t AdvertisingDataBuilder::removeData( { uint8_t *field = findField(advDataType); - if (field) { - return removeField(field); - } else { + if (field == NULL) { return BLE_ERROR_NOT_FOUND; } + + return removeField(field); } ble_error_t AdvertisingDataBuilder::addOrReplaceData( @@ -134,7 +134,7 @@ ble_error_t AdvertisingDataBuilder::addOrReplaceData( { uint8_t *field = findField(advDataType); - if (field) { + if (field != NULL) { return replaceField(advDataType, fieldData, field); } else { return addField(advDataType, fieldData); @@ -148,7 +148,7 @@ ble_error_t AdvertisingDataBuilder::addOrAppendData( { uint8_t *field = findField(advDataType); - if (field) { + if (field != NULL) { return appendToField(fieldData, field); } else { return addField(advDataType, fieldData); From 4058f0908aec1bf38bdd458f1ba00a4252686c56 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Fri, 23 Nov 2018 21:42:02 +0000 Subject: [PATCH 295/361] BLE: Extract computation of minimumSupervisionTimeout. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b42863ee59..044dc6eab6 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -405,6 +405,16 @@ static bool is_advertising_params_valid(const GapAdvertisingParams ¶ms) return true; } +microsecond_t minSupervisionTimeout( + const conn_interval_t &maxConnectionInterval, + const slave_latency_t &slaveLatency +) +{ + // see BLUETOOTH SPECIFICATION Version 5.0 | Vol 2, Part E + // Section 7.8.12 LE Create Connection + return (1 + slaveLatency.value()) * maxConnectionInterval * 2; +} + } // end of anonymous namespace GenericGap::GenericGap( @@ -677,7 +687,7 @@ ble_error_t GenericGap::updateConnectionParameters( conn_event_length_t maxConnectionEventLength ) { - if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { + if (supervisionTimeout <= minSupervisionTimeout(maxConnectionInterval, slaveLatency)) { return BLE_ERROR_INVALID_PARAM; } @@ -702,7 +712,7 @@ ble_error_t GenericGap::acceptConnectionParametersUpdate( conn_event_length_t maxConnectionEventLength ) { - if (supervisionTimeout <= (1 + slaveLatency.value()) * maxConnectionInterval * 2) { + if (supervisionTimeout <= minSupervisionTimeout(maxConnectionInterval, slaveLatency)) { return BLE_ERROR_INVALID_PARAM; } From 6b8b1d0b7af73934b1dc500ebcf2612c11432cab Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 20:12:59 +0000 Subject: [PATCH 296/361] BLE: remove minimize fragmentation parameter in Gap. --- features/FEATURE_BLE/ble/gap/Gap.h | 10 ++++------ features/FEATURE_BLE/ble/generic/GenericGap.h | 8 +++----- features/FEATURE_BLE/source/gap/Gap.cpp | 6 ++---- .../FEATURE_BLE/source/generic/GenericGap.cpp | 20 +++++++++++++------ 4 files changed, 23 insertions(+), 21 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index eb3ba3fea4..cd2a5889f8 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -336,13 +336,12 @@ public: * * @param handle Advertising set handle. * @param payload Advertising payload. - * @param minimiseFragmentation Preference for fragmentation. + * * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation = false + mbed::Span payload ); /** Set new advertising scan response for a given advertising set. This will be sent to @@ -350,13 +349,12 @@ public: * * @param handle Advertising set handle. * @param response Advertising scan response. - * @param minimiseFragmentation Preference for fragmentation. + * * @return BLE_ERROR_NONE on success. */ virtual ble_error_t setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation = false + mbed::Span response ); /** Start advertising using the given advertising set. diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index a499966c04..0a8143a541 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -62,7 +62,7 @@ public: * * @param generic_access_service Platform abstraction instance managing * the GATT generic access service. - * + * * @param pal_sm Security Manager Platform abstraction instance containing the base * Security Manager primitives. */ @@ -114,16 +114,14 @@ public: */ virtual ble_error_t setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation + mbed::Span payload ); /** @copydoc Gap::setAdvertisingScanResponse */ virtual ble_error_t setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation + mbed::Span response ); /** @copydoc Gap::startAdvertising diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 659c33adbc..3f69641368 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -62,8 +62,7 @@ ble_error_t Gap::setAdvertisingParameters( ble_error_t Gap::setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation + mbed::Span payload ) { /* Requesting action from porter(s): override this API if this capability is supported. */ @@ -72,8 +71,7 @@ ble_error_t Gap::setAdvertisingPayload( ble_error_t Gap::setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation + mbed::Span response ) { /* Requesting action from porter(s): override this API if this capability is supported. */ diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 044dc6eab6..7549dcbf6e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1939,20 +1939,28 @@ ble_error_t GenericGap::setExtendedAdvertisingParameters( ble_error_t GenericGap::setAdvertisingPayload( advertising_handle_t handle, - mbed::Span payload, - bool minimiseFragmentation + mbed::Span payload ) { - return setAdvertisingData(handle, payload, minimiseFragmentation, false); + return setAdvertisingData( + handle, + payload, + /* minimise fragmentation */ true, + /* scan response */ true + ); } ble_error_t GenericGap::setAdvertisingScanResponse( advertising_handle_t handle, - mbed::Span response, - bool minimiseFragmentation + mbed::Span response ) { - return setAdvertisingData(handle, response, minimiseFragmentation, true); + return setAdvertisingData( + handle, + response, + /* minimise fragmentation */ true, + /* scan response */ true + ); } ble_error_t GenericGap::setAdvertisingData( From 936f1c550a875d70d7c329c246ab52825c79b93b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 21:25:32 +0000 Subject: [PATCH 297/361] BLE: Update ble::Gap documentation. --- features/FEATURE_BLE/ble/Gap.h | 222 +--------------- features/FEATURE_BLE/ble/gap/Gap.h | 414 +++++++++++++++++++++++++++-- 2 files changed, 390 insertions(+), 246 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index 73ca26617e..c74b729458 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -38,227 +38,7 @@ */ /** - * Define device discovery, connection and link management procedures. - * - * - Device discovery: A device can advertise to nearby peers its existence, - * identity and capabilities. Similarly, a device can scan its environment to - * find advertising peers. The information acquired during the scan helps to - * identify peers and understand their use. A scanner may acquire more information - * about an advertising peer by sending a scan request. If the peer accepts scan - * requests, it may reply with additional information about its state. - * - * - Connection: A bluetooth device can establish a connection to a connectable - * advertising peer. Once the connection is established, both devices can - * communicate using the GATT protocol. The GATT protocol allows connected - * devices to expose a set of states that the other peer can discover, read and write. - * - * - Link Management: Connected devices may drop the connection and may adjust - * connection parameters according to the power envelop needed for their - * application. - * - * @par Accessing gap - * - * Instance of a Gap class for a given BLE device should be accessed using - * BLE::gap(). The reference returned remains valid until the BLE instance - * shut down (see BLE::shutdown()). - * - * @code - * // assuming ble_device has been initialized - * BLE& ble_device; - * - * Gap& gap = ble_device.gap(); - * @endcode - * - * @par Advertising - * - * Advertising consists of broadcasting at a regular interval a small amount of - * data containing valuable informations about the device. These packets may be - * scanned by peer devices listening on BLE advertising channels. - * - * Scanners may also request additional information from a device advertising by - * sending a scan request. If the broadcaster accepts scan requests, it can reply - * with a scan response packet containing additional information. - * - * Advertising parameters are updated using setAdvertisingParams(). The main - * advertising payload is updated using setAdvertisingPayload() and the scan response - * is updated using setAdvertisingScanResponse(). If the advertising is already active - * updated the data will take effect from the next advertising event. - * - * To create a valid advertising payload and scan response you may use - * AdvertisingDataBuilder(). You must first allocate memory and crate an mbed::Span and - * pass that into the AdvertisingDataBuilder which will only be able to add as much - * data as fits in the provided buffer. The builder will accept any size of the buffer - * but for the created data to be usable it must be smaller than the maximum data - * length returned from getMaxAdvertisingDataLength(). - * - * @note The maximum size of data depends on the controller and its support for - * extended advertising however even if the controller supports larger data lengths if - * you wish to be compatible with older devices you may wish to use legacy - * advertising and should not use payloads larger than LEGACY_ADVERTISING_MAX_SIZE. - * - * @par Extended advertising - * - * Extended advertising allows for a wider choice of options than legacy advertising. - * You can send bigger payloads and use different PHYs. This allows for bigger throughput - * or longer range. - * - * Extended advertising may be split across many packets and takes place on both the - * regular advertising channels and the rest of the 37 channels normally used by - * connected devices. - * - * The 3 channels used in legacy advertising are called Primary Advertisement channels. - * The remaining 37 channels are used for secondary advertising. Unlike sending data - * during a connection this allows the device to broadcast data to multiple devices. - * - * The advertising starts on the Primary channels (which you may select) and continues - * on the secondary channels as indicated in the packet sent on the Primary channel. - * This way the advertising can send large payloads without saturating the advertising - * channels. Primary channels are limited to 1M and coded PHYs but Secondary channels - * may use the increased throughput 2M PHY. - * - * @par Periodic advertising - * - * Similarly, you can use periodic advertising to transfer regular data to multiple - * devices. - * - * The advertiser will use primary channels to advertise the information needed to - * listen to the periodic advertisements on secondary channels. This sync information - * will be used by the scanner who can now optimise for power consumption and only - * listen for the periodic advertisements at specified times. - * - * Like extended advertising, periodic advertising offers extra PHY options of 2M - * and coded. The payload may be updated at any time and will be updated on the next - * advertisement event when the periodic advertising is active. - * - * @par Advertising sets - * - * Advertisers may advertise multiple payloads at the same time. The configuration - * and identification of these is done through advertising sets. Use a handle - * obtained from createAvertisingSet() for advertising operations. After ending - * all advertising operations you should remove the handle from the system using - * destroyAdvertisingHandle(). - * - * Extended advertising and periodic advertising is an optional feature and not all - * devices support it and will only be able to see the now called legacy advertising. - * - * Legacy advertising is available through a special handle LEGACY_ADVERTISING_HANDLE. - * This handle is always available and doesn't need to be created and cannot be - * destroyed. - * - * There is a limited number of advertising sets available since they require support - * from the controller. Their availability is dynamic and may be queried at any time - * using getMaxAdvertisingSetNumber(). Advertising sets take up resources even if - * they are not actively advertising right now so it's important to destroy the set - * when you're done with it (or reuse it in the next advertisement). - * - * Periodic advertising and extended advertising share the same set. For periodic - * advertising to start the extended advertising of the same set must also be active. - * Subsequently you may disable extended advertising and the periodic advertising - * will continue. If you start periodic advertising while extended advertising is - * inactive, periodic advertising will not start until you start extended advertising - * at a later time. - * - * @par Privacy - * - * Privacy is a feature that allows a device to avoid being tracked by other - * (untrusted) devices. The device achieves it by periodically generating a - * new random address. The random address may be a resolvable random address, - * enabling trusted devices to recognise it as belonging to the same - * device. These trusted devices receive an Identity Resolution Key (IRK) - * during pairing. This is handled by the SecurityManager and relies on the - * other device accepting and storing the IRK. - * - * Privacy needs to be enabled by calling enablePrivacy() after having - * initialised the SecurityManager since privacy requires SecurityManager - * to handle IRKs. The behaviour of privacy enabled devices is set by - * using setCentralPrivacyConfiguration() which specifies what the device - * should be with devices using random addresses. Random addresses - * generated by privacy enabled device can be of two types: resolvable - * (by devices who have the IRK) and unresolvable. Unresolvable addresses - * can't be used for connecting and connectable advertising therefore a - * resolvable one will be used for these regardless of the privacy - * configuration. - * - * @par Scanning - * - * Scanning consist of listening for peer advertising packets. From a scan, a - * device can identify devices available in its environment. - * - * If the device scans actively, then it will send scan request to scannable - * advertisers and collect their scan response. - * - * Scanning is done by creating ScanParameters and applying then with - * setScanParameters(). One configure you may call startScan(). - * - * When a scanning device receives an advertising packet it will call - * onAdvertisingReport() in the registered event handler. A whitelist may be used - * to limit the advertising reports by setting the correct policy in the scan - * parameters. - * - * @par Connection event handling - * - * A peer may connect device advertising connectable packets. The advertising - * procedure ends as soon as the device is connected. If an advertising timeout - * has been set in the advertising parameters then onAdvertisingEnd will be called - * in the registered eventHandler when it runs out. - * - * A device accepting a connection request from a peer is named a peripheral, - * and the device initiating the connection is named a central. - * - * Connection is initiated by central devices. A call to connect() will result in - * the device scanning on any PHYs set in ConectionParamters passed in. - * - * Peripheral and central receive a connection event when the connection is - * effective. If successful will result in a call to onConnectionComplete in the - * EventHandler registered with the Gap. - * - * It the connection attempt fails it will result in onConnectionComplete called - * on the central device with the event carrying the error flag. - * - * @par Changing the PHYsical transport of a connection - * - * Once a connection has been established, it is possible to change the physical - * transport used between the local and the distant device. Changing the transport - * can either increase the bandwidth or increase the communication range. - * An increased bandwidth equals a better power consumption but also a loss in - * sensibility and therefore a degraded range. - * - * Symmetrically an increased range means a lowered bandwidth and a degraded power - * consumption. - * - * Applications can change the PHY used by calling the function setPhy. Once the - * update has been made the result is forwarded to the application by calling the - * function onPhyUpdateComplete of the event handler registered. - * - * @par disconnection - * - * The application code initiates a disconnection when it calls the - * disconnect(Handle_t, DisconnectionReason_t) function. - * - * Disconnection may also be initiated by the remote peer or the local - * controller/stack. To catch all disconnection events, application code may - * set up an handler taking care of disconnection events by calling - * onDisconnection(). - * - * @par Modulation Schemes - * - * When supported by the host and controller you can select different modulation - * schemes (@see BLUETOOTH SPECIFICATION Version 5.0 | Vol 1, Part A - 1.2): - * - LE 1M PHY - * - LE 2M PHY - * - LE coded PHY - * - * You may set preferred PHYs (separately for RX and TX) using setPreferredPhys(). - * You may also set the currently used PHYs on a selected connection using setPhy(). - * Both of these settings are only advisory and the controller is allowed to make - * its own decision on the best PHY to use based on your request, the peer's - * supported features and the connection's physical conditions. - * - * You may query the currently used PHY using readPhy() which will return the - * result through a call to the registered event handler. You may register the - * handler with setEventHandler(). The events inform about the currently used - * PHY and of any changes to PHYs which may be triggered autonomously by the - * controller or by the peer. + * @copydoc ble::Gap */ class Gap : public ble::Gap { public: diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index cd2a5889f8..552d1208d2 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -28,6 +28,229 @@ namespace ble { +/** + * Define device discovery, connection and link management procedures. + * + * - Device discovery: A device can advertise to nearby peers its existence, + * identity and capabilities. Similarly, a device can scan its environment to + * find advertising peers. The information acquired during the scan helps to + * identify peers and understand their use. A scanner may acquire more information + * about an advertising peer by sending a scan request. If the peer accepts scan + * requests, it may reply with additional information about its state. + * + * - Connection: A bluetooth device can establish a connection to a connectable + * advertising peer. Once the connection is established, both devices can + * communicate using the GATT protocol. The GATT protocol allows connected + * devices to expose a set of states that the other peer can discover, read and write. + * + * - Link Management: Connected devices may drop the connection and may adjust + * connection parameters according to the power envelop needed for their + * application. + * + * @par Accessing gap + * + * Instance of a Gap class for a given BLE device should be accessed using + * BLE::gap(). The reference returned remains valid until the BLE instance + * shut down (see BLE::shutdown()). + * + * @code + * // assuming ble_device has been initialized + * BLE& ble_device; + * + * ble::Gap& gap = ble_device.gap(); + * @endcode + * + * @par Advertising + * + * Advertising consists of broadcasting at a regular interval a small amount of + * data containing valuable informations about the device. These packets may be + * scanned by peer devices listening on BLE advertising channels. + * + * Scanners may also request additional information from a device advertising by + * sending a scan request. If the broadcaster accepts scan requests, it can reply + * with a scan response packet containing additional information. + * + * Advertising parameters are updated using setAdvertisingParams(). The main + * advertising payload is updated using setAdvertisingPayload() and the scan response + * is updated using setAdvertisingScanResponse(). If the advertising is already active + * updated the data will take effect from the next advertising event. + * + * To create a valid advertising payload and scan response you may use + * AdvertisingDataBuilder(). You must first allocate memory and crate an mbed::Span and + * pass that into the AdvertisingDataBuilder which will only be able to add as much + * data as fits in the provided buffer. The builder will accept any size of the buffer + * but for the created data to be usable it must be smaller than the maximum data + * length returned from getMaxAdvertisingDataLength(). + * + * @note The maximum size of data depends on the controller and its support for + * extended advertising however even if the controller supports larger data lengths if + * you wish to be compatible with older devices you may wish to use legacy + * advertising and should not use payloads larger than LEGACY_ADVERTISING_MAX_SIZE. + * + * @par Extended advertising + * + * Extended advertising allows for a wider choice of options than legacy advertising. + * You can send bigger payloads and use different PHYs. This allows for bigger throughput + * or longer range. + * + * Extended advertising may be split across many packets and takes place on both the + * regular advertising channels and the rest of the 37 channels normally used by + * connected devices. + * + * The 3 channels used in legacy advertising are called Primary Advertisement channels. + * The remaining 37 channels are used for secondary advertising. Unlike sending data + * during a connection this allows the device to broadcast data to multiple devices. + * + * The advertising starts on the Primary channels (which you may select) and continues + * on the secondary channels as indicated in the packet sent on the Primary channel. + * This way the advertising can send large payloads without saturating the advertising + * channels. Primary channels are limited to 1M and coded PHYs but Secondary channels + * may use the increased throughput 2M PHY. + * + * @par Periodic advertising + * + * Similarly, you can use periodic advertising to transfer regular data to multiple + * devices. + * + * The advertiser will use primary channels to advertise the information needed to + * listen to the periodic advertisements on secondary channels. This sync information + * will be used by the scanner who can now optimise for power consumption and only + * listen for the periodic advertisements at specified times. + * + * Like extended advertising, periodic advertising offers extra PHY options of 2M + * and coded. The payload may be updated at any time and will be updated on the next + * advertisement event when the periodic advertising is active. + * + * @par Advertising sets + * + * Advertisers may advertise multiple payloads at the same time. The configuration + * and identification of these is done through advertising sets. Use a handle + * obtained from createAvertisingSet() for advertising operations. After ending + * all advertising operations you should remove the handle from the system using + * destroyAdvertisingHandle(). + * + * Extended advertising and periodic advertising is an optional feature and not all + * devices support it and will only be able to see the now called legacy advertising. + * + * Legacy advertising is available through a special handle LEGACY_ADVERTISING_HANDLE. + * This handle is always available and doesn't need to be created and cannot be + * destroyed. + * + * There is a limited number of advertising sets available since they require support + * from the controller. Their availability is dynamic and may be queried at any time + * using getMaxAdvertisingSetNumber(). Advertising sets take up resources even if + * they are not actively advertising right now so it's important to destroy the set + * when you're done with it (or reuse it in the next advertisement). + * + * Periodic advertising and extended advertising share the same set. For periodic + * advertising to start the extended advertising of the same set must also be active. + * Subsequently you may disable extended advertising and the periodic advertising + * will continue. If you start periodic advertising while extended advertising is + * inactive, periodic advertising will not start until you start extended advertising + * at a later time. + * + * @par Privacy + * + * Privacy is a feature that allows a device to avoid being tracked by other + * (untrusted) devices. The device achieves it by periodically generating a + * new random address. The random address may be a resolvable random address, + * enabling trusted devices to recognise it as belonging to the same + * device. These trusted devices receive an Identity Resolution Key (IRK) + * during pairing. This is handled by the SecurityManager and relies on the + * other device accepting and storing the IRK. + * + * Privacy needs to be enabled by calling enablePrivacy() after having + * initialised the SecurityManager since privacy requires SecurityManager + * to handle IRKs. The behaviour of privacy enabled devices is set by + * using setCentralPrivacyConfiguration() which specifies what the device + * should be with devices using random addresses. Random addresses + * generated by privacy enabled device can be of two types: resolvable + * (by devices who have the IRK) and unresolvable. Unresolvable addresses + * can't be used for connecting and connectable advertising therefore a + * resolvable one will be used for these regardless of the privacy + * configuration. + * + * @par Scanning + * + * Scanning consist of listening for peer advertising packets. From a scan, a + * device can identify devices available in its environment. + * + * If the device scans actively, then it will send scan request to scannable + * advertisers and collect their scan response. + * + * Scanning is done by creating ScanParameters and applying then with + * setScanParameters(). One configure you may call startScan(). + * + * When a scanning device receives an advertising packet it will call + * onAdvertisingReport() in the registered event handler. A whitelist may be used + * to limit the advertising reports by setting the correct policy in the scan + * parameters. + * + * @par Connection event handling + * + * A peer may connect device advertising connectable packets. The advertising + * procedure ends as soon as the device is connected. If an advertising timeout + * has been set in the advertising parameters then onAdvertisingEnd will be called + * in the registered eventHandler when it runs out. + * + * A device accepting a connection request from a peer is named a peripheral, + * and the device initiating the connection is named a central. + * + * Connection is initiated by central devices. A call to connect() will result in + * the device scanning on any PHYs set in ConectionParamters passed in. + * + * Peripheral and central receive a connection event when the connection is + * effective. If successful will result in a call to onConnectionComplete in the + * EventHandler registered with the Gap. + * + * It the connection attempt fails it will result in onConnectionComplete called + * on the central device with the event carrying the error flag. + * + * @par Changing the PHYsical transport of a connection + * + * Once a connection has been established, it is possible to change the physical + * transport used between the local and the distant device. Changing the transport + * can either increase the bandwidth or increase the communication range. + * An increased bandwidth equals a better power consumption but also a loss in + * sensibility and therefore a degraded range. + * + * Symmetrically an increased range means a lowered bandwidth and a degraded power + * consumption. + * + * Applications can change the PHY used by calling the function setPhy. Once the + * update has been made the result is forwarded to the application by calling the + * function onPhyUpdateComplete of the event handler registered. + * + * @par disconnection + * + * The application code initiates a disconnection when it calls the + * disconnect(Handle_t, DisconnectionReason_t) function. + * + * Disconnection may also be initiated by the remote peer or the local + * controller/stack. To catch all disconnection events, application code may + * set up an handler taking care of disconnection events by calling + * onDisconnection(). + * + * @par Modulation Schemes + * + * When supported by the host and controller you can select different modulation + * schemes (@see BLUETOOTH SPECIFICATION Version 5.0 | Vol 1, Part A - 1.2): + * - LE 1M PHY + * - LE 2M PHY + * - LE coded PHY + * + * You may set preferred PHYs (separately for RX and TX) using setPreferredPhys(). + * You may also set the currently used PHYs on a selected connection using setPhy(). + * Both of these settings are only advisory and the controller is allowed to make + * its own decision on the best PHY to use based on your request, the peer's + * supported features and the connection's physical conditions. + * + * You may query the currently used PHY using readPhy() which will return the + * result through a call to the registered event handler. You may register the + * handler with setEventHandler(). The events inform about the currently used + * PHY and of any changes to PHYs which may be triggered autonomously by the + * controller or by the peer. + */ class Gap { public: @@ -267,7 +490,7 @@ public: * Assign the event handler implementation that will be used by the gap * module to signal events back to the application. * - * @param handler Application implementation of an Eventhandler. + * @param handler Application implementation of an EventHandler. */ void setEventHandler(EventHandler *handler) { @@ -286,6 +509,9 @@ public: /** Return currently available number of supported advertising sets. * This may change at runtime. * + * @note Devices that do not support Bluetooth 5 still offers one advertising + * set that has the handle LEGACY_ADVERTISING_HANDLE. + * * @return Number of advertising sets that may be created at the same time. */ virtual uint8_t getMaxAdvertisingSetNumber(); @@ -305,6 +531,8 @@ public: * @param[out] handle Advertising handle returned, valid only if function returned success. * @param parameters Advertising parameters for the newly created set. * @return BLE_ERROR_NONE on success. + * + * @version 5+ */ virtual ble_error_t createAdvertisingSet( advertising_handle_t *handle, @@ -318,6 +546,8 @@ public: * * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. + * + * @version 5+ */ virtual ble_error_t destroyAdvertisingSet(advertising_handle_t handle); @@ -338,6 +568,8 @@ public: * @param payload Advertising payload. * * @return BLE_ERROR_NONE on success. + * + * @see ble::AdvertisingDataBuilder to build a payload. */ virtual ble_error_t setAdvertisingPayload( advertising_handle_t handle, @@ -351,6 +583,8 @@ public: * @param response Advertising scan response. * * @return BLE_ERROR_NONE on success. + * + * @see ble::AdvertisingDataBuilder to build a payload. */ virtual ble_error_t setAdvertisingScanResponse( advertising_handle_t handle, @@ -363,6 +597,11 @@ public: * @param maxDuration Max duration for advertising (in units of 10ms) - 0 means no limit. * @param maxEvents Max number of events produced during advertising - 0 means no limit. * @return BLE_ERROR_NONE on success. + * + * @see EventHandler::onScanRequestReceived when a scan request is received. + * @see EventHandler::onAdvertisingEnd when the advertising ends. + * @see EventHandler::onConnectionComplete when the device gets connected + * by a peer. */ virtual ble_error_t startAdvertising( advertising_handle_t handle, @@ -392,6 +631,8 @@ public: * @param periodicAdvertisingIntervalMax Maximum interval for periodic advertising. * @param advertiseTxPower Include transmission power in the advertisements. * @return BLE_ERROR_NONE on success. + * + * @version 5+ */ virtual ble_error_t setPeriodicAdvertisingParameters( advertising_handle_t handle, @@ -405,6 +646,10 @@ public: * @param handle Advertising set handle. * @param payload Advertising payload. * @return BLE_ERROR_NONE on success. + * + * @see ble::AdvertisingDataBuilder to build a payload. + * + * @version 5+ */ virtual ble_error_t setPeriodicAdvertisingPayload( advertising_handle_t handle, @@ -416,6 +661,8 @@ public: * * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. + * + * @version 5+ */ virtual ble_error_t startPeriodicAdvertising(advertising_handle_t handle); @@ -423,6 +670,8 @@ public: * * @param handle Advertising set handle. * @return BLE_ERROR_NONE on success. + * + * @version 5+ */ virtual ble_error_t stopPeriodicAdvertising(advertising_handle_t handle); @@ -430,6 +679,8 @@ public: * * @param handle Advertising set handle. * @return True if periodic advertising is active on this set. + * + * @version 5+ */ virtual bool isPeriodicAdvertisingActive(advertising_handle_t handle); @@ -454,6 +705,9 @@ public: * will begin and scanning. This will repeat until stopScan() is called. * * @return BLE_ERROR_NONE on success. + * + * @see EventHandler::onAdvertisingReport to collect advertising reports. + * @see EventHandler::onScanTimeout when scanning timeout. */ virtual ble_error_t startScan( duplicates_filter_t filtering = duplicates_filter_t::DISABLE, @@ -481,6 +735,15 @@ public: * @param timeout Maximum permitted time between successful receptions. If this time is * exceeded, synchronisation is lost. * @return BLE_ERROR_NONE on success. + * + * @see EventHandler::onPeriodicAdvertisingSyncEstablished when the sync is + * effective. + * @see EventHandler::onPeriodicAdvertisingReport when data are issued by the + * peer. + * @see EventHandler::onPeriodicAdvertisingSyncLoss when the sync has been + * loss. + * + * @version 5+ */ virtual ble_error_t createSync( peer_address_type_t peerAddressType, @@ -498,6 +761,15 @@ public: * @param timeout Maximum permitted time between successful receives. * If this time is exceeded, synchronisation is lost. * @return BLE_ERROR_NONE on success. + * + * @see EventHandler::onPeriodicAdvertisingSyncEstablished when the sync is + * effective. + * @see EventHandler::onPeriodicAdvertisingReport when data are issued by the + * peer. + * @see EventHandler::onPeriodicAdvertisingSyncLoss when the sync has been + * loss. + * + * @version 5+ */ virtual ble_error_t createSync( slave_latency_t maxPacketSkip, @@ -567,6 +839,11 @@ public: * @return BLE_ERROR_NONE if connection establishment procedure is started * successfully. The connectionCallChain (if set) is invoked upon * a connection event. + * + * @see EventHandler::onConnectionComplete will be called whether the + * connection process succeed or fail. + * @see EventHandler::onDisconnectionComplete is called when the connection + * ends. */ virtual ble_error_t connect( target_peer_address_type_t peerAddressType, @@ -583,15 +860,30 @@ public: virtual ble_error_t cancelConnect(); /** - * TODO - * @param connectionHandle - * @param minConnectionInterval - * @param maxConnectionInterval - * @param slaveLatency - * @param supervision_timeout - * @param minConnectionEventLength - * @param maxConnectionEventLength - * @return + * Update connection parameters of an existing connection. + * + * In the central role, this initiates a Link Layer connection parameter + * update procedure. In the peripheral role, this sends the corresponding + * L2CAP request and waits for the central to accept or reject the requested + * connection parameters. + * + * @param connectionHandle The handle of the connection to update. + * @param minConnectionInterval The minimum connection interval requested. + * @param maxConnectionInterval The maximum connection interval requested. + * @param slaveLatency The slave latency requested. + * @param supervision_timeout The supervision timeout requested. + * @param minConnectionEventLength The minimum connection event length requested. + * @param maxConnectionEventLength The maximum connection event length requested. + * + * @return BLE_ERROR_NONE if the request has been sent and false otherwise. + * + * @see EventHandler::onUpdateConnectionParametersRequest when a central + * receives a request to update the connection parameters. + * @see EventHandler::onConnectionParametersUpdateComplete when connection + * parameters have been updated. + * + * @version 4.0+ for central + * @version 4.1+ for peripheral */ virtual ble_error_t updateConnectionParameters( connection_handle_t connectionHandle, @@ -604,24 +896,57 @@ public: ); /** - * TODO - * @param userManageConnectionUpdateRequest - * @return + * Allows the application to accept or reject a connection parameters update + * request. + * + * If this process is managed by the middleware; new connection parameters + * from a slave are always accepted. + * + * @param userManageConnectionUpdateRequest true to let the application + * manage the process and false to let the middleware manage it. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + * + * @version 4.1+ + * + * @see EventHandler::onUpdateConnectionParametersRequest when a central + * receives a request to update the connection parameters. + * + * @see acceptConnectionParametersUpdate to accept the request. + * @see rejectConnectionParametersUpdate to reject the request. */ virtual ble_error_t manageConnectionParametersUpdateRequest( bool userManageConnectionUpdateRequest ); /** - * TODO - * @param connectionHandle - * @param minConnectionInterval - * @param maxConnectionInterval - * @param slaveLatency - * @param supervision_timeout - * @param minConnectionEventLength - * @param maxConnectionEventLength - * @return + * Accept update of the connection parameters. + * + * The central can adjust the new connection parameters. + * + * @param connectionHandle The handle of the connection that has initiated + * the request. + * @param minConnectionInterval The minimum connection interval to be applied. + * @param maxConnectionInterval The maximum connection interval to be applied. + * @param slaveLatency The slave latency to be applied. + * @param supervision_timeout The supervision timeout to be applied. + * @param minConnectionEventLength The minimum connection event length to be + * applied. + * @param maxConnectionEventLength The maximum connection event length to be + * applied. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + * + * @version 4.1+ + * + * @see manageConnectionParametersUpdateRequest To let the application + * manage the process. + * + * @see EventHandler::onUpdateConnectionParametersRequest Called when a + * request to update the connection parameters is received. + * + * @see EventHandler::onConnectionParametersUpdateComplete Called when the + * new connection parameters are effective. */ virtual ble_error_t acceptConnectionParametersUpdate( connection_handle_t connectionHandle, @@ -634,9 +959,20 @@ public: ); /** - * TODO - * @param connectionHandle - * @return + * Reject a request to change the connection parameters. + * + * @param connectionHandle The handle of the connection that has initiated + * the request. + * + * @return BLE_ERROR_NONE in case of success or an appropriate error code. + * + * @version 4.1+ + * + * @see manageConnectionParametersUpdateRequest To let the application + * manage the process. + * + * @see EventHandler::onUpdateConnectionParametersRequest Called when a + * request to update the connection parameters is received. */ virtual ble_error_t rejectConnectionParametersUpdate( connection_handle_t connectionHandle @@ -654,6 +990,9 @@ public: * * @return BLE_ERROR_NONE if the disconnection procedure successfully * started. + * + * @see EventHandler::onDisconnectionComplete when the disconnection is + * effective. */ virtual ble_error_t disconnect( connection_handle_t connectionHandle, @@ -671,6 +1010,10 @@ public: * * @return BLE_ERROR_NONE if the read PHY procedure has been started or an * appropriate error code. + * + * @version 5+ + * + * @see EventHandler::onReadPhy is called when the phy has been read. */ virtual ble_error_t readPhy(connection_handle_t connection); @@ -685,6 +1028,8 @@ public: * * @return BLE_ERROR_NONE if the preferences have been set or an appropriate * error code. + * + * @version 5+ */ virtual ble_error_t setPreferredPhys( const phy_set_t *txPhys, @@ -712,6 +1057,9 @@ public: * * @return BLE_ERROR_NONE if the update PHY procedure has been successfully * started or an error code. + * + * @see EventHandler::onPhyUpdateComplete is called when the phy used by the + * connection has been updated. */ virtual ble_error_t setPhy( connection_handle_t connection, @@ -721,6 +1069,9 @@ public: ); protected: + +#if !defined(DOXYGEN_ONLY) + /* Override the following in the underlying adaptation layer to provide the * functionality of scanning. */ @@ -738,6 +1089,8 @@ protected: { } +#endif + /* -------- soon to be deprecated API -------- */ @@ -845,9 +1198,15 @@ public: ResolutionStrategy resolution_strategy; }; + /** + * Default peripheral privacy configuration. + */ static const PeripheralPrivacyConfiguration_t default_peripheral_privacy_configuration; + /** + * Default peripheral privacy configuration. + */ static const CentralPrivacyConfiguration_t default_central_privacy_configuration; @@ -933,6 +1292,9 @@ public: ); protected: + +#if !defined(DOXYGEN_ONLY) + /** * Construct a Gap instance. */ @@ -944,6 +1306,8 @@ protected: * Event handler provided by the application. */ EventHandler *_eventHandler; + +#endif }; } // namespace ble From 4db8ddfb909e8e26cf97125f2082b42e71a3bdd4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 21:46:55 +0000 Subject: [PATCH 298/361] BLE: fix name of functions in ble::ScanParameters. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 33 ++++++------------- .../FEATURE_BLE/source/generic/GenericGap.cpp | 26 +++++++-------- 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 83908b1108..a456ab2c5c 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -67,19 +67,6 @@ public: { } - ScanParameters( - phy_configuration_t phy_1m_configuration, - own_address_type_t own_address_type = own_address_type_t::PUBLIC, - scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER - ) : - own_address_type(own_address_type), - scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), - phys(phy_set_t::PHY_SET_1M), - phy_1m_configuration(phy_1m_configuration), - phy_coded_configuration() - { - } - ScanParameters( phy_configuration_t phy_1m_configuration, phy_configuration_t phy_coded_configuration, @@ -94,41 +81,41 @@ public: { } - ScanParameters &set_own_address_type(own_address_type_t address) + ScanParameters &setOwnAddressType(own_address_type_t address) { own_address_type = address; return *this; } - own_address_type_t get_own_address_type() const + own_address_type_t getOwnAddressType() const { return own_address_type; } - ScanParameters &set_scanning_filter_policy(scanning_filter_policy_t filter_policy) + ScanParameters &setFilter(scanning_filter_policy_t filter_policy) { scanning_filter_policy = filter_policy; return *this; } - scanning_filter_policy_t get_scanning_filter_policy() const + scanning_filter_policy_t getFilter() const { return scanning_filter_policy; } - ScanParameters &set_scanning_phys(bool enable_1m, bool enable_coded) + ScanParameters &setPhys(bool enable_1m, bool enable_coded) { phys.set_1m(enable_1m); phys.set_coded(enable_coded); return *this; } - phy_set_t get_scanning_phys() const + phy_set_t getPhys() const { return phys; } - ScanParameters &set_1m_phy_configuration( + ScanParameters &set1mPhyConfiguration( scan_interval_t interval, scan_window_t window, bool active_scanning @@ -141,12 +128,12 @@ public: return *this; } - phy_configuration_t get_1m_configuration() const + phy_configuration_t get1mPhyConfiguration() const { return phy_1m_configuration; } - ScanParameters &set_coded_phy_configuration( + ScanParameters &setCodedPhyConfiguration( scan_interval_t interval, scan_window_t window, bool active_scanning @@ -159,7 +146,7 @@ public: return *this; } - phy_configuration_t get_coded_configuration() const + phy_configuration_t getCodedPhyConfiguration() const { return phy_1m_configuration; } diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7549dcbf6e..c6d708da17 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2570,42 +2570,42 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) if (is_extended_advertising_available()) { bool active_scanning[] = { - params.get_1m_configuration().active_scanning, - params.get_coded_configuration().active_scanning + params.get1mPhyConfiguration().active_scanning, + params.getCodedPhyConfiguration().active_scanning }; uint16_t scan_interval[] = { - params.get_1m_configuration().interval.value(), - params.get_coded_configuration().interval.value() + params.get1mPhyConfiguration().interval.value(), + params.getCodedPhyConfiguration().interval.value() }; uint16_t scan_window[] = { - params.get_1m_configuration().window.value(), - params.get_coded_configuration().window.value() + params.get1mPhyConfiguration().window.value(), + params.getCodedPhyConfiguration().window.value() }; return _pal_gap.set_extended_scan_parameters( - params.get_own_address_type(), - params.get_scanning_filter_policy(), - params.get_scanning_phys(), + params.getOwnAddressType(), + params.getFilter(), + params.getPhys(), active_scanning, scan_interval, scan_window ); } else { - if (params.get_scanning_phys().get_coded()) { + if (params.getPhys().get_coded()) { return BLE_ERROR_INVALID_PARAM; } ScanParameters::phy_configuration_t legacy_configuration = - params.get_1m_configuration(); + params.get1mPhyConfiguration(); return _pal_gap.set_scan_parameters( legacy_configuration.active_scanning, legacy_configuration.interval.value(), legacy_configuration.window.value(), - params.get_own_address_type(), - params.get_scanning_filter_policy() + params.getOwnAddressType(), + params.getFilter() ); } } From e130bec6a06deafaf666a7fe96a54a23aa04eea3 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 22:09:46 +0000 Subject: [PATCH 299/361] BLE: rework ScanParameters::phy_configuration_t --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 40 ++++++++++++++++++- .../FEATURE_BLE/source/generic/GenericGap.cpp | 18 ++++----- 2 files changed, 47 insertions(+), 11 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index a456ab2c5c..5d1e2a1f4a 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -32,10 +32,21 @@ namespace ble { class ScanParameters { public: + + /** + * Scan configuration of a physical channel. + */ struct phy_configuration_t { + /** + * Construct a phy_configuration_t. + * @param scan_interval The scan interval. + * @param scan_window The scan window + * @param active_scanning True if scan request should be sent and false + * otherwise. + */ phy_configuration_t( - scan_window_t scan_interval = scan_interval_t::min(), - scan_interval_t scan_window = scan_window_t::min(), + scan_interval_t scan_interval = scan_interval_t::min(), + scan_window_t scan_window = scan_window_t::min(), bool active_scanning = false ) : interval(scan_interval), @@ -47,6 +58,31 @@ public: } } + /** + * Get the scan interval. + */ + const scan_window_t &getInterval() const + { + return interval; + } + + /** + * Get the scan window. + */ + const scan_interval_t &getWindow() const + { + return window; + } + + /** + * Return if active scanning is set. + */ + bool isActiveScanningSet() const + { + return active_scanning; + } + + private: scan_window_t interval; scan_interval_t window; bool active_scanning; diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index c6d708da17..5aa9fb2bc1 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2570,18 +2570,18 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) if (is_extended_advertising_available()) { bool active_scanning[] = { - params.get1mPhyConfiguration().active_scanning, - params.getCodedPhyConfiguration().active_scanning + params.get1mPhyConfiguration().isActiveScanningSet(), + params.getCodedPhyConfiguration().isActiveScanningSet() }; uint16_t scan_interval[] = { - params.get1mPhyConfiguration().interval.value(), - params.getCodedPhyConfiguration().interval.value() + params.get1mPhyConfiguration().getInterval().value(), + params.getCodedPhyConfiguration().getInterval().value() }; uint16_t scan_window[] = { - params.get1mPhyConfiguration().window.value(), - params.getCodedPhyConfiguration().window.value() + params.get1mPhyConfiguration().getWindow().value(), + params.getCodedPhyConfiguration().getWindow().value() }; return _pal_gap.set_extended_scan_parameters( @@ -2601,9 +2601,9 @@ ble_error_t GenericGap::setScanParameters(const ScanParameters ¶ms) params.get1mPhyConfiguration(); return _pal_gap.set_scan_parameters( - legacy_configuration.active_scanning, - legacy_configuration.interval.value(), - legacy_configuration.window.value(), + legacy_configuration.isActiveScanningSet(), + legacy_configuration.getInterval().value(), + legacy_configuration.getWindow().value(), params.getOwnAddressType(), params.getFilter() ); From 3119f9488c2c55d6bc7c956fd0fbf4f96f1736f9 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 22:24:15 +0000 Subject: [PATCH 300/361] BLE: Construct a phy_set_t from a phy_t. --- features/FEATURE_BLE/ble/BLETypes.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 96f0ce6d86..2261ec2756 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -725,6 +725,28 @@ public: set_coded(phy_coded); } + /** + * Create a set from a single phy. + * + * @param phy The phy to add to the set. + */ + phy_set_t(phy_t phy) : _value() + { + switch (phy.value()) { + case phy_t::LE_1M: + set_1m(true); + break; + case phy_t::LE_2M: + set_2m(true); + break; + case phy_t::LE_CODED: + set_coded(true); + break; + default: + break; + } + } + /** Prefer 1M PHY. */ void set_1m(bool enabled = true) { if (enabled) { From 11b1e915927e5dce110d703a07c21722816fa692 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 22:24:37 +0000 Subject: [PATCH 301/361] BLE: Rework ScanParameters construction. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 37 ++++++++++--------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 5d1e2a1f4a..467453a912 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -88,7 +88,18 @@ public: bool active_scanning; }; + /** + * Construct a ScanParameters object that operate on a selected phy. + * + * @param phy The phy to configure. + * @param scan_interval The scan interval. + * @param scan_window The scan window. + * @param active_scanning active scanning flag + * @param own_address_type Address type used in scan requests. + * @param scanning_filter_policy Filter applied. + */ ScanParameters( + phy_t phy = phy_t::LE_1M, scan_window_t scan_interval = scan_interval_t::min(), scan_interval_t scan_window = scan_window_t::min(), bool active_scanning = false, @@ -96,25 +107,17 @@ public: scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER ) : own_address_type(own_address_type), - scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), - phys(phy_set_t::PHY_SET_1M), - phy_1m_configuration(scan_interval, scan_window, active_scanning), + scanning_filter_policy(scanning_filter_policy), + phys(phy), + phy_1m_configuration(), phy_coded_configuration() { - } - - ScanParameters( - phy_configuration_t phy_1m_configuration, - phy_configuration_t phy_coded_configuration, - own_address_type_t own_address_type = own_address_type_t::PUBLIC, - scanning_filter_policy_t scanning_filter_policy = scanning_filter_policy_t::NO_FILTER - ) : - own_address_type(own_address_type), - scanning_filter_policy(scanning_filter_policy_t::NO_FILTER), - phys(true, false, true), - phy_1m_configuration(phy_1m_configuration), - phy_coded_configuration(phy_coded_configuration) - { + phy_configuration_t conf(scan_interval, scan_window, active_scanning); + if (phy == phy_t::LE_1M) { + phy_1m_configuration = conf; + } else if (phy == phy_t::LE_CODED) { + phy_coded_configuration = conf; + } } ScanParameters &setOwnAddressType(own_address_type_t address) From 27011fd95408c4f1737d5dbc25d7b76bb360efe6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sat, 24 Nov 2018 22:32:57 +0000 Subject: [PATCH 302/361] BLE: Document ble::ScanParameters. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index 467453a912..b6f9f3eac1 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -30,6 +30,24 @@ namespace ble { +/** + * Parameters defining the scan process. + * + * The scan process is defined by two main parameters: + * - The scan window that defines how long the device should scan. + * - The scan window that defines how frequently the device should scan. + * + * To scan continuously, the scan window and the scan interval should have the + * same value. + * + * To get extra data from the advertising device, the scanner can send scan + * requests to the advertiser that respond with a scan response. It is possible + * to select what type of address is used to issue the scan request. + * + * With Bluetooth 5, devices can advertise on more physical channels and by + * extension they can scan on more physical channel. It is possible to define + * independent scan parameters for every scannable physical channel. + */ class ScanParameters { public: @@ -120,28 +138,50 @@ public: } } + /** + * Set the address type used for scan requests. + * @param address The type of address to use during scan requests. + * @return A reference to this object. + */ ScanParameters &setOwnAddressType(own_address_type_t address) { own_address_type = address; return *this; } + /** + * Get the address type used during scan requests. + */ own_address_type_t getOwnAddressType() const { return own_address_type; } + /** + * Set the filter to apply during scanning. + * @param filter_policy The filter to apply during scannong. + * @return A reference to this object. + */ ScanParameters &setFilter(scanning_filter_policy_t filter_policy) { scanning_filter_policy = filter_policy; return *this; } + /** + * Get the filter to use during scanning + */ scanning_filter_policy_t getFilter() const { return scanning_filter_policy; } + /** + * Enable or disable phys that should be used during scanning . + * @param enable_1m True to enable the 1M phy and false to disable it. + * @param enable_coded True to enable the coded phy and false to disable it. + * @return A reference to this object. + */ ScanParameters &setPhys(bool enable_1m, bool enable_coded) { phys.set_1m(enable_1m); @@ -149,11 +189,21 @@ public: return *this; } + /** + * Get the phys to use during scanning. + */ phy_set_t getPhys() const { return phys; } + /** + * Set the 1M scan configuration. + * @param interval The scan interval to use. + * @param window The scan window to use. + * @param active_scanning The active scanning flag. + * @return A reference to this object. + */ ScanParameters &set1mPhyConfiguration( scan_interval_t interval, scan_window_t window, @@ -167,11 +217,21 @@ public: return *this; } + /** + * Get the 1M scan configuration. + */ phy_configuration_t get1mPhyConfiguration() const { return phy_1m_configuration; } + /** + * Set the coded phy scan configuration. + * @param interval The scan interval to use. + * @param window The scan window to use. + * @param active_scanning The active scanning flag. + * @return A reference to this object. + */ ScanParameters &setCodedPhyConfiguration( scan_interval_t interval, scan_window_t window, @@ -185,6 +245,9 @@ public: return *this; } + /** + * Get the coded phy scan configuration. + */ phy_configuration_t getCodedPhyConfiguration() const { return phy_1m_configuration; From 9621b26cab6117107bdabde59b9e2bf0f18c1df3 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 10:06:43 +0000 Subject: [PATCH 303/361] BLE: Reorganize ble::gap documentation group. --- .../FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 7 +++---- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 8 ++++---- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 8 ++++---- features/FEATURE_BLE/ble/gap/Events.h | 12 ++++++++++++ features/FEATURE_BLE/ble/gap/Gap.h | 12 ++++++++++++ features/FEATURE_BLE/ble/gap/ScanParameters.h | 8 ++++---- features/FEATURE_BLE/ble/gap/Types.h | 11 +++++++++++ 7 files changed, 50 insertions(+), 16 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 05af4b2a82..a08590dfce 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -29,6 +29,8 @@ #include "UUID.h" #include "ble/gap/Types.h" +namespace ble { + /** * @addtogroup ble * @{ @@ -36,8 +38,6 @@ * @{ */ -namespace ble { - /*! * List of standard Advertising Data types. * @@ -933,12 +933,11 @@ private: uint8_t _payload_length; }; -} // namespace ble - /** * @} * @} */ +} // namespace ble #endif /* ifndef MBED_GAP_ADVERTISING_DATA_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 001ca51320..9056c7a781 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -24,6 +24,8 @@ #include "blecommon.h" #include "SafeEnum.h" +namespace ble { + /** * @addtogroup ble * @{ @@ -31,8 +33,6 @@ * @{ */ -namespace ble { - /** * Parameters defining the advertising process. * @@ -531,11 +531,11 @@ private: bool _includeHeaderTxPower:1; }; -} // namespace ble - /** * @} * @} */ +} // namespace ble + #endif /* ifndef MBED_ADVERTISING_PARAMETERS_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index faa469bcd3..c0038c5f44 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -20,6 +20,8 @@ #include "ble/BLETypes.h" #include "mbed_assert.h" +namespace ble { + /** * @addtogroup ble * @{ @@ -27,8 +29,6 @@ * @{ */ -namespace ble { - /** * Parameters defining the connection initiation process. * @@ -453,11 +453,11 @@ private: bool _enabledPhy[MAX_PARAM_PHYS]; }; -} // namespace ble - /** * @} * @} */ +} // namespace ble + #endif /* ifndef MBED_EXTENDED_CONNECT_PARAMETERS_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index da9cebf70d..369e45ae61 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -23,6 +23,13 @@ namespace ble { +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + /** * Event generated when an advertising packet is seen during passive scanning * or a scan response is received during active scanning. @@ -805,6 +812,11 @@ private: }; +/** + * @} + * @} + */ + } // namespace ble #endif //BLE_GAP_EVENTS_H diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 552d1208d2..baa9422498 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -28,6 +28,13 @@ namespace ble { +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + /** * Define device discovery, connection and link management procedures. * @@ -1310,6 +1317,11 @@ protected: #endif }; +/** + * @} + * @} + */ + } // namespace ble #endif //BLE_GAP_GAP_H diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index b6f9f3eac1..e20db6aa85 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -21,6 +21,8 @@ #include "ble/blecommon.h" #include "BLETypes.h" +namespace ble { + /** * @addtogroup ble * @{ @@ -28,8 +30,6 @@ * @{ */ -namespace ble { - /** * Parameters defining the scan process. * @@ -263,11 +263,11 @@ private: phy_configuration_t phy_coded_configuration; }; -} // namespace ble - /** * @} * @} */ +} // namespace ble + #endif /* ifndef MBED_GAP_SCAN_PARAMETERS_H__ */ diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index c267d2dab3..b3ec2d10e8 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -23,6 +23,13 @@ namespace ble { +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + /* BLE units, using microseconds as the common denominator */ typedef Duration > adv_interval_t; typedef Duration, Value > adv_duration_t; @@ -719,6 +726,10 @@ struct disconnection_reason_t : SafeEnum { } }; +/** + * @} + * @} + */ } // namespace ble From 884d870b68f710535ef107e038a0e731314a3a85 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 10:57:07 +0000 Subject: [PATCH 304/361] BLE: Improve gap/Types.h documentation. --- features/FEATURE_BLE/ble/gap/Types.h | 166 ++++++++++++++++++++++++--- 1 file changed, 151 insertions(+), 15 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index b3ec2d10e8..29117e0df8 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -31,18 +31,99 @@ namespace ble { */ /* BLE units, using microseconds as the common denominator */ -typedef Duration > adv_interval_t; -typedef Duration, Value > adv_duration_t; -typedef Duration, Value > scan_duration_t; -typedef Duration > scan_period_t; -typedef Duration > scan_interval_t; -typedef Duration > scan_window_t; -typedef Duration > conn_interval_t; + +/** + * Time interval between two advertisement. + * + * The duration is in unit of 625µs and ranges from 0x20 to 0xFFFFFF . + * + * @note before Bluetooth 5 range was 0x20 to 0xFFFF. + */ +typedef Duration > adv_interval_t; + +/** + * Advertising process duration. + * + * The duration is in unit of 10ms and ranges from 0x0001 to 0xFFFF. The special + * value 0x0000 means the advertising process never ends; it is accessible with + * adv_duration_t::forever(). + */ +typedef Duration, /* forever */ Value > adv_duration_t; + +/** + * Scan process duration. + * + * The duration is in unit of 10ms and ranges from 0x0001 to 0xFFFF. The special + * value 0x0000 means the scan process never ends; it is accessible with + * scan_duration_t::forever(). + */ +typedef Duration, /* forever */ Value > scan_duration_t; + +/** + * Time interval between two scan processes. + * + * The duration is in unit of 1.28s and ranges from 0x0001 to 0xFFFF. The special + * value 0x0000 is used to indicate that scan_period_t is not used. + */ +typedef Duration > scan_period_t; + +/** + * Time interval between two scan. + * + * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF . + */ +typedef Duration > scan_interval_t; + +/** + * Duration of a scan. + * + * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF . + */ +typedef Duration > scan_window_t; + +/** + * Time interval between two connection events. + * + * The interval is in unit of 1.250 milliseconds and ranges from 0x06 to 0xC80. + */ +typedef Duration > conn_interval_t; + +/** + * Time after which a connection is loss of devices have not exchanged data. + * + * The duration is in unit of 10 milliseconds and ranges from 0x0A to 0xC80. + * + * @note this time should be no larger than (1 + ConnLatency) * ConnIntervalMax * 2 + */ typedef Duration > supervision_timeout_t; + +/** + * Duration of a connection event. + * + * The duration is in unit of 625µs and ranges from 0x0 to 0xFFFF . + */ typedef Duration > conn_event_length_t; + +/** + * Time after which a periodic sync link is considered loss if the receiver hasn't + * receive anything from the advertiser. + * + * The duration is in unit of 10 milliseconds and ranges from 0x0A to 0x4000. + */ typedef Duration > sync_timeout_t; + +/** + * Interval between two periodic advertsising events. + * + * The duration is in unit of 1.250ms and ranges from 0x06 to 0xFFFF. + */ typedef Duration > periodic_interval_t; +/** + * Number of connection events that can be skipped by the slave. + * + * It ranges from 0 to 0x1F3. + */ typedef Bounded slave_latency_t; /** @@ -66,6 +147,7 @@ typedef uint16_t periodic_sync_handle_t; * devices in the scanning range. */ struct advertising_type_t : SafeEnum { + /// enumeration of advertising_type_t values enum type { /** * Device is connectable, scannable and doesn't expect connection from a @@ -109,6 +191,8 @@ struct advertising_type_t : SafeEnum { /** * Construct a new advertising_type_t value. + * + * @param value The value of the advertising_type_t created. */ advertising_type_t(type value) : SafeEnum(value) { @@ -119,19 +203,24 @@ struct advertising_type_t : SafeEnum { /** Used to indicate if the packet is complete and if it's truncated. */ struct advertising_data_status_t : SafeEnum { + /// enumeration of advertising_data_status_t values enum type { - COMPLETE = 0x00, /**< Advertising payload complete. */ - INCOMPLETE_MORE_DATA = 0x01, /**< Partial advertising payload, more to come. */ - INCOMPLETE_DATA_TRUNCATED = 0x02 /**< Advertising payload incomplete and no more is comoing. */ + COMPLETE = 0x00, /// Advertising payload complete. + INCOMPLETE_MORE_DATA = 0x01, /// Partial advertising payload, more to come. + INCOMPLETE_DATA_TRUNCATED = 0x02 /// Advertising payload incomplete and no more is coming. }; /** * Construct a new advertising_data_status_t value. + * + * @param value The value of the advertising_data_status_t created. */ advertising_data_status_t(type value) : SafeEnum(value) { } +#if !defined(DOXYGEN_ONLY) + /** * Explicit constructor from a raw value. */ @@ -139,6 +228,9 @@ struct advertising_data_status_t : SafeEnum SafeEnum(static_cast(raw_value)) { } + +#endif + }; /** Properties of an advertising event. @@ -286,32 +378,37 @@ typedef int8_t advertising_power_t; * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2. */ struct advertising_filter_policy_t : SafeEnum { + /// enumeration of advertising_filter_policy_t values enum type { /** * Process connection and scan requests from all devices. The whitelist is * not used. */ - NO_FILTER = 0x00, + NO_FILTER = 0x00, /** * Process connection requests from all devices but filter out scan requests * of devices which are not in the whitelist. */ - FILTER_SCAN_REQUESTS = 0x01, + FILTER_SCAN_REQUESTS = 0x01, /** * Process scan requests from all devices but filter out connection requests * of devices which are not in the whitelist. */ - FILTER_CONNECTION_REQUEST = 0x02, + FILTER_CONNECTION_REQUEST = 0x02, /** * Filter out scan or connection requests of devices which are not in the * whitelist. */ - FILTER_SCAN_AND_CONNECTION_REQUESTS = 0x03 + FILTER_SCAN_AND_CONNECTION_REQUESTS = 0x03 }; + /** + * Construct a advertising_filter_policy_t. + * @param value The value of the advertising_filter_policy_t created. + */ advertising_filter_policy_t(type value) : SafeEnum(value) { } @@ -323,6 +420,7 @@ struct advertising_filter_policy_t : SafeEnum { + /// enumeration of scanning_filter_policy_t values enum type { /** * Accept all advertising packets except directed advertising packet not @@ -336,7 +434,6 @@ struct scanning_filter_policy_t : SafeEnum { */ FILTER_ADVERTISING = 0x01, - /** * Accept all advertising packets except directed advertising packets * where the initiator's identity address does not address this device. @@ -361,6 +458,8 @@ struct scanning_filter_policy_t : SafeEnum { /** * Construct a new instance of scanning_filter_policy_t. + * + * @param value The value of the scanning_filter_policy_t created. */ scanning_filter_policy_t(type value) : SafeEnum(value) { @@ -371,6 +470,7 @@ struct scanning_filter_policy_t : SafeEnum { * Filter policy which can be used during connection initiation. */ struct initiator_filter_policy_t : SafeEnum { + /// enumeration of initiator_filter_policy_t values. enum type { /** * The whitelist is not used to determine which advertiser to connect to. @@ -383,6 +483,10 @@ struct initiator_filter_policy_t : SafeEnum USE_WHITE_LIST }; + /** + * Construct a initiator_filter_policy_t. + * @param value The value of the initiator_filter_policy_t. + */ initiator_filter_policy_t(type value) : SafeEnum(value) { } @@ -394,6 +498,7 @@ struct initiator_filter_policy_t : SafeEnum * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3. */ struct duplicates_filter_t : SafeEnum { + /// enumeration of duplicates_filter_t values enum type { /** * Disable duplicate filtering. @@ -413,6 +518,7 @@ struct duplicates_filter_t : SafeEnum { /** * Construct a new duplicates_filter_t value. + * @param value The value of the duplicates_filter_t created. */ duplicates_filter_t(type value) : SafeEnum(value) { @@ -424,6 +530,7 @@ struct duplicates_filter_t : SafeEnum { * advertising, scanning and initiating */ struct own_address_type_t : SafeEnum { + /// enumeration of own_address_type_t values. enum type { /** * Use the public device address. @@ -454,13 +561,20 @@ struct own_address_type_t : SafeEnum { /** * Construct a new instance of own_address_type_t. + * @param value The value of the own_address_type_t created. */ own_address_type_t(type value) : SafeEnum(value) { } }; +/** + * Type of an address to connect to. + * + * It is used to connect to a device directly of with directed advertising. + */ struct target_peer_address_type_t : SafeEnum { + /// enumeration of target_peer_address_type_t values. enum type { PUBLIC = 0x00, /**< Public Device Address or Public Identity Address. */ PUBLIC_ADDRESS = 0x00, @@ -468,6 +582,11 @@ struct target_peer_address_type_t : SafeEnum { + /// enumeration of clock_accuracy_t values. enum type { /** * 500 PPM @@ -549,11 +669,14 @@ struct clock_accuracy_t : SafeEnum { /** * Construct a new clock_accuracy_t value. + * @param value The value of the clock_accuracy_t created. */ clock_accuracy_t(type value) : SafeEnum(value) { } +#if !defined(DOXYGEN_ONLY) + /** * Construct a new clock_accuracy_t value from a raw value. * @param raw_value The value of the clock accuracy. @@ -561,6 +684,8 @@ struct clock_accuracy_t : SafeEnum { explicit clock_accuracy_t(uint8_t raw_value) : SafeEnum(raw_value) { } + +#endif }; /** @@ -606,11 +731,14 @@ struct connection_role_t : SafeEnum { /** * Construct a new instance of role_t. + * + * @param value The value of the role_t created. */ connection_role_t(type value) : SafeEnum(value) { } +#if !defined(DOXYGEN_ONLY) /** * Explicit constructor from a raw value. @@ -619,12 +747,15 @@ struct connection_role_t : SafeEnum { explicit connection_role_t(uint8_t raw_value) : SafeEnum(raw_value) { } + +#endif }; /** * Enumeration of disconnection reasons that should be transmited to the peer. */ struct local_disconnection_reason_t : SafeEnum { + /// enumeration of local_disconnection_reason_t values. enum type { /** * GAP or GATT failed to authenticate the peer. @@ -669,6 +800,8 @@ struct local_disconnection_reason_t : SafeEnum { + /// enumeration of disconnection_reason_t values. enum type { /** * GAP or GATT failed to authenticate the peer. @@ -720,6 +854,8 @@ struct disconnection_reason_t : SafeEnum { /** * Construct a new instance of disconnection_reason_t. + * + * @param value The value of the disconnection_reason_t created. */ disconnection_reason_t(type value) : SafeEnum(value) { From 78d4a9b6c8a980a4a016ef3c6a54d2f09a3b4ee1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 11:22:55 +0000 Subject: [PATCH 305/361] BLE: Cleanup enum duplicates in gap/Types.h --- .../ble/gap/AdvertisingParameters.h | 4 +- features/FEATURE_BLE/ble/gap/Types.h | 60 +++++++------------ features/FEATURE_BLE/ble/pal/GapEvents.h | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 20 +++---- .../source/generic/GenericSecurityManager.cpp | 10 ++-- 5 files changed, 40 insertions(+), 56 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 9056c7a781..6ed73e7cb5 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -127,7 +127,7 @@ public: * @note If value in input are out of range, they will be normalized. */ AdvertisingParameters( - advertising_type_t advType = advertising_type_t::ADV_CONNECTABLE_UNDIRECTED, + advertising_type_t advType = advertising_type_t::CONNECTABLE_UNDIRECTED, adv_interval_t minInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MIN), adv_interval_t maxInterval = adv_interval_t(DEFAULT_ADVERTISING_INTERVAL_MAX) ) : @@ -151,7 +151,7 @@ public: _includeHeaderTxPower(false) { /* Min interval is slightly larger than in other modes. */ - if (_advType == advertising_type_t::ADV_NON_CONNECTABLE_UNDIRECTED) { + if (_advType == advertising_type_t::NON_CONNECTABLE_UNDIRECTED) { _minInterval = adv_interval_t(std::max(_minInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); _maxInterval = adv_interval_t(std::max(_maxInterval.value(), GAP_ADV_PARAMS_INTERVAL_MIN_NONCON)); } diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 29117e0df8..d56ed9fc52 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -95,14 +95,14 @@ typedef Duration > conn_interval_t; * * @note this time should be no larger than (1 + ConnLatency) * ConnIntervalMax * 2 */ -typedef Duration > supervision_timeout_t; +typedef Duration > supervision_timeout_t; /** * Duration of a connection event. * * The duration is in unit of 625µs and ranges from 0x0 to 0xFFFF . */ -typedef Duration > conn_event_length_t; +typedef Duration > conn_event_length_t; /** * Time after which a periodic sync link is considered loss if the receiver hasn't @@ -110,14 +110,14 @@ typedef Duration > conn_event_length_t * * The duration is in unit of 10 milliseconds and ranges from 0x0A to 0x4000. */ -typedef Duration > sync_timeout_t; +typedef Duration > sync_timeout_t; /** * Interval between two periodic advertsising events. * * The duration is in unit of 1.250ms and ranges from 0x06 to 0xFFFF. */ -typedef Duration > periodic_interval_t; +typedef Duration > periodic_interval_t; /** * Number of connection events that can be skipped by the slave. @@ -155,38 +155,42 @@ struct advertising_type_t : SafeEnum { * * @see Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1. */ - ADV_CONNECTABLE_UNDIRECTED = 0x00, - ADV_IND = 0x00, + CONNECTABLE_UNDIRECTED = 0x00, /** * Device is connectable and expects connection from a specific peer. * (3.75 ms or smaller Advertising Interval) * @see Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2. */ - ADV_CONNECTABLE_DIRECTED = 0x01, - ADV_DIRECT_IND = 0x01, + CONNECTABLE_DIRECTED = 0x01, /** * Device is scannable but not connectable. * * @see Vol 6, Part B, Section 2.3.1.4. */ - ADV_SCANNABLE_UNDIRECTED = 0x02, - ADV_SCAN_IND = 0x02, + SCANNABLE_UNDIRECTED = 0x02, /** * Device is not connectable and not scannable. * * @see Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3. */ - ADV_NON_CONNECTABLE_UNDIRECTED = 0x03, - ADV_NONCONN_IND = 0x03, + NON_CONNECTABLE_UNDIRECTED = 0x03, /** * Device is connectable and expects connection from a specific peer (sent at long user set intervals). */ - ADV_CONNECTABLE_DIRECTED_LOW_DUTY = 0x04, + CONNECTABLE_DIRECTED_LOW_DUTY = 0x04, + +#if !defined(DOXYGEN_ONLY) + // used by the PAL; naming in line with the the spec. + ADV_IND = 0x00, + ADV_DIRECT_IND = 0x01, + ADV_SCAN_IND = 0x02, + ADV_NONCONN_IND = 0x03, ADV_DIRECT_IND_LOW_DUTY_CYCLE = 0x04 +#endif }; /** @@ -329,7 +333,7 @@ public: */ bool complete() const { - return data_status().value() == advertising_data_status_t::COMPLETE; + return data_status() == advertising_data_status_t::COMPLETE; } /** Is there more data coming. @@ -338,7 +342,7 @@ public: */ bool more_data_to_come() const { - return data_status().value() == advertising_data_status_t::INCOMPLETE_MORE_DATA; + return data_status() == advertising_data_status_t::INCOMPLETE_MORE_DATA; } /** Is the payload truncated. @@ -347,7 +351,7 @@ public: */ bool truncated() const { - return data_status().value() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; + return data_status() == advertising_data_status_t::INCOMPLETE_DATA_TRUNCATED; } private: @@ -535,13 +539,11 @@ struct own_address_type_t : SafeEnum { /** * Use the public device address. */ - PUBLIC_ADDRESS = 0x00, PUBLIC = 0x00, /** * Use the random device address. */ - RANDOM_ADDRESS = 0x01, RANDOM = 0x01, /** @@ -577,10 +579,7 @@ struct target_peer_address_type_t : SafeEnum { */ CENTRAL = 0x00, - /** - * @see CENTRAL - */ - MASTER = 0x00, - /** * Peripheral Role. * @@ -721,12 +715,7 @@ struct connection_role_t : SafeEnum { * * @note A peripheral is a broadcaster. */ - PERIPHERAL = 0x01, - - /** - * @see PERIPHERAL - */ - SLAVE = 0x01 + PERIPHERAL = 0x01 }; /** @@ -761,25 +750,21 @@ struct local_disconnection_reason_t : SafeEnum { /** * Connection parameters were unacceptable. */ - CONN_INTERVAL_UNACCEPTABLE = 0x3B + UNACCEPTABLE_CONNECTION_PARAMETERS = 0x3B }; /** diff --git a/features/FEATURE_BLE/ble/pal/GapEvents.h b/features/FEATURE_BLE/ble/pal/GapEvents.h index 728205479f..28623eb3f4 100644 --- a/features/FEATURE_BLE/ble/pal/GapEvents.h +++ b/features/FEATURE_BLE/ble/pal/GapEvents.h @@ -158,7 +158,7 @@ struct GapConnectionCompleteEvent : public GapEvent { connection_handle(connection_handle), role(role), peer_address_type( - peer_address_type == advertising_peer_address_type_t::PUBLIC_ADDRESS ? + peer_address_type == advertising_peer_address_type_t::PUBLIC ? peer_address_type_t::PUBLIC : peer_address_type_t::RANDOM ), diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 5aa9fb2bc1..3c59c4f726 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1097,7 +1097,7 @@ ble_error_t GenericGap::startRadioScan(const GapScanningParams &scanningParams) pal::own_address_type_t own_address_type = get_own_address_type(CENTRAL_SCAN /* central, can use non resolvable address for scan requests */); - if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) { + if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM)) { // Use non-resolvable static random address set_random_address_rotation(true); } @@ -1227,7 +1227,7 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) pal::own_address_type_t own_address_type = get_own_address_type(address_use_type); - if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM_ADDRESS)) { + if (_privacy_enabled && (own_address_type == pal::own_address_type_t::RANDOM)) { // Use non-resolvable static random address set_random_address_rotation(true); } @@ -1243,7 +1243,7 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) /* advertising_interval_max */ params.getIntervalInADVUnits(), (pal::advertising_type_t::type) params.getAdvertisingType(), own_address_type, - pal::advertising_peer_address_type_t::PUBLIC_ADDRESS, + pal::advertising_peer_address_type_t::PUBLIC, ble::address_t(), pal::advertising_channel_map_t::ALL_ADVERTISING_CHANNELS, _advertising_filter_policy @@ -1473,7 +1473,7 @@ BLE_DEPRECATED_API_USE_END() bool needs_authentication = false; if (_privacy_enabled && - e.role.value() == e.role.SLAVE && + e.role.value() == e.role.PERIPHERAL && e.peer_address_type == peer_address_type_t::RANDOM ) { // Apply privacy policy if in peripheral mode for non-resolved addresses @@ -1490,7 +1490,7 @@ BLE_DEPRECATED_API_USE_END() // Reject connection request - the user will get notified through a callback _pal_gap.disconnect( e.connection_handle, - pal::disconnection_reason_t::AUTHENTICATION_FAILLURE + pal::disconnection_reason_t::AUTHENTICATION_FAILURE ); return; @@ -1508,7 +1508,7 @@ BLE_DEPRECATED_API_USE_END() } } - if (e.role.value() == e.role.SLAVE) { + if (e.role.value() == e.role.PERIPHERAL) { _advertising_timeout.detach(); _pal_gap.advertising_enable(false); @@ -1534,7 +1534,7 @@ BLE_DEPRECATED_API_USE_END() processConnectionEvent( e.connection_handle, - e.role.value() == e.role.MASTER ? ::Gap::CENTRAL : ::Gap::PERIPHERAL, + e.role.value() == e.role.CENTRAL ? ::Gap::CENTRAL : ::Gap::PERIPHERAL, e.peer_address_type, e.peer_address.data(), _address_type, @@ -1606,7 +1606,7 @@ pal::own_address_type_t GenericGap::get_own_address_type(AddressUseType_t addres // An non resolvable private address should be generated if (use_non_resolvable_address) { - return pal::own_address_type_t::RANDOM_ADDRESS; + return pal::own_address_type_t::RANDOM; } switch (_address_type) { @@ -1619,9 +1619,9 @@ pal::own_address_type_t GenericGap::get_own_address_type(AddressUseType_t addres switch (_address_type) { case BLEProtocol::AddressType::PUBLIC: - return pal::own_address_type_t::PUBLIC_ADDRESS; + return pal::own_address_type_t::PUBLIC; default: - return pal::own_address_type_t::RANDOM_ADDRESS; + return pal::own_address_type_t::RANDOM; } } diff --git a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp index fc6da98b71..0c5e047dc4 100644 --- a/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp +++ b/features/FEATURE_BLE/source/generic/GenericSecurityManager.cpp @@ -1100,8 +1100,8 @@ void GenericSecurityManager::on_security_entry_retrieved( _pal.add_device_to_resolving_list( identity->identity_address_is_public ? - address_type_t::PUBLIC_ADDRESS : - address_type_t::RANDOM_ADDRESS, + address_type_t::PUBLIC : + address_type_t::RANDOM, identity->identity_address, identity->irk ); @@ -1117,8 +1117,8 @@ void GenericSecurityManager::on_identity_list_retrieved( for (size_t i = 0; i < count; ++i) { _pal.add_device_to_resolving_list( identity_list[i].identity_address_is_public ? - address_type_t::PUBLIC_ADDRESS : - address_type_t::RANDOM_ADDRESS, + address_type_t::PUBLIC : + address_type_t::RANDOM, identity_list[i].identity_address, identity_list[i].irk ); @@ -1564,7 +1564,7 @@ void GenericSecurityManager::on_keys_distributed_bdaddr( _db->set_entry_peer_bdaddr( cb->db_entry, - (peer_address_type == advertising_peer_address_type_t::PUBLIC_ADDRESS), + (peer_address_type == advertising_peer_address_type_t::PUBLIC), peer_identity_address ); } From dff8f25d49de987cf697d386ff2fb3a928c1440f Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 11:34:21 +0000 Subject: [PATCH 306/361] BLE: Improve Duration documentation. --- features/FEATURE_BLE/ble/common/Duration.h | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 416c0ba7a4..2bb91c5c0a 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -23,6 +23,8 @@ namespace ble { +#if !defined(DOXYGEN_ONLY) + /** * Define a compile time range. * @tparam Min left-bound @@ -78,6 +80,8 @@ struct Value { static const T VALUE = V; }; +#endif + /** * Model BLE durations. * @@ -267,6 +271,8 @@ typedef Duration second_t; * @tparam FIn The Forever value of duration. * @param duration The duration to convert. * @return The converted duration. It is rounded up if precision is loss. + * + * @related Duration */ template DurationOut durationCast(Duration duration) @@ -279,6 +285,8 @@ DurationOut durationCast(Duration duration) * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return The result of the addition of the two durations in microseconds. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -296,6 +304,8 @@ microsecond_t operator+( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return The addition of the two durations in input. + * + * @related Duration */ template Duration operator+( @@ -313,6 +323,8 @@ Duration operator+( * @param rhs The integer. * * @return A duration that represents the multiplication of lhs with rhs. + * + * @related Duration */ template Duration operator*(Duration lhs, uint32_t rhs) @@ -327,6 +339,8 @@ Duration operator*(Duration lhs, uint32_t * @param rhs The multiplication. * * @return A duration that represents the multiplication of lhs with rhs. + * + * @related Duration */ template Duration operator*(uint32_t lhs, Duration rhs) @@ -339,6 +353,8 @@ Duration operator*(uint32_t lhs, Duration * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is less than rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -354,6 +370,8 @@ bool operator<(Duration lhs, Duration bool operator<(Duration lhs, Duration rhs) @@ -366,6 +384,8 @@ bool operator<(Duration lhs, Duration rhs) * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is less than or equal to rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -384,6 +404,8 @@ bool operator<=( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is less than or equal to rhs and false otherwise. + * + * @related Duration */ template bool operator<=(Duration lhs, Duration rhs) @@ -396,6 +418,8 @@ bool operator<=(Duration lhs, Duration rhs) * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is equal to rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -414,6 +438,8 @@ bool operator==( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is equal to rhs and false otherwise. + * + * @related Duration */ template bool operator==(Duration lhs, Duration rhs) @@ -426,6 +452,8 @@ bool operator==(Duration lhs, Duration rhs * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is not equal to rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -444,6 +472,8 @@ bool operator!=( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is not equal to rhs and false otherwise. + * + * @related Duration */ template bool operator!=(Duration lhs, Duration rhs) @@ -456,6 +486,8 @@ bool operator!=(Duration lhs, Duration rhs * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is greater or equal to rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -474,6 +506,8 @@ bool operator>=( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is greater or equal to rhs and false otherwise. + * + * @related Duration */ template bool operator>=(Duration lhs, Duration rhs) @@ -486,6 +520,8 @@ bool operator>=(Duration lhs, Duration rhs * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is greater than rhs and false otherwise. + * + * @related Duration */ template< typename RepLHS, uint32_t TBLHS, typename RangeLHS, typename FLHS, @@ -504,6 +540,8 @@ bool operator>( * @param lhs Left hand side operand. * @param rhs Right hand side operand. * @return true if lhs is greater than rhs and false otherwise. + * + * @related Duration */ template bool operator>(Duration lhs, Duration rhs) @@ -513,6 +551,8 @@ bool operator>(Duration lhs, Duration rhs) /* ---------------------- Static variable initialization -------------------- */ +#if !defined(DOXYGEN_ONLY) + template const uint32_t Range::MIN; @@ -522,6 +562,8 @@ const uint32_t Range::MAX; template const T Value::VALUE; +#endif + template const uint32_t Duration::TIME_BASE; From 0407ee8c810c42f3fe0efd33b29b2d2f63b35a06 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 11:46:00 +0000 Subject: [PATCH 307/361] BLE: move privacy configuration type in ble namespace. --- features/FEATURE_BLE/ble/Gap.h | 10 ++ features/FEATURE_BLE/ble/gap/Gap.h | 169 +++++------------------- features/FEATURE_BLE/ble/gap/Types.h | 103 +++++++++++++++ features/FEATURE_BLE/source/gap/Gap.cpp | 16 +-- 4 files changed, 152 insertions(+), 146 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index c74b729458..eb500cd30e 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -649,6 +649,16 @@ public: } }; + /** + * @copydoc ble::peripheral_privacy_configuration_t + */ + typedef ble::peripheral_privacy_configuration_t PeripheralPrivacyConfiguration_t; + + /** + * @copydoc ble::central_privay_configuration_t + */ + typedef ble::central_privay_configuration_t CentralPrivacyConfiguration_t; + /** * Number of microseconds in 1.25 milliseconds. */ diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index baa9422498..b2d0023aee 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -1075,146 +1075,16 @@ public: coded_symbol_per_bit_t codedSymbol ); -protected: - -#if !defined(DOXYGEN_ONLY) - - /* Override the following in the underlying adaptation layer to provide the - * functionality of scanning. */ - - /** Can only be called if use_non_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionOneAPI() const - { - } - - /** Can only be called if use_deprecated_scan_api() hasn't been called. - * This guards against mixed use of deprecated and nondeprecated API. - */ - virtual void useVersionTwoAPI() const - { - } - -#endif - - - /* -------- soon to be deprecated API -------- */ - -public: - /** - * Privacy Configuration of the peripheral role. - * - * @note This configuration also applies to the broadcaster role configuration. - */ - struct PeripheralPrivacyConfiguration_t { - /** - * Indicates if non resolvable random address should be used when the - * peripheral advertises non connectable packets. - * - * Resolvable random address continues to be used for connectable packets. - */ - bool use_non_resolvable_random_address; - - /** - * Resolution strategy for initiator resolvable addresses when a - * connection request is received. - */ - enum ResolutionStrategy { - /** - * Do not resolve the address of the initiator and accept the - * connection request. - */ - DO_NOT_RESOLVE, - - /** - * If a bond is present in the secure database and the address - * resolution fail then reject the connection request with the error - * code AUTHENTICATION_FAILLURE. - */ - REJECT_NON_RESOLVED_ADDRESS, - - /** - * Perform the pairing procedure if the initiator resolvable - * address failed the resolution process. - */ - PERFORM_PAIRING_PROCEDURE, - - /** - * Perform the authentication procedure if the initiator resolvable - * address failed the resolution process. - */ - PERFORM_AUTHENTICATION_PROCEDURE - }; - - /** - * Connection strategy to use when a connection request contains a - * private resolvable address. - */ - ResolutionStrategy resolution_strategy; - }; - - /** - * Privacy Configuration of the central role. - * - * @note This configuration is also used when the local device operates as - * an observer. - */ - struct CentralPrivacyConfiguration_t { - /** - * Indicates if non resolvable random address should be used when the - * central or observer sends scan request packets. - * - * Resolvable random address continue to be used for connection requests. - */ - bool use_non_resolvable_random_address; - - - /** - * Resolution strategy of resolvable addresses received in advertising - * packets. - */ - enum ResolutionStrategy { - /** - * Do not resolve the address received in advertising packets. - */ - DO_NOT_RESOLVE, - - /** - * Resolve the resolvable addresses in the advertising packet and - * forward advertising packet to the application independently of - * the address resolution procedure result. - */ - RESOLVE_AND_FORWARD, - - /** - * Filter out packets containing a resolvable that cannot be resolved - * by this device. - * - * @note Filtering is applied if the local device contains at least - * one bond. - */ - RESOLVE_AND_FILTER - }; - - /** - * Resolution strategy applied to advertising packets received by the - * local device. - */ - ResolutionStrategy resolution_strategy; - }; - - /** - * Default peripheral privacy configuration. - */ - static const PeripheralPrivacyConfiguration_t + * Default peripheral privacy configuration. + */ + static const peripheral_privacy_configuration_t default_peripheral_privacy_configuration; /** * Default peripheral privacy configuration. */ - static const CentralPrivacyConfiguration_t + static const central_privay_configuration_t default_central_privacy_configuration; /** @@ -1260,7 +1130,7 @@ public: * @return BLE_ERROR_NONE in case of success or an appropriate error code. */ virtual ble_error_t setPeripheralPrivacyConfiguration( - const PeripheralPrivacyConfiguration_t *configuration + const peripheral_privacy_configuration_t *configuration ); /** @@ -1272,7 +1142,7 @@ public: * @return BLE_ERROR_NONE in case of success or an appropriate error code. */ virtual ble_error_t getPeripheralPrivacyConfiguration( - PeripheralPrivacyConfiguration_t *configuration + peripheral_privacy_configuration_t *configuration ); /** @@ -1283,7 +1153,7 @@ public: * @return BLE_ERROR_NONE in case of success or an appropriate error code. */ virtual ble_error_t setCentralPrivacyConfiguration( - const CentralPrivacyConfiguration_t *configuration + const central_privay_configuration_t *configuration ); /** @@ -1295,11 +1165,34 @@ public: * @return BLE_ERROR_NONE in case of success or an appropriate error code. */ virtual ble_error_t getCentralPrivacyConfiguration( - CentralPrivacyConfiguration_t *configuration + central_privay_configuration_t *configuration ); protected: +#if !defined(DOXYGEN_ONLY) + + /* Override the following in the underlying adaptation layer to provide the + * functionality of scanning. */ + + /** Can only be called if use_non_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionOneAPI() const + { + } + + /** Can only be called if use_deprecated_scan_api() hasn't been called. + * This guards against mixed use of deprecated and nondeprecated API. + */ + virtual void useVersionTwoAPI() const + { + } + +#endif + +protected: + #if !defined(DOXYGEN_ONLY) /** diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index d56ed9fc52..21c50d7713 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -846,6 +846,109 @@ struct disconnection_reason_t : SafeEnum { } }; +/** + * Privacy Configuration of the peripheral role. + * + * @note This configuration also applies to the broadcaster role configuration. + */ +struct peripheral_privacy_configuration_t { + /** + * Indicates if non resolvable random address should be used when the + * peripheral advertises non connectable packets. + * + * Resolvable random address continues to be used for connectable packets. + */ + bool use_non_resolvable_random_address; + + /** + * Resolution strategy for initiator resolvable addresses when a + * connection request is received. + */ + enum resolution_strategy_t { + /** + * Do not resolve the address of the initiator and accept the + * connection request. + */ + DO_NOT_RESOLVE, + + /** + * If a bond is present in the secure database and the address + * resolution fail then reject the connection request with the error + * code AUTHENTICATION_FAILLURE. + */ + REJECT_NON_RESOLVED_ADDRESS, + + /** + * Perform the pairing procedure if the initiator resolvable + * address failed the resolution process. + */ + PERFORM_PAIRING_PROCEDURE, + + /** + * Perform the authentication procedure if the initiator resolvable + * address failed the resolution process. + */ + PERFORM_AUTHENTICATION_PROCEDURE + }; + + /** + * Connection strategy to use when a connection request contains a + * private resolvable address. + */ + resolution_strategy_t resolution_strategy; +}; + +/** + * Privacy Configuration of the central role. + * + * @note This configuration is also used when the local device operates as + * an observer. + */ +struct central_privay_configuration_t { + /** + * Indicates if non resolvable random address should be used when the + * central or observer sends scan request packets. + * + * Resolvable random address continue to be used for connection requests. + */ + bool use_non_resolvable_random_address; + + + /** + * Resolution strategy of resolvable addresses received in advertising + * packets. + */ + enum resolution_strategy_t { + /** + * Do not resolve the address received in advertising packets. + */ + DO_NOT_RESOLVE, + + /** + * Resolve the resolvable addresses in the advertising packet and + * forward advertising packet to the application independently of + * the address resolution procedure result. + */ + RESOLVE_AND_FORWARD, + + /** + * Filter out packets containing a resolvable that cannot be resolved + * by this device. + * + * @note Filtering is applied if the local device contains at least + * one bond. + */ + RESOLVE_AND_FILTER + }; + + /** + * Resolution strategy applied to advertising packets received by the + * local device. + */ + resolution_strategy_t resolution_strategy; +}; + + /** * @} * @} diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 3f69641368..8b62805df3 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -317,14 +317,14 @@ ble_error_t Gap::setPhy( /* -------------------- Future deprecation ------------------------- */ -const Gap::PeripheralPrivacyConfiguration_t Gap::default_peripheral_privacy_configuration = { +const peripheral_privacy_configuration_t Gap::default_peripheral_privacy_configuration = { /* use_non_resolvable_random_address */ false, - /* resolution_strategy */ PeripheralPrivacyConfiguration_t::PERFORM_PAIRING_PROCEDURE + /* resolution_strategy */ peripheral_privacy_configuration_t::PERFORM_PAIRING_PROCEDURE }; -const Gap::CentralPrivacyConfiguration_t Gap::default_central_privacy_configuration = { +const central_privay_configuration_t Gap::default_central_privacy_configuration = { /* use_non_resolvable_random_address */ false, - /* resolution_strategy */ CentralPrivacyConfiguration_t::RESOLVE_AND_FORWARD + /* resolution_strategy */ central_privay_configuration_t::RESOLVE_AND_FORWARD }; ble_error_t Gap::enablePrivacy(bool enable) @@ -333,28 +333,28 @@ ble_error_t Gap::enablePrivacy(bool enable) } ble_error_t Gap::setPeripheralPrivacyConfiguration( - const PeripheralPrivacyConfiguration_t *configuration + const peripheral_privacy_configuration_t *configuration ) { return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::getPeripheralPrivacyConfiguration( - PeripheralPrivacyConfiguration_t *configuration + peripheral_privacy_configuration_t *configuration ) { return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::setCentralPrivacyConfiguration( - const CentralPrivacyConfiguration_t *configuration + const central_privay_configuration_t *configuration ) { return BLE_ERROR_NOT_IMPLEMENTED; } ble_error_t Gap::getCentralPrivacyConfiguration( - CentralPrivacyConfiguration_t *configuration + central_privay_configuration_t *configuration ) { return BLE_ERROR_NOT_IMPLEMENTED; From be7cc41da4367c54a944fe3ea45c184e398fbf35 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 13:48:26 +0000 Subject: [PATCH 308/361] BLE: doxygen fixes. --- features/FEATURE_BLE/ble/BLETypes.h | 4 ++++ features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 8 ++++++-- features/FEATURE_BLE/ble/gap/AdvertisingParameters.h | 6 +++--- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 2261ec2756..55cead261d 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -321,6 +321,10 @@ void set_all_zeros(byte_array_class &byte_array) { memset(&byte_array[0], 0x00, byte_array.size()); } +/** + * Model fixed size array values. + * @tparam array_size The size of the array. + */ template struct byte_array_t { /** diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index a08590dfce..a7ce3ccdbe 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -539,7 +539,12 @@ struct adv_data_appearance_t : SafeEnum { } }; - +/** + * Build advertising data. + * + * The builder accept an array of bytes in input and returns the result of the + * construction with getAdvertisingData(). + */ class AdvertisingDataBuilder { public: /** Advertising data needs a user provided buffer to store the data. @@ -774,7 +779,6 @@ public: * * @param[in] service UUID of the service. * @param[in] data New data to be added. - * @param[in] complete True if this is a complete list. * * @retval BLE_ERROR_NONE on success. * @retval BLE_ERROR_BUFFER_OVERFLOW if buffer is too small to contain the new data. diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 6ed73e7cb5..2598e851bb 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -184,7 +184,7 @@ public: /** Set the advertising intervals on the primary channels. * - * @param[in] minInterval, maxInterval Time interval between two advertisement. + * @param[in] min, max Time interval between two advertisement. * A range is provided to the LE subsystem so it can adjust the advertising * interval with other transmission happening on the BLE radio. * @@ -325,7 +325,7 @@ public: /** Set the filter policy of whitelist use during advertising; * - * @param Policy to use. + * @param mode Policy to use. * * @return A reference to this object. */ @@ -427,7 +427,7 @@ public: * * @return A reference to this object. * - * @see ::ble::Gap::EventHandler::onScanRequest() + * @see ::ble::Gap::EventHandler::onScanRequestReceived() */ AdvertisingParameters &setScanRequestNotification(bool enable = true) { From 09ba26ce4b06197119dda3c31d0c3e133f83485c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 14:56:53 +0000 Subject: [PATCH 309/361] BLE: Move advertising data types in their own file. --- .../ble/gap/AdvertisingDataBuilder.h | 503 +---------------- .../ble/gap/AdvertisingDataTypes.h | 534 ++++++++++++++++++ 2 files changed, 535 insertions(+), 502 deletions(-) create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index a7ce3ccdbe..72fcd1bb06 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -25,8 +25,8 @@ #include "platform/NonCopyable.h" #include "ble/blecommon.h" -#include "ble/SafeEnum.h" #include "UUID.h" +#include "ble/gap/AdvertisingDataTypes.h" #include "ble/gap/Types.h" namespace ble { @@ -38,507 +38,6 @@ namespace ble { * @{ */ -/*! - * List of standard Advertising Data types. - * - * These AD types are used to describe the capabilities of the peripheral - * and are inserted inside the advertising or scan response payloads. - * - * @par Source - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. - * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. - */ -struct adv_data_type_t : SafeEnum { - /** struct scoped enum wrapped by the class */ - enum type { - /** - * Flags, refer to AdvertisingData::Flags_t. - */ - FLAGS = 0x01, - - /** - * Incomplete list of 16-bit Service IDs. - */ - INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, - - /** - * Complete list of 16-bit Service IDs. - */ - COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, - - /** - * Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). - */ - INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, - - /** - * Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). - */ - COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, - - /** - * Incomplete list of 128-bit Service IDs. - */ - INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, - - /** - * Complete list of 128-bit Service IDs. - */ - COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, - - /** - * Shortened Local Name. - */ - SHORTENED_LOCAL_NAME = 0x08, - - /** - * Complete Local Name. - */ - COMPLETE_LOCAL_NAME = 0x09, - - /** - * TX Power Level (in dBm). - */ - TX_POWER_LEVEL = 0x0A, - - /** - * Device ID. - */ - DEVICE_ID = 0x10, - - /** - * Slave Connection Interval Range. - */ - SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, - - /** - * List of 128-bit service UUIDs the device is looking for. - */ - LIST_16BIT_SOLICITATION_IDS = 0x14, - - /** - * List of 128-bit service UUIDs the device is looking for. - */ - LIST_128BIT_SOLICITATION_IDS = 0x15, - - /** - * Service Data. - */ - SERVICE_DATA = 0x16, - - /** - * Service Data. - */ - SERVICE_DATA_16BIT_ID = 0x16, - - /** - * Service Data. - */ - SERVICE_DATA_128BIT_ID = 0x21, - - /** - * Appearance, refer to AdvertisingData::Appearance_t. - */ - APPEARANCE = 0x19, - - /** - * Advertising Interval. - */ - ADVERTISING_INTERVAL = 0x1A, - - /** - * Manufacturer Specific Data. - */ - MANUFACTURER_SPECIFIC_DATA = 0xFF - }; - - /** - * Construct a new instance of adv_data_type_t. - */ - adv_data_type_t(type value) : SafeEnum(value) - { - } -}; - - -/** - * Set of advertising flags. - * - * @note LE_LIMITED_DISCOVERABLE and LE_GENERAL_DISCOVERABLE are mutually - * exclusive - * - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. - */ -struct adv_data_flags_t { - enum { - LE_LIMITED_DISCOVERABLE = 0x01, /**< Discoverable for a limited period of time.*/ - LE_GENERAL_DISCOVERABLE = 0x02, /**< Discoverable at any moment. */ - BREDR_NOT_SUPPORTED = 0x04, /**< LE only and does not support Bluetooth Enhanced DataRate. */ - SIMULTANEOUS_LE_BREDR_C = 0x08, /**< Not relevant - dual mode only. */ - SIMULTANEOUS_LE_BREDR_H = 0x10 /**< Not relevant - dual mode only. */ - }; - - static const uint8_t default_flags = BREDR_NOT_SUPPORTED | LE_GENERAL_DISCOVERABLE; - - /** Create from raw value */ - adv_data_flags_t(uint8_t value = 0) : _value(value) - { - } - - adv_data_flags_t &setGeneralDiscoverable(bool enable = true) - { - _value &= ~0x03; - if (enable) { - _value |= LE_GENERAL_DISCOVERABLE; - } - return *this; - } - - adv_data_flags_t &setLimitedDiscoverable(bool enable = true) - { - _value &= ~0x03; - if (enable) { - _value |= LE_LIMITED_DISCOVERABLE; - } - return *this; - } - - adv_data_flags_t &setBredrNotSupported(bool enable = true) - { - _value &= ~BREDR_NOT_SUPPORTED; - if (enable) { - _value |= BREDR_NOT_SUPPORTED; - } - return *this; - } - - adv_data_flags_t &setSimultaneousLeBredrC(bool enable = true) - { - _value &= ~SIMULTANEOUS_LE_BREDR_C; - if (enable) { - _value |= SIMULTANEOUS_LE_BREDR_C; - } - return *this; - } - - adv_data_flags_t &setSimultaneousLeBredrH(bool enable = true) - { - _value &= ~SIMULTANEOUS_LE_BREDR_H; - if (enable) { - _value |= SIMULTANEOUS_LE_BREDR_H; - } - return *this; - } - - bool getGeneralDiscoverable() - { - return _value & LE_GENERAL_DISCOVERABLE; - } - - bool getlimitedDiscoverable() - { - return _value & LE_LIMITED_DISCOVERABLE; - } - - bool getBrEdrNotSupported() - { - return _value & BREDR_NOT_SUPPORTED; - } - - bool getSimultaneousLeBredrC() - { - return _value & SIMULTANEOUS_LE_BREDR_C; - } - - bool getSimultaneousLeBredrH() - { - return _value & SIMULTANEOUS_LE_BREDR_H; - } - - void clear() - { - _value = 0; - } - - uint8_t value() - { - return _value; - } - -private: - uint8_t _value; -}; - - -/** - * Enumeration of values for the adv_data_type_t::APPEARANCE. - * - * These values describe the physical shape or appearance of the device. - * - * @par Source - * - * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. - * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. - * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. - */ -struct adv_data_appearance_t : SafeEnum { - /** struct scoped enum wrapped by the class */ - enum type { - /** - * Unknown or unspecified appearance type. - */ - UNKNOWN = 0, - - /** - * Generic Phone. - */ - GENERIC_PHONE = 64, - - /** - * Generic Computer. - */ - GENERIC_COMPUTER = 128, - - /** - * Generic Watch. - */ - GENERIC_WATCH = 192, - - /** - * Sports Watch. - */ - WATCH_SPORTS_WATCH = 193, - - /** - * Generic Clock. - */ - GENERIC_CLOCK = 256, - - /** - * Generic Display. - */ - GENERIC_DISPLAY = 320, - - /** - * Generic Remote Control. - */ - GENERIC_REMOTE_CONTROL = 384, - - /** - * Generic Eye Glasses. - */ - GENERIC_EYE_GLASSES = 448, - - /** - * Generic Tag. - */ - GENERIC_TAG = 512, - - /** - * Generic Keyring. - */ - GENERIC_KEYRING = 576, - - /** - * Generic Media Player. - */ - GENERIC_MEDIA_PLAYER = 640, - - /** - * Generic Bar Code Scanner. - */ - GENERIC_BARCODE_SCANNER = 704, - - /** - * Generic Thermometer. - */ - GENERIC_THERMOMETER = 768, - - /** - * Ear Thermometer. - */ - THERMOMETER_EAR = 769, - - /** - * Generic Heart Rate Sensor. - */ - GENERIC_HEART_RATE_SENSOR = 832, - - /** - * Belt Heart Rate Sensor. - */ - HEART_RATE_SENSOR_HEART_RATE_BELT = 833, - - /** - * Generic Blood Pressure. - */ - GENERIC_BLOOD_PRESSURE = 896, - - /** - * Arm Blood Pressure. - */ - BLOOD_PRESSURE_ARM = 897, - - /** - * Wrist Blood Pressure. - */ - BLOOD_PRESSURE_WRIST = 898, - - /** - * Human Interface Device (HID). - */ - HUMAN_INTERFACE_DEVICE_HID = 960, - - /** - * Keyboard. - */ - KEYBOARD = 961, - - /** - * Mouse. - */ - MOUSE = 962, - - /** - * Joystick. - */ - JOYSTICK = 963, - - /** - * Gamepad. - */ - GAMEPAD = 964, - - /** - * Digitizer Tablet. - */ - DIGITIZER_TABLET = 965, - - /** - * Card Reader. - */ - CARD_READER = 966, - - /** - * Digital Pen. - */ - DIGITAL_PEN = 967, - - /** - * Bar Code Scanner. - */ - BARCODE_SCANNER = 968, - - /** - * Generic Glucose Meter. - */ - GENERIC_GLUCOSE_METER = 1024, - - /** - * Generic Running/Walking Sensor. - */ - GENERIC_RUNNING_WALKING_SENSOR = 1088, - - /** - * In Shoe Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_IN_SHOE = 1089, - - /** - * On Shoe Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_ON_SHOE = 1090, - - /** - * On Hip Running/Walking Sensor. - */ - RUNNING_WALKING_SENSOR_ON_HIP = 1091, - - /** - * Generic Cycling. - */ - GENERIC_CYCLING = 1152, - - /** - * Cycling Computer. - */ - CYCLING_CYCLING_COMPUTER = 1153, - - /** - * Cycling Speed Sensor. - */ - CYCLING_SPEED_SENSOR = 1154, - - /** - * Cycling Cadence Sensor. - */ - CYCLING_CADENCE_SENSOR = 1155, - - /** - * Cycling Power Sensor. - */ - CYCLING_POWER_SENSOR = 1156, - - /** - * Cycling Speed and Cadence Sensor. - */ - CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, - - /** - * Generic Pulse Oximeter. - */ - PULSE_OXIMETER_GENERIC = 3136, - - /** - * Fingertip Pulse Oximeter. - */ - PULSE_OXIMETER_FINGERTIP = 3137, - - /** - * Wrist Worn Pulse Oximeter. - */ - PULSE_OXIMETER_WRIST_WORN = 3138, - - /** - * Generic Weight Scale. - */ - GENERIC_WEIGHT_SCALE = 3200, - - /** - * Generic Outdoor. - */ - OUTDOOR_GENERIC = 5184, - - /** - * Outdoor Location Display Device. - */ - OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, - - /** - * Outdoor Location and Navigation Display Device. - */ - OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, - - /** - * Outdoor Location Pod. - */ - OUTDOOR_LOCATION_POD = 5187, - - /** - * Outdoor Location and Navigation Pod. - */ - OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 - }; - - /** - * Construct a new instance of adv_data_appearance_t. - */ - adv_data_appearance_t(type value) : SafeEnum(value) - { - } -}; - /** * Build advertising data. * diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h new file mode 100644 index 0000000000..275ed9cfe8 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h @@ -0,0 +1,534 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAP_ADVERTISINGDATATYPES_H +#define BLE_GAP_ADVERTISINGDATATYPES_H + +#include "ble/SafeEnum.h" + +namespace ble { + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +/*! + * List of standard Advertising Data types. + * + * These AD types are used to describe the capabilities of the peripheral + * and are inserted inside the advertising or scan response payloads. + * + * @par Source + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18. + * @li @c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile. + */ +struct adv_data_type_t : SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { + /** + * Flags, refer to AdvertisingData::Flags_t. + */ + FLAGS = 0x01, + + /** + * Incomplete list of 16-bit Service IDs. + */ + INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, + + /** + * Complete list of 16-bit Service IDs. + */ + COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, + + /** + * Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, + + /** + * Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0). + */ + COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, + + /** + * Incomplete list of 128-bit Service IDs. + */ + INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, + + /** + * Complete list of 128-bit Service IDs. + */ + COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, + + /** + * Shortened Local Name. + */ + SHORTENED_LOCAL_NAME = 0x08, + + /** + * Complete Local Name. + */ + COMPLETE_LOCAL_NAME = 0x09, + + /** + * TX Power Level (in dBm). + */ + TX_POWER_LEVEL = 0x0A, + + /** + * Device ID. + */ + DEVICE_ID = 0x10, + + /** + * Slave Connection Interval Range. + */ + SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, + + /** + * List of 128-bit service UUIDs the device is looking for. + */ + LIST_16BIT_SOLICITATION_IDS = 0x14, + + /** + * List of 128-bit service UUIDs the device is looking for. + */ + LIST_128BIT_SOLICITATION_IDS = 0x15, + + /** + * Service Data. + */ + SERVICE_DATA = 0x16, + + /** + * Service Data. + */ + SERVICE_DATA_16BIT_ID = 0x16, + + /** + * Service Data. + */ + SERVICE_DATA_128BIT_ID = 0x21, + + /** + * Appearance, refer to AdvertisingData::Appearance_t. + */ + APPEARANCE = 0x19, + + /** + * Advertising Interval. + */ + ADVERTISING_INTERVAL = 0x1A, + + /** + * Manufacturer Specific Data. + */ + MANUFACTURER_SPECIFIC_DATA = 0xFF + }; + + /** + * Construct a new instance of adv_data_type_t. + */ + adv_data_type_t(type value) : SafeEnum(value) + { + } +}; + + +/** + * Set of advertising flags. + * + * @note LE_LIMITED_DISCOVERABLE and LE_GENERAL_DISCOVERABLE are mutually + * exclusive + * + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1. + */ +struct adv_data_flags_t { + enum { + LE_LIMITED_DISCOVERABLE = 0x01, /**< Discoverable for a limited period of time.*/ + LE_GENERAL_DISCOVERABLE = 0x02, /**< Discoverable at any moment. */ + BREDR_NOT_SUPPORTED = 0x04, /**< LE only and does not support Bluetooth Enhanced DataRate. */ + SIMULTANEOUS_LE_BREDR_C = 0x08, /**< Not relevant - dual mode only. */ + SIMULTANEOUS_LE_BREDR_H = 0x10 /**< Not relevant - dual mode only. */ + }; + + static const uint8_t default_flags = BREDR_NOT_SUPPORTED | LE_GENERAL_DISCOVERABLE; + + /** Create from raw value */ + adv_data_flags_t(uint8_t value = 0) : _value(value) + { + } + + adv_data_flags_t &setGeneralDiscoverable(bool enable = true) + { + _value &= ~0x03; + if (enable) { + _value |= LE_GENERAL_DISCOVERABLE; + } + return *this; + } + + adv_data_flags_t &setLimitedDiscoverable(bool enable = true) + { + _value &= ~0x03; + if (enable) { + _value |= LE_LIMITED_DISCOVERABLE; + } + return *this; + } + + adv_data_flags_t &setBredrNotSupported(bool enable = true) + { + _value &= ~BREDR_NOT_SUPPORTED; + if (enable) { + _value |= BREDR_NOT_SUPPORTED; + } + return *this; + } + + adv_data_flags_t &setSimultaneousLeBredrC(bool enable = true) + { + _value &= ~SIMULTANEOUS_LE_BREDR_C; + if (enable) { + _value |= SIMULTANEOUS_LE_BREDR_C; + } + return *this; + } + + adv_data_flags_t &setSimultaneousLeBredrH(bool enable = true) + { + _value &= ~SIMULTANEOUS_LE_BREDR_H; + if (enable) { + _value |= SIMULTANEOUS_LE_BREDR_H; + } + return *this; + } + + bool getGeneralDiscoverable() + { + return _value & LE_GENERAL_DISCOVERABLE; + } + + bool getlimitedDiscoverable() + { + return _value & LE_LIMITED_DISCOVERABLE; + } + + bool getBrEdrNotSupported() + { + return _value & BREDR_NOT_SUPPORTED; + } + + bool getSimultaneousLeBredrC() + { + return _value & SIMULTANEOUS_LE_BREDR_C; + } + + bool getSimultaneousLeBredrH() + { + return _value & SIMULTANEOUS_LE_BREDR_H; + } + + void clear() + { + _value = 0; + } + + uint8_t value() + { + return _value; + } + +private: + uint8_t _value; +}; + + +/** + * Enumeration of values for the adv_data_type_t::APPEARANCE. + * + * These values describe the physical shape or appearance of the device. + * + * @par Source + * + * @li @c Bluetooth Core Specification Supplement, Part A, Section 1.12. + * @li @c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2. + * @li @c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml. + */ +struct adv_data_appearance_t : SafeEnum { + /** struct scoped enum wrapped by the class */ + enum type { + /** + * Unknown or unspecified appearance type. + */ + UNKNOWN = 0, + + /** + * Generic Phone. + */ + GENERIC_PHONE = 64, + + /** + * Generic Computer. + */ + GENERIC_COMPUTER = 128, + + /** + * Generic Watch. + */ + GENERIC_WATCH = 192, + + /** + * Sports Watch. + */ + WATCH_SPORTS_WATCH = 193, + + /** + * Generic Clock. + */ + GENERIC_CLOCK = 256, + + /** + * Generic Display. + */ + GENERIC_DISPLAY = 320, + + /** + * Generic Remote Control. + */ + GENERIC_REMOTE_CONTROL = 384, + + /** + * Generic Eye Glasses. + */ + GENERIC_EYE_GLASSES = 448, + + /** + * Generic Tag. + */ + GENERIC_TAG = 512, + + /** + * Generic Keyring. + */ + GENERIC_KEYRING = 576, + + /** + * Generic Media Player. + */ + GENERIC_MEDIA_PLAYER = 640, + + /** + * Generic Bar Code Scanner. + */ + GENERIC_BARCODE_SCANNER = 704, + + /** + * Generic Thermometer. + */ + GENERIC_THERMOMETER = 768, + + /** + * Ear Thermometer. + */ + THERMOMETER_EAR = 769, + + /** + * Generic Heart Rate Sensor. + */ + GENERIC_HEART_RATE_SENSOR = 832, + + /** + * Belt Heart Rate Sensor. + */ + HEART_RATE_SENSOR_HEART_RATE_BELT = 833, + + /** + * Generic Blood Pressure. + */ + GENERIC_BLOOD_PRESSURE = 896, + + /** + * Arm Blood Pressure. + */ + BLOOD_PRESSURE_ARM = 897, + + /** + * Wrist Blood Pressure. + */ + BLOOD_PRESSURE_WRIST = 898, + + /** + * Human Interface Device (HID). + */ + HUMAN_INTERFACE_DEVICE_HID = 960, + + /** + * Keyboard. + */ + KEYBOARD = 961, + + /** + * Mouse. + */ + MOUSE = 962, + + /** + * Joystick. + */ + JOYSTICK = 963, + + /** + * Gamepad. + */ + GAMEPAD = 964, + + /** + * Digitizer Tablet. + */ + DIGITIZER_TABLET = 965, + + /** + * Card Reader. + */ + CARD_READER = 966, + + /** + * Digital Pen. + */ + DIGITAL_PEN = 967, + + /** + * Bar Code Scanner. + */ + BARCODE_SCANNER = 968, + + /** + * Generic Glucose Meter. + */ + GENERIC_GLUCOSE_METER = 1024, + + /** + * Generic Running/Walking Sensor. + */ + GENERIC_RUNNING_WALKING_SENSOR = 1088, + + /** + * In Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_IN_SHOE = 1089, + + /** + * On Shoe Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_SHOE = 1090, + + /** + * On Hip Running/Walking Sensor. + */ + RUNNING_WALKING_SENSOR_ON_HIP = 1091, + + /** + * Generic Cycling. + */ + GENERIC_CYCLING = 1152, + + /** + * Cycling Computer. + */ + CYCLING_CYCLING_COMPUTER = 1153, + + /** + * Cycling Speed Sensor. + */ + CYCLING_SPEED_SENSOR = 1154, + + /** + * Cycling Cadence Sensor. + */ + CYCLING_CADENCE_SENSOR = 1155, + + /** + * Cycling Power Sensor. + */ + CYCLING_POWER_SENSOR = 1156, + + /** + * Cycling Speed and Cadence Sensor. + */ + CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, + + /** + * Generic Pulse Oximeter. + */ + PULSE_OXIMETER_GENERIC = 3136, + + /** + * Fingertip Pulse Oximeter. + */ + PULSE_OXIMETER_FINGERTIP = 3137, + + /** + * Wrist Worn Pulse Oximeter. + */ + PULSE_OXIMETER_WRIST_WORN = 3138, + + /** + * Generic Weight Scale. + */ + GENERIC_WEIGHT_SCALE = 3200, + + /** + * Generic Outdoor. + */ + OUTDOOR_GENERIC = 5184, + + /** + * Outdoor Location Display Device. + */ + OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, + + /** + * Outdoor Location and Navigation Display Device. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, + + /** + * Outdoor Location Pod. + */ + OUTDOOR_LOCATION_POD = 5187, + + /** + * Outdoor Location and Navigation Pod. + */ + OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 + }; + + /** + * Construct a new instance of adv_data_appearance_t. + */ + adv_data_appearance_t(type value) : SafeEnum(value) + { + } +}; + +} // namespace ble + +#endif //BLE_GAP_ADVERTISINGDATATYPES_H From d4a66ae034f9fb8103f4347f3616ca597fd7ee33 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 15:41:02 +0000 Subject: [PATCH 310/361] BLE: Add an AdvertisingDataParser --- .../ble/gap/AdvertisingDataParser.h | 122 ++++++++++++++++++ .../ble/gap/AdvertisingDataTypes.h | 5 + 2 files changed, 127 insertions(+) create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingDataParser.h diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataParser.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataParser.h new file mode 100644 index 0000000000..e41610b9fe --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataParser.h @@ -0,0 +1,122 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAP_ADVERTISINGDATAPARSER_H +#define BLE_GAP_ADVERTISINGDATAPARSER_H + +#include +#include "ble/gap/AdvertisingDataTypes.h" +#include "platform/Span.h" + +namespace ble { + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +/** + * Parse and iterate over advertising data + */ +class AdvertisingDataParser { + + enum { + DATA_SIZE_INDEX = 0, + TYPE_INDEX = 1, + VALUE_INDEX = 2, + TYPE_SIZE = 1, + DATA_SIZE_SIZE = 1 + }; + +public: + /** + * Representation of an Advertising Data element. + */ + struct element_t { + adv_data_type_t type; + mbed::Span value; + }; + + /** + * Build a parser from an array of bytes. + * @param data The data to parse. + */ + AdvertisingDataParser(mbed::Span data) : + data(data), + position(0) + { + } + + /** + * Return if there is advertising data element left to parse. + */ + bool hasNext() const + { + if (position >= data.size()) { + return false; + } + + if (position + current_length() >= data.size()) { + return false; + } + + return true; + } + + /** + * Return the next advertising data element. + * + * @note Calling this function if there is no next element is undefined + * behavior. + */ + element_t next() + { + element_t element = { + (ble::adv_data_type_t::type) data[TYPE_INDEX], + data.subspan(position + VALUE_INDEX, current_length() - (TYPE_SIZE)) + }; + + position += (DATA_SIZE_SIZE + current_length()); + return element; + } + + /** + * Reset the parser. + */ + void reset() + { + position = 0; + } + +private: + uint8_t current_length() const { + return data[position + DATA_SIZE_INDEX]; + } + + mbed::Span data; + size_t position; +}; + +/** + * @} + * @} + */ + +} // namespace ble + +#endif //BLE_GAP_ADVERTISINGDATAPARSER_H diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h index 275ed9cfe8..d6a123d793 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataTypes.h @@ -529,6 +529,11 @@ struct adv_data_appearance_t : SafeEnum { } }; +/** + * @} + * @} + */ + } // namespace ble #endif //BLE_GAP_ADVERTISINGDATATYPES_H From 8cbc53617f78d08e08dbcfad3d8e6e4fe044b62b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Sun, 25 Nov 2018 17:29:48 +0000 Subject: [PATCH 311/361] BLE: Add a simple builder for AdvertisingData. --- .../ble/gap/AdvertisingDataSimpleBuilder.h | 315 ++++++++++++++++++ features/FEATURE_BLE/ble/gap/Gap.h | 1 + 2 files changed, 316 insertions(+) create mode 100644 features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h new file mode 100644 index 0000000000..a720437178 --- /dev/null +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h @@ -0,0 +1,315 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BLE_GAP_SIMPLEADVERTISINGDATABUILDER_H +#define BLE_GAP_SIMPLEADVERTISINGDATABUILDER_H + +#include "ble/gap/AdvertisingDataBuilder.h" + +namespace ble { + +/** + * @addtogroup ble + * @{ + * @addtogroup gap + * @{ + */ + +/** + * Build advertising data. + * + * It is a simplified version of AdvertisingDataBuilder that can generate + * advertising data "inline". + * + * It differs on different points with AdvertisingDataBuilder: + * - The buffer used to build the advertising data is embedded in the object. + * - If insertion fail, an assertion is raised. In non debug mode, if an + * insertion fail, the buffer is not modified. + * - The API is fluent. + * - It hides advanced functions. + * + * @code + void setupAdvertisingData(ble::Gap& gap) + { + using namespace ble; + gap.setAdvertisingPayload( + LEGACY_ADVERTISING_HANDLE, + AdvertisingDataSimpleBuilder() + .setFlags() + .setName("My device", true) + .setAppearance(adv_data_appearance_t::GENERIC_HEART_RATE_SENSOR) + .setLocalService(ATT_UUID_HEART_RATE_SERVICE) + .getAdvertisingData() + ); + } + * @endcode + */ +template +class AdvertisingDataSimpleBuilder { +public: + /** + * Construct a AdvertisingDataSimpleBuilder + */ + AdvertisingDataSimpleBuilder() : _builder(_buffer) + { + } + + /** + * Add device appearance in the advertising payload. + * + * @param[in] appearance The appearance to advertise. + * + * @return A reference to this object. + * + * @note If the field is already present in the payload, it is replaced. + */ + AdvertisingDataSimpleBuilder &setAppearance(adv_data_appearance_t appearance) + { + MBED_ASSERT(_builder.setAppearance(appearance) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add BLE flags in the advertising payload. + * + * @param[in] flags Bitfield describing the capability of the device. See + * allowed flags in Flags_t. + * + * @return A reference to this object. + * + * @note If the field is already present in the payload, it is replaced. + */ + AdvertisingDataSimpleBuilder &setFlags( + adv_data_flags_t flags = adv_data_flags_t::default_flags + ) + { + MBED_ASSERT(_builder.setFlags(flags) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add the advertising TX in the advertising payload. + * + * @param[in] txPower Transmission power level in dB. + * + * @return A reference to this object. + * + * @note If the field is already present in the payload, it is replaced. + */ + AdvertisingDataSimpleBuilder &setTxPowerAdvertised(advertising_power_t txPower) + { + MBED_ASSERT(_builder.setTxPowerAdvertised(txPower) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add device name to the advertising payload. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] name Null terminated string containing the name. + * @param[in] complete Complete local name if true, otherwise + * + * @return A reference to this object. + * + * @note If the field is already present in the payload, it is replaced. + */ + AdvertisingDataSimpleBuilder &setName(const char *name, bool complete = true) + { + MBED_ASSERT(_builder.setName(name, complete) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add manufacturer specific data to the advertising payload. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data New data to be added. + * + * @return a reference to this object. + */ + AdvertisingDataSimpleBuilder &setManufacturerSpecificData(mbed::Span data) + { + MBED_ASSERT(_builder.setManufacturerSpecificData(data) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add advertising interval to the payload. This field can only carry 2 bytes. + * + * @param interval Interval to advertise. Cannot be larger than 0xFFFF. + * + * @return a reference to this object. + */ + AdvertisingDataSimpleBuilder &setAdvertisingInterval(adv_interval_t interval) + { + MBED_ASSERT(_builder.setAdvertisingInterval(interval) == BLE_ERROR_NONE); + } + + /** + * Add connection interval preferences to the payload + * + * @param min Minimum connection interval to advertise. + * @param max Maximum connection interval to advertise. + * + * @return a reference to this object. + */ + AdvertisingDataSimpleBuilder &setConnectionIntervalPreference( + conn_interval_t min, + conn_interval_t max + ) + { + MBED_ASSERT(_builder.setConnectionIntervalPreference(min, max) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add service data data to the advertising payload. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] service UUID of the service. + * @param[in] data New data to be added. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder &setServiceData(UUID service, mbed::Span data) + { + MBED_ASSERT(_builder.setServiceData(service, data) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add local service ID to the advertising payload. If they data can't fit + * no modification will take place. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data New data to be added. + * @param[in] complete True if this is a complete list. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder &setLocalService( + const UUID& data, + bool complete = true + ) + { + MBED_ASSERT( + _builder.setLocalServiceList( + mbed::make_Span(&data, 1), complete + ) == BLE_ERROR_NONE + ); + return *this; + } + + + /** + * Add local service IDs to the advertising payload. If they data can't fit + * no modification will take place. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data New data to be added. + * @param[in] complete True if this is a complete list. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder &setLocalServiceList( + mbed::Span data, + bool complete = true + ) + { + MBED_ASSERT(_builder.setLocalServiceList(data, complete) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add a UUID of a solicited service. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data List of 128 or 16 bit service UUIDs. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder &setRequestedService(const UUID& data) + { + MBED_ASSERT( + _builder.setRequestedServiceList(mbed::make_Span(&data, 1)) == BLE_ERROR_NONE + ); + return *this; + } + + /** + * Add a list of UUIDs of solicited services. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] data List of 128 or 16 bit service UUIDs. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder &setRequestedServiceList(mbed::Span data) + { + MBED_ASSERT(_builder.setRequestedServiceList(data) == BLE_ERROR_NONE); + return *this; + } + + /** + * Add a new field into the payload. The operation fail if type is already present. + * + * @note Data size for individual types cannot exceed 255 bytes. + * + * @param[in] advDataType The type of the field to add. + * @param[in] fieldData Span of data to add. + * + * @return A reference to this object. + */ + AdvertisingDataSimpleBuilder& addData( + adv_data_type_t advDataType, + mbed::Span fieldData + ) + { + MBED_ASSERT(_builder.addData(advDataType, fieldData) == BLE_ERROR_NONE); + return *this; + } + + /** + * Get the subspan of the buffer containing valid data. + * + * @return A Span containing the payload. + */ + mbed::Span getAdvertisingData() const + { + return _builder.getAdvertisingData(); + } + +private: + uint8_t _buffer[DataSize]; + AdvertisingDataBuilder _builder; +}; + +/** + * @} + * @} + */ + +} // namespace ble + + +#endif //BLE_GAP_SIMPLEADVERTISINGDATABUILDER_H diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index b2d0023aee..7c79e62493 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -21,6 +21,7 @@ #include "ble/BLETypes.h" #include "ble/BLEProtocol.h" #include "ble/gap/AdvertisingDataBuilder.h" +#include "ble/gap/AdvertisingDataSimpleBuilder.h" #include "ble/gap/ConnectionParameters.h" #include "ble/gap/ScanParameters.h" #include "ble/gap/AdvertisingParameters.h" From 208b1bd3e967435abf695b4672a6e92746f910c8 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:10:39 +0000 Subject: [PATCH 312/361] fix size calculation for UUID data payload --- .../source/gap/AdvertisingDataBuilder.cpp | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp index 1f72f0c6d0..1e0d465a8b 100644 --- a/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp +++ b/features/FEATURE_BLE/source/gap/AdvertisingDataBuilder.cpp @@ -477,25 +477,28 @@ ble_error_t AdvertisingDataBuilder::setUUIDData( for (size_t i = 0, end = data.size(); i < end; ++i) { if (data[i].shortOrLong() == UUID::UUID_TYPE_SHORT) { - size_short++; + size_short += data[i].getLen(); } else { - size_long++; + size_long += data[i].getLen(); } } - if ((size_long * 8 > MAX_DATA_FIELD_SIZE) || (size_short * 2 > MAX_DATA_FIELD_SIZE)) { + if ((size_long > MAX_DATA_FIELD_SIZE) || (size_short > MAX_DATA_FIELD_SIZE)) { return BLE_ERROR_INVALID_PARAM; } - /* calculate total size including headers for types */ - size_t total_size = size_long + (!!size_long) * 2 + - size_short + (!!size_short) * 2; + /* UUID data consists of a type byte, size byte and the list UUIDs itself, we include + * the header (type and size bytes) size only if the size of the UUIDs is non-zero + * (!!non_zero_variable) == 1 */ + size_t long_uuid_data_size = (!!size_long) * FIELD_HEADER_SIZE + size_long; + size_t short_uuid_data_size = (!!size_short) * FIELD_HEADER_SIZE + size_short; + size_t new_size = long_uuid_data_size + short_uuid_data_size; /* count all the bytes of existing data */ size_t old_size = getFieldSize(shortType) + getFieldSize(longType); /* if we can't fit the new data do not proceed */ - if (total_size > data.size() - (_payload_length - old_size)) { + if (new_size > data.size() - (_payload_length - old_size)) { return BLE_ERROR_BUFFER_OVERFLOW; } @@ -529,4 +532,4 @@ ble_error_t AdvertisingDataBuilder::setUUIDData( return status; } -} // end of namespace ble \ No newline at end of file +} // end of namespace ble From 528deb168fa79a7b23e7456955a8003064867b8c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:16:23 +0000 Subject: [PATCH 313/361] fix wrong variable being swapped --- features/FEATURE_BLE/source/gap/ConnectionParameters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp index e999e78778..3ed5b646ef 100644 --- a/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp +++ b/features/FEATURE_BLE/source/gap/ConnectionParameters.cpp @@ -107,7 +107,7 @@ void ConnectionParameters::swapCodedAnd2M() uint16_t scanWindow = _scanWindow[LE_2M_INDEX]; uint16_t minConnectionInterval = _minConnectionInterval[LE_2M_INDEX]; uint16_t maxConnectionInterval = _maxConnectionInterval[LE_2M_INDEX]; - uint16_t slaveLatency = _maxConnectionInterval[LE_2M_INDEX]; + uint16_t slaveLatency = _slaveLatency[LE_2M_INDEX]; uint16_t connectionSupervisionTimeout = _connectionSupervisionTimeout[LE_2M_INDEX]; uint16_t minEventLength = _minEventLength[LE_2M_INDEX]; uint16_t maxEventLength = _maxEventLength[LE_2M_INDEX]; From e0e186c8318a330126bf5492e385eeefbff8cc44 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:21:37 +0000 Subject: [PATCH 314/361] replace consts with a private enum --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index c0038c5f44..018fb52723 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -119,10 +119,12 @@ namespace ble { * @see ble::Gap::connect() */ class ConnectionParameters { - static const uint8_t MAX_PARAM_PHYS = 3; - static const uint8_t LE_1M_INDEX = 0; - static const uint8_t LE_2M_INDEX = 1; - static const uint8_t LE_CODED_INDEX = 2; + enum { + LE_1M_INDEX = 0, + LE_2M_INDEX = 1, + LE_CODED_INDEX = 2, + MAX_PARAM_PHYS = 3 + }; public: /** From a03aaa23421c1d1328dddf372ddf7e5b1252c689 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:26:13 +0000 Subject: [PATCH 315/361] simplify and explain swapping --- .../FEATURE_BLE/ble/gap/ConnectionParameters.h | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 018fb52723..b023a2e5d3 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -382,25 +382,19 @@ private: { uint8_t index = phyToIndex(phy); - bool was_swapped = false; - bool is_swapped = false; - - if (isSwapped()) { - was_swapped = true; - } + bool was_swapped = isSwapped(); _enabledPhy[index] = enable; - if (isSwapped()) { - is_swapped = true; - } + bool is_swapped = isSwapped(); if (was_swapped != is_swapped) { swapCodedAnd2M(); } - if (is_swapped && phy == phy_t::LE_CODED) { - index -= 1; + if (is_swapped && index == LE_CODED_INDEX) { + /* to keep the data contiguous coded params are in place of the missing 2M params */ + index = LE_2M_INDEX; } return index; From f3a64feaf15e31d5e7bb508300672368884336cc Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:26:26 +0000 Subject: [PATCH 316/361] replace magic numbers --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index b023a2e5d3..95da1bb656 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -405,13 +405,13 @@ private: uint8_t index; switch (phy.value()) { case phy_t::LE_1M: - index = 0; + index = LE_1M_INDEX; break; case phy_t::LE_2M: - index = 1; + index = LE_2M_INDEX; break; case phy_t::LE_CODED: - index = 2; + index = LE_CODED_INDEX; break; default: index = MAX_PARAM_PHYS; From bee115c39ed709b209fe988dbd6dd180bde6e029 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:31:03 +0000 Subject: [PATCH 317/361] replace magic numbers --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 95da1bb656..83b8b999ce 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -360,11 +360,11 @@ private: uint8_t getFirstEnabledIndex() const { if (_enabledPhy[LE_1M_INDEX]) { - return 0; + return LE_1M_INDEX; } else if (_enabledPhy[LE_2M_INDEX]) { - return 1; + return LE_2M_INDEX; } else if (_enabledPhy[LE_CODED_INDEX]) { - return 2; + return LE_CODED_INDEX; } /* this should never happen, it means you were trying to start a connection with a blank set * of paramters - you need to enabled at least one phy */ From d3d93e1ef9984a36ef9b496b23d68c9388c579f4 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 11:50:45 +0000 Subject: [PATCH 318/361] BLE: Improve ble::Gap documentation. --- features/FEATURE_BLE/ble/gap/Gap.h | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 7c79e62493..d4bb83f359 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -71,7 +71,7 @@ namespace ble { * @par Advertising * * Advertising consists of broadcasting at a regular interval a small amount of - * data containing valuable informations about the device. These packets may be + * data containing valuable information about the device. These packets may be * scanned by peer devices listening on BLE advertising channels. * * Scanners may also request additional information from a device advertising by @@ -84,16 +84,22 @@ namespace ble { * updated the data will take effect from the next advertising event. * * To create a valid advertising payload and scan response you may use - * AdvertisingDataBuilder(). You must first allocate memory and crate an mbed::Span and + * AdvertisingDataBuilder. You must first allocate memory and create an mbed::Span and * pass that into the AdvertisingDataBuilder which will only be able to add as much * data as fits in the provided buffer. The builder will accept any size of the buffer * but for the created data to be usable it must be smaller than the maximum data * length returned from getMaxAdvertisingDataLength(). * - * @note The maximum size of data depends on the controller and its support for - * extended advertising however even if the controller supports larger data lengths if - * you wish to be compatible with older devices you may wish to use legacy - * advertising and should not use payloads larger than LEGACY_ADVERTISING_MAX_SIZE. + * Another option is to use AdvertisingDataSimpleBuilder that allocates memory + * on the stack and offers a fluent interface at the expense of a reduced set of + * APIs and error management options. + * + * @note Prior to Bluetooth 5; advertising and scanning payload size were limited + * to LEGACY_ADVERTISING_MAX_SIZE. It changed with Bluetooth 5 and now the maximum + * size of data that can be advertised depends on the controller. If you wish + * to be compatible with older devices you may wish to advertise with the + * LEGACY_ADVERTISING_HANDLE and uses payloads no larger than LEGACY_ADVERTISING_MAX_SIZE + * with that advertising set. * * @par Extended advertising * @@ -150,8 +156,10 @@ namespace ble { * they are not actively advertising right now so it's important to destroy the set * when you're done with it (or reuse it in the next advertisement). * - * Periodic advertising and extended advertising share the same set. For periodic - * advertising to start the extended advertising of the same set must also be active. + * Periodic advertising and extended advertising share the same set but not the same + * data. Periodic advertising synchronization information are carried out by + * extended advertising therefore to let other devices be aware that your device + * exposes periodic advertising you should start extended advertising of the set. * Subsequently you may disable extended advertising and the periodic advertising * will continue. If you start periodic advertising while extended advertising is * inactive, periodic advertising will not start until you start extended advertising @@ -1077,8 +1085,8 @@ public: ); /** - * Default peripheral privacy configuration. - */ + * Default peripheral privacy configuration. + */ static const peripheral_privacy_configuration_t default_peripheral_privacy_configuration; From c9e8501b2249eafac1402d2b37941d464a284264 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 11:34:08 +0000 Subject: [PATCH 319/361] make PHY case consistent --- .../ble/gap/ConnectionParameters.h | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 83b8b999ce..bd4f897e83 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -63,13 +63,13 @@ namespace ble { * These parameters can be set at construction time or by calling the function * setConnectionParameters(). * - * @par Phy + * @par PHY * * Bluetooth 5 have introduced the support of different physical layer to either - * increase the range or the throughput. Multiple phy can be configured + * increase the range or the throughput. Multiple PHY can be configured * independently for scanning and connecting. * - * Legacy connection happens on the 1M phy (phy_t::LE_1M). It is the only phy + * Legacy connection happens on the 1M PHY (phy_t::LE_1M). It is the only PHY * that can be configured on legacy systems. * * The constructor, setScanParameters() and setConnectionParameters() accept @@ -130,7 +130,7 @@ public: /** * Create a ConnectionParameters object. * - * @param phy The phy being configured. + * @param phy The PHY being configured. * @param scanInterval Interval between two scans. * @param scanWindow Scan duration during a scan interval. * @param minConnectionInterval Minimum value of the connection interval. @@ -156,13 +156,13 @@ public: /* setters */ /** - * Set the scan parameters for a given phy. + * Set the scan parameters for a given PHY. * * @param phy PHY being configured. * @param scanInterval Interval between two scans. * @param scanWindow Scan duration within a scan interval. * - * @note It is useless to configure the 2M phy as it is not used during + * @note It is useless to configure the 2M PHY as it is not used during * scanning. * * @return A reference to this. @@ -240,9 +240,9 @@ public: } /** - * Disable an individual phy. + * Disable an individual PHY. * - * @param phy The phy to disable. + * @param phy The PHY to disable. * * @return A reference to this. */ @@ -253,9 +253,9 @@ public: } /** - * Enable an individual phy. + * Enable an individual PHY. * - * @param phy The phy to enable. + * @param phy The PHY to enable. * * @return A reference to this. */ @@ -288,8 +288,8 @@ public: } /** - * Return the number of phy enabled. - * @return The number of phy enabled. + * Return the number of PHY enabled. + * @return The number of PHY enabled. */ uint8_t getNumberOfEnabledPhys() const { @@ -367,14 +367,14 @@ private: return LE_CODED_INDEX; } /* this should never happen, it means you were trying to start a connection with a blank set - * of paramters - you need to enabled at least one phy */ + * of paramters - you need to enabled at least one PHY */ MBED_ASSERT("Trying to use connection parameters without any PHY defined."); return 0; } /** Handle toggling PHYs on and off and return the correct index to use to set the configuration elements. * - * @param phy Which Phy is being toggle. + * @param phy Which PHY is being toggle. * @param enable On or Off. * @return The index to the array of settings. */ From 190b9bc125994a675fae668d168fe2b2c7e3ce1b Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 14:11:29 +0000 Subject: [PATCH 320/361] BLE: Fix address type in ::ble::Gap::connect --- features/FEATURE_BLE/ble/BLETypes.h | 8 -------- features/FEATURE_BLE/ble/gap/Gap.h | 2 +- features/FEATURE_BLE/ble/generic/GenericGap.h | 2 +- features/FEATURE_BLE/source/gap/Gap.cpp | 2 +- .../FEATURE_BLE/source/generic/GenericGap.cpp | 17 +++++++++++++++-- 5 files changed, 18 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/ble/BLETypes.h b/features/FEATURE_BLE/ble/BLETypes.h index 55cead261d..652e46a4ef 100644 --- a/features/FEATURE_BLE/ble/BLETypes.h +++ b/features/FEATURE_BLE/ble/BLETypes.h @@ -605,14 +605,6 @@ struct peer_address_type_t :SafeEnum { ANONYMOUS = 0xFF }; - ble::target_peer_address_type_t getTargetAddressType() const { - if (value() == RANDOM || value() == RANDOM_STATIC_IDENTITY) { - return ble::target_peer_address_type_t::RANDOM; - } - - return ble::target_peer_address_type_t::PUBLIC; - } - /** * Construct a new instance of peer_address_type_t. */ diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index d4bb83f359..7c1fc6fe38 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -862,7 +862,7 @@ public: * ends. */ virtual ble_error_t connect( - target_peer_address_type_t peerAddressType, + peer_address_type_t peerAddressType, const address_t &peerAddress, const ConnectionParameters &connectionParams ); diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 0a8143a541..5cfad352ee 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -294,7 +294,7 @@ public: * @see Gap::connect */ virtual ble_error_t connect( - target_peer_address_type_t peerAddressType, + peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ConnectionParameters &connectionParams ); diff --git a/features/FEATURE_BLE/source/gap/Gap.cpp b/features/FEATURE_BLE/source/gap/Gap.cpp index 8b62805df3..4cb4c6a50e 100644 --- a/features/FEATURE_BLE/source/gap/Gap.cpp +++ b/features/FEATURE_BLE/source/gap/Gap.cpp @@ -228,7 +228,7 @@ uint8_t Gap::getMaxPeriodicAdvertiserListSize() } ble_error_t Gap::connect( - target_peer_address_type_t peerAddressType, + peer_address_type_t peerAddressType, const address_t &peerAddress, const ConnectionParameters &connectionParams ) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3c59c4f726..adbffd649e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -638,7 +638,7 @@ ble_error_t GenericGap::connect( ble_error_t GenericGap::connect( - target_peer_address_type_t peerAddressType, + peer_address_type_t peerAddressType, const ble::address_t &peerAddress, const ConnectionParameters &connectionParams ) @@ -647,6 +647,10 @@ ble_error_t GenericGap::connect( return BLE_ERROR_INVALID_PARAM; } + if (peerAddressType == peer_address_type_t::ANONYMOUS) { + return BLE_ERROR_INVALID_PARAM; + } + if (!is_extended_advertising_available()) { phy_set_t set(connectionParams.getPhySet()); if (set.count() != 1 || set.get_1m() == false) { @@ -654,10 +658,19 @@ ble_error_t GenericGap::connect( } } + // reduce the address type to public or random + peer_address_type_t adjusted_address_type(peer_address_type_t::PUBLIC); + + if (peerAddressType == peer_address_type_t::RANDOM || + peerAddressType == peer_address_type_t::RANDOM_STATIC_IDENTITY + ) { + adjusted_address_type = peer_address_type_t::RANDOM; + } + return _pal_gap.extended_create_connection( connectionParams.getFilterPolicy(), connectionParams.getOwnAddressType(), - (peer_address_type_t::type) peerAddressType.value(), + adjusted_address_type, peerAddress, (phy_set_t) connectionParams.getPhySet(), connectionParams.getScanIntervalArray(), From a915748cbeec1b95769c4a1319c655521a821d2c Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 14:12:10 +0000 Subject: [PATCH 321/361] BLE: Fallback to legacy connect when required. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index adbffd649e..db1ee4c0e1 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -656,6 +656,21 @@ ble_error_t GenericGap::connect( if (set.count() != 1 || set.get_1m() == false) { return BLE_ERROR_INVALID_PARAM; } + + return _pal_gap.create_connection( + connectionParams.getScanIntervalArray()[0], + connectionParams.getScanWindowArray()[0], + connectionParams.getFilterPolicy(), + (pal::connection_peer_address_type_t::type) peerAddressType.value(), + peerAddress, + connectionParams.getOwnAddressType(), + connectionParams.getMinConnectionIntervalArray()[0], + connectionParams.getMaxConnectionIntervalArray()[0], + connectionParams.getSlaveLatencyArray()[0], + connectionParams.getConnectionSupervisionTimeoutArray()[0], + connectionParams.getMinEventLengthArray()[0], + connectionParams.getMaxConnectionIntervalArray()[0] + ); } // reduce the address type to public or random From 3aa91ecbbabd35bee228262c01ca866b18a429f6 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:22:50 +0000 Subject: [PATCH 322/361] BLE: return phy_set_t in ConnectionParameters::getPhySet --- features/FEATURE_BLE/ble/gap/ConnectionParameters.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index bd4f897e83..5aecd15527 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -302,14 +302,14 @@ public: #if !defined(DOXYGEN_ONLY) - uint8_t getPhySet() const + phy_set_t getPhySet() const { phy_set_t set( _enabledPhy[LE_1M_INDEX], _enabledPhy[LE_2M_INDEX], _enabledPhy[LE_CODED_INDEX] ); - return set.value(); + return set; } /* these return pointers to arrays of settings valid only across the number of active PHYs */ From 93b6ecfa7e4ff466c12b5a1cfa45b2b94afd2981 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:23:24 +0000 Subject: [PATCH 323/361] BLE: initialize properly deprecated and non deprecated flags. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index db1ee4c0e1..b542c48d27 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -438,6 +438,8 @@ GenericGap::GenericGap( _advertising_timeout(), _scan_timeout(), _connection_event_handler(NULL), + _deprecated_scan_api_used(false), + _non_deprecated_scan_api_used(false), _user_manage_connection_parameter_requests(false) { _pal_gap.initialize(); From d1b5c8cbb5068724b5ef12b97a9c0067028a60a3 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:23:53 +0000 Subject: [PATCH 324/361] BLE: Mark LEGACY_ADVERTISING_HANDLE as active in initialization. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index b542c48d27..f6ff52ce3a 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -458,6 +458,7 @@ GenericGap::GenericGap( LEGACY_ADVERTISING_HANDLE, AdvertisingParameters() ); + _active_sets.set(LEGACY_ADVERTISING_HANDLE); } } From 89355b9fb0b1dcbaf80ab41b5aedb6134bca2cf1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:24:42 +0000 Subject: [PATCH 325/361] BLE: Check supervision timeout value in connect. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index f6ff52ce3a..23567d78c7 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -654,6 +654,17 @@ ble_error_t GenericGap::connect( return BLE_ERROR_INVALID_PARAM; } + for (size_t i = 0; i < connectionParams.getPhySet().count(); ++i) { + if (supervision_timeout_t(connectionParams.getConnectionSupervisionTimeoutArray()[i]) <= + minSupervisionTimeout( + conn_interval_t(connectionParams.getMaxConnectionIntervalArray()[i]), + slave_latency_t(connectionParams.getSlaveLatencyArray()[i]) + ) + ) { + return BLE_ERROR_INVALID_PARAM; + } + } + if (!is_extended_advertising_available()) { phy_set_t set(connectionParams.getPhySet()); if (set.count() != 1 || set.get_1m() == false) { From 2d63714f2e7d0f975b628c131856fb965e9dd578 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:25:46 +0000 Subject: [PATCH 326/361] BLE: Implement connection parameter management in GAP. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 43 +++++++++++++------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 23567d78c7..39980f7b86 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1611,23 +1611,40 @@ void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEv void GenericGap::on_connection_parameter_request(const pal::GapRemoteConnectionParameterRequestEvent &e) { - // intern behavior, accept all new parameter requests - // TODO: expose an API so user code can accept or reject such request - _pal_gap.accept_connection_parameter_request( - e.connection_handle, - e.min_connection_interval, - e.max_connection_interval, - e.connection_latency, - e.supervision_timeout, - /* minimum_connection_event_length */ 0, - /* maximum_connection_event_length */ 0 - ); + if (_user_manage_connection_parameter_requests) { + _eventHandler->onUpdateConnectionParametersRequest( + UpdateConnectionParametersRequestEvent( + e.connection_handle, + conn_interval_t(e.min_connection_interval), + conn_interval_t(e.max_connection_interval), + e.connection_latency, + supervision_timeout_t(e.supervision_timeout) + ) + ); + } else { + _pal_gap.accept_connection_parameter_request( + e.connection_handle, + e.min_connection_interval, + e.max_connection_interval, + e.connection_latency, + e.supervision_timeout, + /* minimum_connection_event_length */ 0, + /* maximum_connection_event_length */ 0 + ); + } } void GenericGap::on_connection_update(const pal::GapConnectionUpdateEvent &e) { - // TODO: add feature in interface to notify the user that the connection - // has been updated. + _eventHandler->onConnectionParametersUpdateComplete( + ConnectionParametersUpdateCompleteEvent( + e.status == pal::hci_error_code_t::SUCCESS ? BLE_ERROR_NONE : BLE_ERROR_UNSPECIFIED, + e.connection_handle, + conn_interval_t(e.connection_interval), + e.connection_latency, + supervision_timeout_t(e.supervision_timeout) + ) + ); } void GenericGap::on_unexpected_error(const pal::GapUnexpectedErrorEvent &e) From f71e08ccf1403ca0613b7da13cb3fc3f5926becf Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 15:26:24 +0000 Subject: [PATCH 327/361] BLE: tag API uses in GenericGap. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 81 +++++++++++++++++-- 1 file changed, 76 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 39980f7b86..7c845b9d13 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -466,9 +466,7 @@ GenericGap::~GenericGap() { } -bool GenericGap::isFeatureSupported( - controller_supported_features_t feature -) +bool GenericGap::isFeatureSupported(controller_supported_features_t feature) { return _pal_gap.is_feature_supported(feature); } @@ -548,6 +546,7 @@ uint16_t GenericGap::getMaxAdvertisingInterval() const ble_error_t GenericGap::stopAdvertising() { + useVersionOneAPI(); ble_error_t err = _pal_gap.advertising_enable(false); if (err) { return err; @@ -588,6 +587,7 @@ ble_error_t GenericGap::connect( const GapScanningParams *scanParams ) { + useVersionOneAPI(); if (connectionParams == NULL) { connectionParams = &default_connection_params; } @@ -631,6 +631,7 @@ ble_error_t GenericGap::connect( const GapScanningParams *scanParams ) { + useVersionOneAPI(); return connect( peerAddr, to_peer_address_type(peerAddrType), @@ -646,6 +647,8 @@ ble_error_t GenericGap::connect( const ConnectionParameters &connectionParams ) { + useVersionTwoAPI(); + if (!connectionParams.getNumberOfEnabledPhys()) { return BLE_ERROR_INVALID_PARAM; } @@ -729,6 +732,8 @@ ble_error_t GenericGap::updateConnectionParameters( conn_event_length_t maxConnectionEventLength ) { + useVersionTwoAPI(); + if (supervisionTimeout <= minSupervisionTimeout(maxConnectionInterval, slaveLatency)) { return BLE_ERROR_INVALID_PARAM; } @@ -754,6 +759,8 @@ ble_error_t GenericGap::acceptConnectionParametersUpdate( conn_event_length_t maxConnectionEventLength ) { + useVersionTwoAPI(); + if (supervisionTimeout <= minSupervisionTimeout(maxConnectionInterval, slaveLatency)) { return BLE_ERROR_INVALID_PARAM; } @@ -773,6 +780,8 @@ ble_error_t GenericGap::rejectConnectionParametersUpdate( connection_handle_t connectionHandle ) { + useVersionTwoAPI(); + return _pal_gap.reject_connection_parameter_request( connectionHandle, pal::hci_error_code_t::UNACCEPTABLE_CONNECTION_PARAMETERS @@ -781,6 +790,7 @@ ble_error_t GenericGap::rejectConnectionParametersUpdate( ble_error_t GenericGap::cancelConnect() { + useVersionTwoAPI(); return _pal_gap.cancel_connection_creation(); } @@ -851,11 +861,15 @@ ble_error_t GenericGap::disconnect( local_disconnection_reason_t reason ) { + useVersionTwoAPI(); + return _pal_gap.disconnect(connectionHandle, reason); } ble_error_t GenericGap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) { + useVersionOneAPI(); + if (is_disconnection_reason_valid(reason) == false) { return BLE_ERROR_INVALID_PARAM; } @@ -867,6 +881,8 @@ ble_error_t GenericGap::disconnect(Handle_t connectionHandle, DisconnectionReaso ble_error_t GenericGap::updateConnectionParams(Handle_t handle, const ConnectionParams_t *params) { + useVersionOneAPI(); + if (is_connection_params_valid(params) == false) { return BLE_ERROR_PARAM_OUT_OF_RANGE; } @@ -1078,6 +1094,8 @@ ble_error_t GenericGap::setWhitelist(const Whitelist_t &whitelist) ble_error_t GenericGap::setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode) { + useVersionOneAPI(); + if (mode > ::Gap::ADV_POLICY_FILTER_ALL_REQS) { return BLE_ERROR_INVALID_PARAM; } @@ -1090,6 +1108,8 @@ ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) { useVersionOneAPI(); + useVersionOneAPI(); + if (mode > ::Gap::SCAN_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; } @@ -1100,6 +1120,8 @@ ble_error_t GenericGap::setScanningPolicyMode(ScanningPolicyMode_t mode) ble_error_t GenericGap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) { + useVersionOneAPI(); + if (mode > ::Gap::INIT_POLICY_FILTER_ALL_ADV) { return BLE_ERROR_INVALID_PARAM; } @@ -1110,6 +1132,7 @@ ble_error_t GenericGap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) ::Gap::AdvertisingPolicyMode_t GenericGap::getAdvertisingPolicyMode(void) const { + useVersionOneAPI(); return (AdvertisingPolicyMode_t) _advertising_filter_policy.value(); } @@ -1121,6 +1144,7 @@ ble_error_t GenericGap::setInitiatorPolicyMode(InitiatorPolicyMode_t mode) ::Gap::InitiatorPolicyMode_t GenericGap::getInitiatorPolicyMode(void) const { + useVersionOneAPI(); return (InitiatorPolicyMode_t) _initiator_policy_mode.value(); } @@ -1240,6 +1264,8 @@ ble_error_t GenericGap::getCentralPrivacyConfiguration( ble_error_t GenericGap::setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse) { + useVersionOneAPI(); + ble_error_t err = _pal_gap.set_advertising_data( advData.getPayloadLen(), pal::advertising_data_t(advData.getPayload(), advData.getPayloadLen()) @@ -1256,6 +1282,8 @@ ble_error_t GenericGap::setAdvertisingData(const GapAdvertisingData &advData, co ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) { + useVersionOneAPI(); + if (is_advertising_params_valid(params) == false) { return BLE_ERROR_INVALID_PARAM; } @@ -1605,7 +1633,7 @@ void GenericGap::on_disconnection_complete(const pal::GapDisconnectionCompleteEv (::Gap::DisconnectionReason_t) e.reason ); } else { - // TODO: define what to do in case of faillure + // TODO: define what to do in case of failure } } @@ -1842,12 +1870,14 @@ const size_t GenericGap::MAX_HCI_DATA_LENGTH; uint8_t GenericGap::getMaxAdvertisingSetNumber() { + useVersionTwoAPI(); uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); return std::min(MAX_ADVERTISING_SETS, set_number); } uint8_t GenericGap::getMaxAdvertisingDataLength() { + useVersionTwoAPI(); return _pal_gap.get_maximum_advertising_data_length(); } @@ -1856,6 +1886,8 @@ ble_error_t GenericGap::createAdvertisingSet( const AdvertisingParameters ¶meters ) { + useVersionTwoAPI(); + if (is_extended_advertising_available()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1885,6 +1917,8 @@ ble_error_t GenericGap::createAdvertisingSet( ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) { + useVersionTwoAPI(); + if (is_extended_advertising_available()) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1923,6 +1957,8 @@ ble_error_t GenericGap::setAdvertisingParameters( const AdvertisingParameters ¶ms ) { + useVersionTwoAPI(); + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2001,6 +2037,8 @@ ble_error_t GenericGap::setAdvertisingPayload( mbed::Span payload ) { + useVersionTwoAPI(); + return setAdvertisingData( handle, payload, @@ -2014,6 +2052,8 @@ ble_error_t GenericGap::setAdvertisingScanResponse( mbed::Span response ) { + useVersionTwoAPI(); + return setAdvertisingData( handle, response, @@ -2124,6 +2164,8 @@ ble_error_t GenericGap::startAdvertising( uint8_t maxEvents ) { + useVersionTwoAPI(); + ble_error_t error = BLE_ERROR_NONE; if (handle >= getMaxAdvertisingSetNumber()) { @@ -2187,6 +2229,8 @@ ble_error_t GenericGap::startAdvertising( ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) { + useVersionTwoAPI(); + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2218,6 +2262,8 @@ ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) bool GenericGap::isAdvertisingActive(advertising_handle_t handle) { + useVersionTwoAPI(); + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2232,6 +2278,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingParameters( bool advertiseTxPower ) { + useVersionTwoAPI(); + if (periodicAdvertisingIntervalMin.value() > periodicAdvertisingIntervalMax.value()) { return BLE_ERROR_INVALID_PARAM; } @@ -2261,6 +2309,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( mbed::Span payload ) { + useVersionTwoAPI(); + if (handle == LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -2316,6 +2366,8 @@ ble_error_t GenericGap::setPeriodicAdvertisingPayload( ble_error_t GenericGap::startPeriodicAdvertising(advertising_handle_t handle) { + useVersionTwoAPI(); + if (handle == LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -2347,6 +2399,8 @@ ble_error_t GenericGap::startPeriodicAdvertising(advertising_handle_t handle) ble_error_t GenericGap::stopPeriodicAdvertising(advertising_handle_t handle) { + useVersionTwoAPI(); + if (handle == LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -2363,7 +2417,6 @@ ble_error_t GenericGap::stopPeriodicAdvertising(advertising_handle_t handle) return BLE_ERROR_INVALID_STATE; } - ble_error_t err = _pal_gap.periodic_advertising_enable(false, handle); if (err) { return err; @@ -2375,6 +2428,8 @@ ble_error_t GenericGap::stopPeriodicAdvertising(advertising_handle_t handle) bool GenericGap::isPeriodicAdvertisingActive(advertising_handle_t handle) { + useVersionTwoAPI(); + if (handle >= getMaxAdvertisingSetNumber()) { return BLE_ERROR_INVALID_PARAM; } @@ -2722,6 +2777,8 @@ ble_error_t GenericGap::createSync( sync_timeout_t timeout ) { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2751,6 +2808,8 @@ ble_error_t GenericGap::createSync( sync_timeout_t timeout ) { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2767,6 +2826,8 @@ ble_error_t GenericGap::createSync( ble_error_t GenericGap::cancelCreateSync() { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2776,6 +2837,8 @@ ble_error_t GenericGap::cancelCreateSync() ble_error_t GenericGap::terminateSync(periodic_sync_handle_t handle) { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2789,6 +2852,8 @@ ble_error_t GenericGap::addDeviceToPeriodicAdvertiserList( advertising_sid_t sid ) { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2816,6 +2881,8 @@ ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( advertising_sid_t sid ) { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2839,6 +2906,8 @@ ble_error_t GenericGap::removeDeviceFromPeriodicAdvertiserList( ble_error_t GenericGap::clearPeriodicAdvertiserList() { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } @@ -2848,6 +2917,8 @@ ble_error_t GenericGap::clearPeriodicAdvertiserList() uint8_t GenericGap::getMaxPeriodicAdvertiserListSize() { + useVersionTwoAPI(); + if (is_extended_advertising_available() == false) { return BLE_ERROR_NOT_IMPLEMENTED; } From e54e3eaee0a9de506133e85aa2203a2e67f3ffb5 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 15:40:00 +0000 Subject: [PATCH 328/361] cast no longer needed --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7c845b9d13..8687c44c17 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -704,7 +704,7 @@ ble_error_t GenericGap::connect( connectionParams.getOwnAddressType(), adjusted_address_type, peerAddress, - (phy_set_t) connectionParams.getPhySet(), + connectionParams.getPhySet(), connectionParams.getScanIntervalArray(), connectionParams.getScanWindowArray(), connectionParams.getMinConnectionIntervalArray(), From 2b94b66fd24d68297220cfa4e196ab2d0fcd7f1e Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 15:41:32 +0000 Subject: [PATCH 329/361] deprecate services that are not useless --- .../ble/services/URIBeaconConfigService.h | 21 ++++++++++++++----- features/FEATURE_BLE/ble/services/iBeacon.h | 12 +++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h index 9eb95bd40c..56b0ce2920 100644 --- a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h +++ b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h @@ -39,11 +39,16 @@ extern const uint8_t UUID_RESET_CHAR[UUID::LENGTH_OF_LONG_UUID]; extern const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)]; /** -* @class URIBeaconConfigService -* @brief UriBeacon Configuration Service. Can be used to set URL, adjust power levels, and set flags. -* See http://uribeacon.org -* -*/ + * @class URIBeaconConfigService + * @brief UriBeacon Configuration Service. Can be used to set URL, adjust power levels, and set flags. + * See http://uribeacon.org + * + * @deprecated This service is deprecated and no replacement is currently available. + */ +MBED_DEPRECATED_SINCE( + "mbed-os-5.11", + "This service is deprecated and no replacement is currently available." +) class URIBeaconConfigService { public: /** @@ -89,7 +94,13 @@ class URIBeaconConfigService { * Default un-encoded URI. Applies only if the resetToDefaultsFlag is true. * @param[in] defaultAdvPowerLevelsIn * Default power-levels array. Applies only if the resetToDefaultsFlag is true. + * + * @deprecated This service is deprecated and no replacement is currently available. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11", + "This service is deprecated and no replacement is currently available." + ) URIBeaconConfigService(BLE &bleIn, Params_t ¶msIn, bool resetToDefaultsFlag, diff --git a/features/FEATURE_BLE/ble/services/iBeacon.h b/features/FEATURE_BLE/ble/services/iBeacon.h index f75e460381..ba5b1b2560 100644 --- a/features/FEATURE_BLE/ble/services/iBeacon.h +++ b/features/FEATURE_BLE/ble/services/iBeacon.h @@ -81,7 +81,13 @@ * The licence also grant access to the iBeacons technical specification. * * @note More information at https://developer.apple.com/ibeacon/Getting-Started-with-iBeacon.pdf + * + * @deprecated This service is deprecated and no replacement is currently available. */ +MBED_DEPRECATED_SINCE( + "mbed-os-5.11", + "This service is deprecated and no replacement is currently available." +) class iBeacon { public: @@ -197,7 +203,13 @@ public: * to the beacon. * * @param[in] compID ID of the beacon manufacturer. + * + * @deprecated This service is deprecated and no replacement is currently available. */ + MBED_DEPRECATED_SINCE( + "mbed-os-5.11", + "This service is deprecated and no replacement is currently available." + ) iBeacon( BLE &_ble, LocationUUID_t uuid, From f4a560dacef1829bf23c309411b834efb1c4c652 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 16:25:33 +0000 Subject: [PATCH 330/361] reset advertising sets on reset --- features/FEATURE_BLE/ble/generic/GenericGap.h | 7 +++++++ features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/features/FEATURE_BLE/ble/generic/GenericGap.h b/features/FEATURE_BLE/ble/generic/GenericGap.h index 5cfad352ee..d3a02ffdd9 100644 --- a/features/FEATURE_BLE/ble/generic/GenericGap.h +++ b/features/FEATURE_BLE/ble/generic/GenericGap.h @@ -755,6 +755,13 @@ private: data[p.byte_index] &= ~(0x01 << p.bit_index); } + void clear() + { + for (size_t i = 0; i < (bit_size / 8 + 1); ++i) { + data[i] = 0; + } + } + private: struct position { position(size_t bit_number) : diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 8687c44c17..968a1e7e94 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1345,8 +1345,15 @@ ble_error_t GenericGap::startAdvertising(const GapAdvertisingParams ¶ms) ble_error_t GenericGap::reset(void) { ::Gap::reset(); + _advertising_timeout.detach(); _scan_timeout.detach(); + + _existing_sets.clear(); + _active_sets.clear(); + _active_periodic_sets.clear(); + _active_sets.set(LEGACY_ADVERTISING_HANDLE); + _pal_gap.clear_advertising_sets(); return BLE_ERROR_NONE; From 6f3a9ca107cf02b81ed5d4dab8315bccdb00b423 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 16:29:33 +0000 Subject: [PATCH 331/361] legacy handle starts off present in _existing_sets --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 968a1e7e94..881f533f4e 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -458,7 +458,7 @@ GenericGap::GenericGap( LEGACY_ADVERTISING_HANDLE, AdvertisingParameters() ); - _active_sets.set(LEGACY_ADVERTISING_HANDLE); + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); } } @@ -1352,7 +1352,7 @@ ble_error_t GenericGap::reset(void) _existing_sets.clear(); _active_sets.clear(); _active_periodic_sets.clear(); - _active_sets.set(LEGACY_ADVERTISING_HANDLE); + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); _pal_gap.clear_advertising_sets(); From bed7677c81db107dfaf0f7cc3f68b9a5bdde1a1c Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 16:51:28 +0000 Subject: [PATCH 332/361] stop advertising before reseting --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 881f533f4e..3db249fd27 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1349,11 +1349,32 @@ ble_error_t GenericGap::reset(void) _advertising_timeout.detach(); _scan_timeout.detach(); + /* stop all advertising sets */ + for (size_t i = 0; i < MAX_ADVERTISING_SETS; ++i) { + if (_active_sets.get(i)) { + _pal_gap.extended_advertising_enable( + /* enable */ false, + /* number of advertising sets */ 1, + (advertising_handle_t*)&i, + NULL, + NULL + ); + } + if (_active_periodic_sets.get(i)) { + _pal_gap.periodic_advertising_enable( + /* enable */ false, + (advertising_handle_t)i + ); + } + } + + /* clear state of all advertising sets */ _existing_sets.clear(); + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); _active_sets.clear(); _active_periodic_sets.clear(); - _existing_sets.set(LEGACY_ADVERTISING_HANDLE); + /* clear advertising set data on the controller */ _pal_gap.clear_advertising_sets(); return BLE_ERROR_NONE; From bf535af159afde0078d1078017e8702fda7c5b28 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 16:57:07 +0000 Subject: [PATCH 333/361] check feature support before calling extended functnions --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 58 +++++++++++-------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 3db249fd27..9c390487d2 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1349,34 +1349,42 @@ ble_error_t GenericGap::reset(void) _advertising_timeout.detach(); _scan_timeout.detach(); - /* stop all advertising sets */ - for (size_t i = 0; i < MAX_ADVERTISING_SETS; ++i) { - if (_active_sets.get(i)) { - _pal_gap.extended_advertising_enable( - /* enable */ false, - /* number of advertising sets */ 1, - (advertising_handle_t*)&i, - NULL, - NULL - ); - } - if (_active_periodic_sets.get(i)) { - _pal_gap.periodic_advertising_enable( - /* enable */ false, - (advertising_handle_t)i - ); + if (is_extended_advertising_available()) { + /* stop all advertising sets */ + for (size_t i = 0; i < MAX_ADVERTISING_SETS; ++i) { + if (_active_sets.get(i)) { + _pal_gap.extended_advertising_enable( + /* enable */ false, + /* number of advertising sets */ 1, + (advertising_handle_t*)&i, + NULL, + NULL + ); + } + if (_active_periodic_sets.get(i)) { + _pal_gap.periodic_advertising_enable( + /* enable */ false, + (advertising_handle_t)i + ); + } } + + /* clear state of all advertising sets */ + _existing_sets.clear(); + _active_sets.clear(); + _active_periodic_sets.clear(); + + /* clear advertising set data on the controller */ + _pal_gap.clear_advertising_sets(); + + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); + + setExtendedAdvertisingParameters( + LEGACY_ADVERTISING_HANDLE, + AdvertisingParameters() + ); } - /* clear state of all advertising sets */ - _existing_sets.clear(); - _existing_sets.set(LEGACY_ADVERTISING_HANDLE); - _active_sets.clear(); - _active_periodic_sets.clear(); - - /* clear advertising set data on the controller */ - _pal_gap.clear_advertising_sets(); - return BLE_ERROR_NONE; } From ac47736259bd4ae4746bb6f949e432a1681c3616 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 16:56:45 +0000 Subject: [PATCH 334/361] BLE: Enable cordio extended modules if available. --- .../targets/TARGET_CORDIO/source/CordioBLE.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp index 4fbbc9e87b..05e191767f 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp @@ -259,6 +259,15 @@ void BLE::processEvents() ::BLE::Instance(::BLE::DEFAULT_INSTANCE), BLE_ERROR_NONE }; + + // initialize extended module if supported + if (HciGetLeSupFeat() == HCI_LE_SUP_FEAT_LE_EXT_ADV) { + DmExtAdvInit(); + DmExtScanInit(); + DmExtConnMasterInit(); + DmExtConnSlaveInit(); + } + deviceInstance().getGattServer().initialize(); deviceInstance().initialization_status = INITIALIZED; _init_callback.call(&context); From 7f3314576058f50d636631fd40fca0d2fb14021d Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 17:12:50 +0000 Subject: [PATCH 335/361] BLE: Fix extended advertising check. --- features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp index 05e191767f..08d04492bd 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioBLE.cpp @@ -261,7 +261,7 @@ void BLE::processEvents() }; // initialize extended module if supported - if (HciGetLeSupFeat() == HCI_LE_SUP_FEAT_LE_EXT_ADV) { + if (HciGetLeSupFeat() & HCI_LE_SUP_FEAT_LE_EXT_ADV) { DmExtAdvInit(); DmExtScanInit(); DmExtConnMasterInit(); From 3ae38ac1e81348421f56bc1c72bc0d2f13ac44d8 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 17:06:38 +0000 Subject: [PATCH 336/361] always set existing set for legacy handle --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 9c390487d2..305b330df3 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -458,8 +458,9 @@ GenericGap::GenericGap( LEGACY_ADVERTISING_HANDLE, AdvertisingParameters() ); - _existing_sets.set(LEGACY_ADVERTISING_HANDLE); } + + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); } GenericGap::~GenericGap() @@ -1377,14 +1378,14 @@ ble_error_t GenericGap::reset(void) /* clear advertising set data on the controller */ _pal_gap.clear_advertising_sets(); - _existing_sets.set(LEGACY_ADVERTISING_HANDLE); - setExtendedAdvertisingParameters( LEGACY_ADVERTISING_HANDLE, AdvertisingParameters() ); } + _existing_sets.set(LEGACY_ADVERTISING_HANDLE); + return BLE_ERROR_NONE; } From daf0f429c8c8914134aa3a4e4dff2427c1bcaaef Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 19:12:48 +0000 Subject: [PATCH 337/361] BLE: Fix advertising set issues on legacy controllers. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 305b330df3..f738e85f33 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1908,8 +1908,13 @@ const size_t GenericGap::MAX_HCI_DATA_LENGTH; uint8_t GenericGap::getMaxAdvertisingSetNumber() { useVersionTwoAPI(); - uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); - return std::min(MAX_ADVERTISING_SETS, set_number); + + if (is_extended_advertising_available()) { + uint8_t set_number = _pal_gap.get_max_number_of_advertising_sets(); + return std::min(MAX_ADVERTISING_SETS, set_number); + } else { + return 1; + } } uint8_t GenericGap::getMaxAdvertisingDataLength() From 0ef7a404759867a6f838412c65e0d310ef66d4bd Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 21:00:46 +0000 Subject: [PATCH 338/361] BLE: Fix set advertising paylaod dispatch. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index f738e85f33..0fe570b5f8 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1441,6 +1441,7 @@ void GenericGap::processDisconnectionEvent( } if (_eventHandler) { + printf("disconnection complete passed to application event handler\r\n"); _eventHandler->onDisconnectionComplete( DisconnectionEvent( handle, @@ -2085,7 +2086,7 @@ ble_error_t GenericGap::setAdvertisingPayload( handle, payload, /* minimise fragmentation */ true, - /* scan response */ true + /* scan response */ false ); } From 56185582aa1fdaf966de6e143dae804ebcb7ab0e Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 21:01:14 +0000 Subject: [PATCH 339/361] BLE: Report legacy advertising with new API. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 0fe570b5f8..2bcef45c63 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1550,6 +1550,26 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent &e) peer_address_type_t peer_address_type = static_cast(advertising.address_type.value()); + // report in new event handler + if (_eventHandler) { + _eventHandler->onAdvertisingReport( + AdvertisingReportEvent( + advertising_event_t(/*advertising.type*/ 0), // TODO + peer_address_type, + advertising.address, + /* primary */ phy_t::LE_1M, + /* secondary */ phy_t::NONE, + /* SID - NO ADI FIELD IN THE PDU */ 0xFF, + /* tx power information not available */ 127, + advertising.rssi, + /* NO PERIODIC ADVERTISING */ periodic_interval_t(0), + peer_address_type_t::ANONYMOUS, + ble::address_t (), + mbed::Span(advertising.data.data(), advertising.data.size()) + ) + ); + } + BLE_DEPRECATED_API_USE_BEGIN() processAdvertisementReport( advertising.address.data(), From 4d986bf376cf8d69ef12299bdc84b57665758b01 Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 21:11:34 +0000 Subject: [PATCH 340/361] fix is feature enabled condition and made in consistent --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 52 +++++++++---------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 2bcef45c63..045e87cd36 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -669,7 +669,7 @@ ble_error_t GenericGap::connect( } } - if (!is_extended_advertising_available()) { + if (is_extended_advertising_available() == false) { phy_set_t set(connectionParams.getPhySet()); if (set.count() != 1 || set.get_1m() == false) { return BLE_ERROR_INVALID_PARAM; @@ -1951,7 +1951,7 @@ ble_error_t GenericGap::createAdvertisingSet( { useVersionTwoAPI(); - if (is_extended_advertising_available()) { + if (is_extended_advertising_available() == false) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -1982,7 +1982,7 @@ ble_error_t GenericGap::destroyAdvertisingSet(advertising_handle_t handle) { useVersionTwoAPI(); - if (is_extended_advertising_available()) { + if (is_extended_advertising_available() == false) { return BLE_ERROR_OPERATION_NOT_PERMITTED; } @@ -2030,7 +2030,9 @@ ble_error_t GenericGap::setAdvertisingParameters( return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_available()) { + if (is_extended_advertising_available()) { + return setExtendedAdvertisingParameters(handle, params); + } else { if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -2051,8 +2053,6 @@ ble_error_t GenericGap::setAdvertisingParameters( channel_map, params.getFilter() ); - } else { - return setExtendedAdvertisingParameters(handle, params); } } @@ -2155,7 +2155,7 @@ ble_error_t GenericGap::setAdvertisingData( } // handle special case of legacy advertising - if (!is_extended_advertising_available()) { + if (is_extended_advertising_available() == false) { if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } @@ -2239,24 +2239,7 @@ ble_error_t GenericGap::startAdvertising( return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_available()) { - if (handle != LEGACY_ADVERTISING_HANDLE) { - return BLE_ERROR_INVALID_PARAM; - } - - error = _pal_gap.advertising_enable(true); - if (error) { - return error; - } - - _advertising_timeout.detach(); - if (maxDuration.value()) { - _advertising_timeout.attach_us( - mbed::callback(this, &GenericGap::on_advertising_timeout), - durationCast(maxDuration).value() - ); - } - } else { + if (is_extended_advertising_available()) { ble::address_t random_address; if (!getUnresolvableRandomAddress(random_address)) { @@ -2283,6 +2266,23 @@ ble_error_t GenericGap::startAdvertising( if (error) { return error; } + } else { + if (handle != LEGACY_ADVERTISING_HANDLE) { + return BLE_ERROR_INVALID_PARAM; + } + + error = _pal_gap.advertising_enable(true); + if (error) { + return error; + } + + _advertising_timeout.detach(); + if (maxDuration.value()) { + _advertising_timeout.attach_us( + mbed::callback(this, &GenericGap::on_advertising_timeout), + durationCast(maxDuration).value() + ); + } } _active_sets.set(handle); @@ -2302,7 +2302,7 @@ ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) return BLE_ERROR_INVALID_PARAM; } - if (!is_extended_advertising_available()) { + if (is_extended_advertising_available() == false) { if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } From a14f143c850dddf77393ce02d08f1b9f503144ce Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 23:00:29 +0000 Subject: [PATCH 341/361] set active set to false when stoping advertising --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 045e87cd36..7065f044ad 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -2302,25 +2302,37 @@ ble_error_t GenericGap::stopAdvertising(advertising_handle_t handle) return BLE_ERROR_INVALID_PARAM; } - if (is_extended_advertising_available() == false) { + ble_error_t status; + + if (is_extended_advertising_available()) { + status = _pal_gap.extended_advertising_enable( + /*enable ? */ false, + /* number of advertising sets */ 1, + &handle, + NULL, + NULL + ); + + if (status) { + return status; + } + } else { if (handle != LEGACY_ADVERTISING_HANDLE) { return BLE_ERROR_INVALID_PARAM; } - ble_error_t err = _pal_gap.advertising_enable(false); - if (err) { - return err; + status = _pal_gap.advertising_enable(false); + + if (status) { + return status; } + _advertising_timeout.detach(); } - return _pal_gap.extended_advertising_enable( - /*enable ? */ false, - /* number of advertising sets */ 1, - &handle, - NULL, - NULL - ); + _active_sets.clear(handle); + + return status; } bool GenericGap::isAdvertisingActive(advertising_handle_t handle) From ef1552a8f5105983e171865094abcd0f1b955029 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 22:59:57 +0000 Subject: [PATCH 342/361] BLE: report legacy connection event in new event handler. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 7065f044ad..6a0c2c939f 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1587,6 +1587,24 @@ BLE_DEPRECATED_API_USE_END() void GenericGap::on_connection_complete(const pal::GapConnectionCompleteEvent &e) { if (e.status != pal::hci_error_code_t::SUCCESS) { + if (_eventHandler) { + _eventHandler->onConnectionComplete( + ConnectionCompleteEvent( + BLE_ERROR_NOT_FOUND, + INVALID_ADVERTISING_HANDLE, + connection_role_t::CENTRAL, + peer_address_type_t::ANONYMOUS, + ble::address_t(), + ble::address_t(), + ble::address_t(), + ble::conn_interval_t::max(), + /* dummy slave latency */ 0, + ble::supervision_timeout_t::max(), + /* master clock accuracy */ 0 + ) + ); + } + // for now notify user that the connection failled by issuing a timeout // event @@ -1660,6 +1678,26 @@ BLE_DEPRECATED_API_USE_END() address = _pal_gap.get_random_address(); } + // new process event + if (_eventHandler) { + _eventHandler->onConnectionComplete( + ConnectionCompleteEvent( + BLE_ERROR_NONE, + e.connection_handle, + e.role, + e.peer_address_type, + e.peer_address, + e.local_resolvable_private_address, + e.peer_resolvable_private_address, + conn_interval_t(e.connection_interval), + e.connection_latency, + supervision_timeout_t(e.supervision_timeout), + /* default master clock accuracy */ ble::clock_accuracy_t::PPM_500 + ) + ); + } + + // legacy process event processConnectionEvent( e.connection_handle, e.role.value() == e.role.CENTRAL ? ::Gap::CENTRAL : ::Gap::PERIPHERAL, From b552f8c3f08bb92394396b8bc6d21a26e89ae28f Mon Sep 17 00:00:00 2001 From: paul-szczepanek-arm <33840200+paul-szczepanek-arm@users.noreply.github.com> Date: Mon, 26 Nov 2018 23:06:06 +0000 Subject: [PATCH 343/361] fix return code for implemented func --- .../targets/TARGET_CORDIO/source/CordioPalSecurityManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalSecurityManager.cpp b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalSecurityManager.cpp index 3c1bc36a94..a957deb40c 100644 --- a/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalSecurityManager.cpp +++ b/features/FEATURE_BLE/targets/TARGET_CORDIO/source/CordioPalSecurityManager.cpp @@ -443,7 +443,7 @@ ble_error_t CordioSecurityManager::cancel_pairing( ble_error_t CordioSecurityManager::get_random_data(byte_array_t<8> &random_data) { SecRand(random_data.data(), random_data.size()); - return BLE_ERROR_NOT_IMPLEMENTED; + return BLE_ERROR_NONE; } //////////////////////////////////////////////////////////////////////////// From 0c9ce24638cff1e5f2b0da5a26497d29114ac728 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 23:16:31 +0000 Subject: [PATCH 344/361] BLE: remove unwanted trace. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 6a0c2c939f..89e75b9a8d 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1441,7 +1441,6 @@ void GenericGap::processDisconnectionEvent( } if (_eventHandler) { - printf("disconnection complete passed to application event handler\r\n"); _eventHandler->onDisconnectionComplete( DisconnectionEvent( handle, From 66a9e635bd90b1dfdfd1907c59a4be6cdc391bb1 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 23:28:30 +0000 Subject: [PATCH 345/361] BLE: report correct event type for legacy advertising report. --- .../FEATURE_BLE/source/generic/GenericGap.cpp | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index 89e75b9a8d..c997d14fa9 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1551,9 +1551,31 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent &e) // report in new event handler if (_eventHandler) { + uint8_t event_type = 0; + + // Conversion table available at BLUETOOTH SPECIFICATION Version 5.0 | Vol 2, Part E + // 7.7.65.13 + switch (advertising.type.value()) { + case pal::received_advertising_type_t::ADV_IND: + event_type = 0x13; + break; + case pal::received_advertising_type_t::ADV_DIRECT_IND: + event_type = 0x15; + break; + case pal::received_advertising_type_t::ADV_SCAN_IND: + event_type = 0x12; + break; + case pal::received_advertising_type_t::ADV_NONCONN_IND: + event_type = 0x10; + break; + case pal::received_advertising_type_t::SCAN_RESPONSE: + event_type = 0x1B; + break; + } + _eventHandler->onAdvertisingReport( AdvertisingReportEvent( - advertising_event_t(/*advertising.type*/ 0), // TODO + advertising_event_t(event_type), // TODO peer_address_type, advertising.address, /* primary */ phy_t::LE_1M, From 7b1e225012d08b1804888290f7f2ce45d7300cd2 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 23:36:43 +0000 Subject: [PATCH 346/361] BLE: Fix address name in NRF targets. --- .../targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xGap.cpp | 2 +- .../TARGET_NRF51/source/nRF5xPalSecurityManager.cpp | 4 ++-- .../TARGET_NRF51/source/nRF5xPalSecurityManager.h | 2 +- .../targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xGap.cpp | 2 +- .../TARGET_NRF52/source/nRF5xPalSecurityManager.cpp | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xGap.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xGap.cpp index e441fd4717..f4b0d393b2 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xGap.cpp @@ -79,7 +79,7 @@ peer_address_type_t convert_nordic_address(uint8_t address) { } peer_address_type_t convert_identity_address(advertising_peer_address_type_t address) { - if (address == advertising_peer_address_type_t::PUBLIC_ADDRESS) { + if (address == advertising_peer_address_type_t::PUBLIC) { return peer_address_type_t::PUBLIC_IDENTITY; } else { return peer_address_type_t::RANDOM_STATIC_IDENTITY; diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.cpp index e797b85223..36c7c1e0a2 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.cpp @@ -988,10 +988,10 @@ bool nRF5xSecurityManager::sm_handler(const ble_evt_t *evt) ); advertising_peer_address_type_t - address_type(advertising_peer_address_type_t::PUBLIC_ADDRESS); + address_type(advertising_peer_address_type_t::PUBLIC); if (pairing_cb->peer_id_key.id_addr_info.addr_type) { - address_type = advertising_peer_address_type_t::RANDOM_ADDRESS; + address_type = advertising_peer_address_type_t::RANDOM; } handler->on_keys_distributed_bdaddr( diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.h b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.h index 46482fcee4..32184507da 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.h +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF51/source/nRF5xPalSecurityManager.h @@ -90,7 +90,7 @@ public: struct resolving_list_entry_t { resolving_list_entry_t() : peer_identity_address_type( - advertising_peer_address_type_t::PUBLIC_ADDRESS + advertising_peer_address_type_t::PUBLIC ) { } diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xGap.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xGap.cpp index ae12ee7c27..5c343eafa5 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xGap.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xGap.cpp @@ -108,7 +108,7 @@ peer_address_type_t convert_nordic_address(bool identity, uint8_t address) { } peer_address_type_t convert_identity_address(advertising_peer_address_type_t address) { - if (address == advertising_peer_address_type_t::PUBLIC_ADDRESS) { + if (address == advertising_peer_address_type_t::PUBLIC) { return peer_address_type_t::PUBLIC_IDENTITY; } else { return peer_address_type_t::RANDOM_STATIC_IDENTITY; diff --git a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xPalSecurityManager.cpp b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xPalSecurityManager.cpp index 5eb1310bb4..a1d6b1e7e9 100644 --- a/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xPalSecurityManager.cpp +++ b/features/FEATURE_BLE/targets/TARGET_NORDIC/TARGET_NRF52/source/nRF5xPalSecurityManager.cpp @@ -1022,10 +1022,10 @@ bool nRF5xSecurityManager::sm_handler(const ble_evt_t *evt) ); advertising_peer_address_type_t - address_type(advertising_peer_address_type_t::PUBLIC_ADDRESS); + address_type(advertising_peer_address_type_t::PUBLIC); if (pairing_cb->peer_id_key.id_addr_info.addr_type) { - address_type = advertising_peer_address_type_t::RANDOM_ADDRESS; + address_type = advertising_peer_address_type_t::RANDOM; } handler->on_keys_distributed_bdaddr( From a65296e9ee8563c188cfc6e3e35e007188894f50 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Mon, 26 Nov 2018 23:44:23 +0000 Subject: [PATCH 347/361] BLE: removed resolved TODO. --- features/FEATURE_BLE/source/generic/GenericGap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/features/FEATURE_BLE/source/generic/GenericGap.cpp b/features/FEATURE_BLE/source/generic/GenericGap.cpp index c997d14fa9..a4928a07df 100644 --- a/features/FEATURE_BLE/source/generic/GenericGap.cpp +++ b/features/FEATURE_BLE/source/generic/GenericGap.cpp @@ -1575,7 +1575,7 @@ void GenericGap::on_advertising_report(const pal::GapAdvertisingReportEvent &e) _eventHandler->onAdvertisingReport( AdvertisingReportEvent( - advertising_event_t(event_type), // TODO + advertising_event_t(event_type), peer_address_type, advertising.address, /* primary */ phy_t::LE_1M, From ecf8c7320f76b2bc934f894d2fdab0de2a290873 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 17:58:50 -0600 Subject: [PATCH 348/361] Edit Gap.h Edit file for capitalization and active voice. --- features/FEATURE_BLE/ble/Gap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/features/FEATURE_BLE/ble/Gap.h b/features/FEATURE_BLE/ble/Gap.h index eb500cd30e..b3019d8a9c 100644 --- a/features/FEATURE_BLE/ble/Gap.h +++ b/features/FEATURE_BLE/ble/Gap.h @@ -1354,7 +1354,7 @@ protected: * @return BLE_ERROR_NONE if the scan procedure was successfully started. * * @deprecated Deprecated since addition of extended advertising support. - * Vendors should use the cordio hci interface or the ble::pal or implement + * Vendors should use the Cordio HCI interface or the ble::pal or implement * startScan(duplicates_filter_t, scan_duration_t, period) */ MBED_DEPRECATED_SINCE( @@ -1375,7 +1375,7 @@ public: * @return The current GAP state of the device. * * @deprecated Deprecated since addition of extended advertising support. - * This is not meaningful when extended advertising is used, please use + * This is not meaningful when you use extended advertising; please use * isAdvertisingActive() and getConnectionCount(). */ MBED_DEPRECATED_SINCE( From 451f9aad12da6c220f057954cab0b48376866831 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:01:30 -0600 Subject: [PATCH 349/361] Edit Bounded.h Edit file, mostly for consistent capitalization and active voice. --- features/FEATURE_BLE/ble/common/Bounded.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Bounded.h b/features/FEATURE_BLE/ble/common/Bounded.h index 87293e6808..85b62cf386 100644 --- a/features/FEATURE_BLE/ble/common/Bounded.h +++ b/features/FEATURE_BLE/ble/common/Bounded.h @@ -29,15 +29,15 @@ namespace ble { * * @tparam Rep The C++ integer type used to represent the values. * @tparam Min Minimum value allowed. - * @tparam Max maximum value allowed. + * @tparam Max Maximum value allowed. */ template struct Bounded { /** * Construct a bounded integer. * - * If v is out of the range [Min : Max] then if it is less than Min the - * value of the bounded integer will be Min and if it greater than Max then + * If v is out of the range [Min : Max], then if it is less than Min, the + * value of the bounded integer will be Min. If it greater than Max, then * the value of the bounded integer will be Max. * * @param v The value to store. @@ -64,7 +64,7 @@ struct Bounded { /** * The left-bound value. * - * @return The lowest value that can be represented by this type + * @return The lowest value that this type can represent */ static Rep min() { @@ -74,7 +74,7 @@ struct Bounded { /** * The right-bound value. * - * @return The highest value that can be represented by this type + * @return The highest value that this type can represent */ static Rep max() { From 7df90ba3bc921bcfe09f7debebcff0bdabad0697 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:12:56 -0600 Subject: [PATCH 350/361] Edit AdvertisingDataBuilder.h Edit file, mostly to fix typos and standardize hyphen use. --- features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h index 72fcd1bb06..78574cce57 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataBuilder.h @@ -41,12 +41,12 @@ namespace ble { /** * Build advertising data. * - * The builder accept an array of bytes in input and returns the result of the + * The builder accepts an array of bytes in input and returns the result of the * construction with getAdvertisingData(). */ class AdvertisingDataBuilder { public: - /** Advertising data needs a user provided buffer to store the data. + /** Advertising data needs a user-provided buffer to store the data. * * @param buffer Buffer used to store the data. * @note Use Gap::getMaxAdvertisingDataLength() to find out how much can be accepted. @@ -69,7 +69,7 @@ public: mbed::Span getAdvertisingData() const; /** - * Add a new field into the payload. Will return an error if type is already present. + * Add a new field into the payload. Returns an error if type is already present. * * @note Data size for individual types cannot exceed 255 bytes. * @@ -232,7 +232,7 @@ public: ble_error_t setName(const char *name, bool complete = true); /** - * Add manufacturer specific data to the advertising payload. + * Add manufacturer-specific data to the advertising payload. * * @note Data size for individual types cannot exceed 255 bytes. * @@ -286,7 +286,7 @@ public: ble_error_t setServiceData(UUID service, mbed::Span data); /** - * Add local service IDs to the advertising payload. If they data can't fit + * Add local service IDs to the advertising payload. If the data can't fit, * no modification will take place. * * @note Data size for individual types cannot exceed 255 bytes. From 5347a8ae4aba725e09f439a8a87cba71a764ba1b Mon Sep 17 00:00:00 2001 From: Donatien Garnier Date: Tue, 27 Nov 2018 00:16:33 +0000 Subject: [PATCH 351/361] Update Duration.h in consistent casing --- features/FEATURE_BLE/ble/common/Duration.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/features/FEATURE_BLE/ble/common/Duration.h b/features/FEATURE_BLE/ble/common/Duration.h index 2bb91c5c0a..70e6c559e8 100644 --- a/features/FEATURE_BLE/ble/common/Duration.h +++ b/features/FEATURE_BLE/ble/common/Duration.h @@ -126,12 +126,12 @@ struct Duration { * * @note The operation fail at compile time of there is a loss of precision. * - * @tparam OtherRep The type used to represent the other duration. - * @tparam OtherTB The time base in us units of the other duration. - * @tparam OtherRange The range of the other duration. + * @tparam OtherRep The type used to represent the other Duration. + * @tparam OtherTB The time base in us units of the other Duration. + * @tparam OtherRange The range of the other Duration. * @tparam OtherF The forever value of the other type. * - * @param other The duration used to construct this object. + * @param other The Duration used to construct this object. */ template Duration(Duration other) : @@ -149,7 +149,7 @@ struct Duration { * @tparam OtherRange The range used by other_ms. * @tparam OtherF The forever value used by other_ms. * - * @param other_ms The duration in ms to convert. + * @param other_ms The Duration in ms to convert. */ template explicit Duration(Duration other_ms, void* = NULL) : @@ -183,7 +183,7 @@ struct Duration { static const uint32_t TIME_BASE = TB; /** - * Left-bound of the Duration range. + * Left-bound of the duration range. */ static const Rep MIN = Range::MIN; @@ -223,8 +223,8 @@ struct Duration { } /** - * Return the duration value meaning forever. - * @return the duration value meaning forever. + * Return the Duration value meaning forever. + * @return the Duration value meaning forever. */ static Duration forever() { From 31a73fc00702d478916050182250eaaae842a4e6 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:17:22 -0600 Subject: [PATCH 352/361] Edit AdvertisitngDataSimpleBuilder.h Edit file, mostly for consistent tense and typos. --- .../ble/gap/AdvertisingDataSimpleBuilder.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h b/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h index a720437178..9c529f4a09 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingDataSimpleBuilder.h @@ -34,10 +34,10 @@ namespace ble { * It is a simplified version of AdvertisingDataBuilder that can generate * advertising data "inline". * - * It differs on different points with AdvertisingDataBuilder: + * It differs from AdvertisingDataBuilder on the following points: * - The buffer used to build the advertising data is embedded in the object. - * - If insertion fail, an assertion is raised. In non debug mode, if an - * insertion fail, the buffer is not modified. + * - If insertion fails, an assertion is raised. Outside of debug mode, if an + * insertion fails, the buffer is not modified. * - The API is fluent. * - It hides advanced functions. * @@ -178,7 +178,7 @@ public: } /** - * Add service data data to the advertising payload. + * Add service data to the advertising payload. * * @note Data size for individual types cannot exceed 255 bytes. * @@ -194,7 +194,7 @@ public: } /** - * Add local service ID to the advertising payload. If they data can't fit + * Add local service ID to the advertising payload. If the data can't fit, * no modification will take place. * * @note Data size for individual types cannot exceed 255 bytes. @@ -219,7 +219,7 @@ public: /** - * Add local service IDs to the advertising payload. If they data can't fit + * Add local service IDs to the advertising payload. If the data can't fit, * no modification will take place. * * @note Data size for individual types cannot exceed 255 bytes. @@ -271,7 +271,7 @@ public: } /** - * Add a new field into the payload. The operation fail if type is already present. + * Add a new field into the payload. The operation fails if type is already present. * * @note Data size for individual types cannot exceed 255 bytes. * From c904ac898a450da73750e61c26c1c525c4c8fd70 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:32:35 -0600 Subject: [PATCH 353/361] Edit AdvertisingParameters.h Edit file, mostly for active voice and U.S. spelling. --- .../ble/gap/AdvertisingParameters.h | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h index 2598e851bb..18e9c83f37 100644 --- a/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h +++ b/features/FEATURE_BLE/ble/gap/AdvertisingParameters.h @@ -40,30 +40,30 @@ namespace ble { * * Advertising parameters for legacy advertising are a mainly defined by a pair * of values: - * - The Advertising mode modelled after advertising_type_t. It defines - * if the device is connectable and scannable. This value can be set at - * construction time, updated with setType() and queried by getType(). - * - Time interval between advertisement. It can be set at construction time, - * updated by setPrimaryInterval() and obtained from getMinPrimaryInterval() + * - The Advertising mode modeled after advertising_type_t. It defines + * whether the device is connectable and scannable. You can set this value at + * construction time, update it with setType() and query it with getType(). + * - Time interval between advertisement. You can set it at construction time, + * update it with setPrimaryInterval() and obtain it from getMinPrimaryInterval() * and getMaxPrimaryInterval(). * * In addition, it is possible to adjust other parameters: - * - The advertising channels can be selected with setPrimaryChannels() and - * queried by getChannel37(), getChannel38() and getChannel39(). - * - The address type used by the local device can be set with setOwnAddressType() - * and queried by getOwnAddressType(). - * - The filter policy for scan and connection requests can be set with - * setFilter() and queried by getFilter(). + * - You can select the advertising channels with setPrimaryChannels() and + * queried them with getChannel37(), getChannel38() and getChannel39(). + * - You can set the address type used by the local device with setOwnAddressType() + * and query it by getOwnAddressType(). + * - You can set the filter policy for scan and connection requests with + * setFilter() and query it with getFilter(). * - * For directed advertising, the address of the target can be set with the help - * of setPeer() and queried by getPeerAddress() and getPeerAddressType(). + * For directed advertising, you can set the address of the target with the help + * of setPeer() and query it with getPeerAddress() and getPeerAddressType(). * * @par Extended advertising: * - * To use extended advertising features, legacy advertising should be disabled - * first with setUseLegacyPDU(). + * To use extended advertising features, first disable legacy advertising + * with setUseLegacyPDU(). * - * Extended advertising add new features to BLE advertising: + * Extended advertising adds new features to BLE advertising: * - Control the advertising power with setTxPower(). * - Include the Tx power in advertising packet with includeTxPowerInHeader(). * - Set a secondary phy_t channel with setPhy(). @@ -73,8 +73,8 @@ namespace ble { * * @par Fluent interface: * - * This API is designed with usability in mind. It is perfectly legal to - * construct it and pass it in place. To achieve this the fluent interface pattern + * This API is designed for usability. You can construct + * it and pass it in place. To achieve this, the fluent interface pattern * is used. Every setter returns a reference to the object modified and can be * chained. * @@ -121,10 +121,10 @@ public: * * @param[in] advType Type of advertising. * @param[in] minInterval, maxInterval Time interval between two advertisement. - * A range is provided to the LE subsystem so it can adjust the advertising + * A range is provided to the LE subsystem, so it can adjust the advertising * interval with other transmission happening on the BLE radio. * - * @note If value in input are out of range, they will be normalized. + * @note If values in input are out of range, they will be normalized. */ AdvertisingParameters( advertising_type_t advType = advertising_type_t::CONNECTABLE_UNDIRECTED, @@ -184,8 +184,8 @@ public: /** Set the advertising intervals on the primary channels. * - * @param[in] min, max Time interval between two advertisement. - * A range is provided to the LE subsystem so it can adjust the advertising + * @param[in] min, max Time interval between two advertisements. + * A range is provided to the LE subsystem, so it can adjust the advertising * interval with other transmission happening on the BLE radio. * * @return reference to this object. @@ -218,7 +218,7 @@ public: } /** Set which channels are to be used for primary advertising. - * At least must be used. If all are set to disabled all channels will be used. + * At least must be used. If all are set to disabled, all channels will be used. * * @param channel37 Use channel 37. * @param channel38 Use channel 38. @@ -446,7 +446,7 @@ public: /** Use legacy PDU during advertising. * - * @param enable If true legacy PDU will be used. + * @param enable If true, legacy PDU will be used. * * @return A reference to this object. */ @@ -467,7 +467,7 @@ public: /** Set if TX power should be included in the header. * - * @param enable If true include the TX power in the header. + * @param enable If true, include the TX power in the header. * * @return A reference to this object. */ From 2e02869173fb4e8abbde6e6cb9554041b52dbdd6 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:40:55 -0600 Subject: [PATCH 354/361] Edit ConnectionParameters.h Edit file, mostly for agreement. --- .../ble/gap/ConnectionParameters.h | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h index 5aecd15527..d93052a48f 100644 --- a/features/FEATURE_BLE/ble/gap/ConnectionParameters.h +++ b/features/FEATURE_BLE/ble/gap/ConnectionParameters.h @@ -32,18 +32,18 @@ namespace ble { /** * Parameters defining the connection initiation process. * - * The connection initiation process is divided in two different phases. First - * the initiating device scan for the peer it should connect. Once the peer has - * been found, it sends a connection request that contains the connection + * The connection initiation process is divided in two different phases. First, + * the initiating device scans for the peer to which it should connect. Once it finds + * the peer, it sends a connection request that contains the connection * parameters. * * @par Scan parameters * * The scan parameters are defined by two durations: the scan interval and the - * scan window. The scan interval is the duration between two scan cycle and the - * scan window defines how long the device search during a scan cycle. + * scan window. The scan interval is the duration between two scan cycles, and the + * scan window defines how long the device searches during a scan cycle. * - * The scan window and the scan interval can be set at construction time or by + * You can set the scan window and the scan interval at construction time or by * calling setScanParameters(). * * @par Connection parameters @@ -58,32 +58,32 @@ namespace ble { * if the connected devices haven't exchanged a single packet. It is important * to note that even if the application doesn't send actual data, the Bluetooth * controller takes care of sending empty data packets to maintain the - * connection alive. + * connection. * - * These parameters can be set at construction time or by calling the function + * You can set these parameters at construction time or by calling the function * setConnectionParameters(). * * @par PHY * - * Bluetooth 5 have introduced the support of different physical layer to either - * increase the range or the throughput. Multiple PHY can be configured + * Bluetooth 5 has introduced the support of different physical layer to either + * increase the range or the throughput. You can configure multiple PHY * independently for scanning and connecting. * * Legacy connection happens on the 1M PHY (phy_t::LE_1M). It is the only PHY - * that can be configured on legacy systems. + * that you can configure on legacy systems. * * The constructor, setScanParameters() and setConnectionParameters() accept * a phy_t parameter that defines to which PHY the parameters set applies. * * @par Other parameters: * - * It is possible to defined what type of address is used to establish the - * connection and whether or not if the whitelist should be used to find the peer + * It is possible to define what type of address is used to establish the + * connection and whether the whitelist should be used to find the peer * to connect to. * * @par Example: * - * Thanks to the fluent API it is easy to compose the connection parameters at + * Thanks to the fluent API, you can compose the connection parameters at * instantiation point: * * @code @@ -137,9 +137,9 @@ public: * @param maxConnectionInterval Maximum value of the connection interval. * @param slaveLatency Maximum number of packets the slave can drop. * @param connectionSupervisionTimeout Time after which the connection is - * considered lost if no data exchanged have taken place. + * considered lost if no data has been exchanged. * @param minEventLength Minimum duration of a connection event. - * @param maxEventLength Maximum duration of a connection event + * @param maxEventLength Maximum duration of a connection event. */ ConnectionParameters( phy_t phy = phy_t::LE_1M, @@ -162,7 +162,7 @@ public: * @param scanInterval Interval between two scans. * @param scanWindow Scan duration within a scan interval. * - * @note It is useless to configure the 2M PHY as it is not used during + * @note It is useless to configure the 2M PHY because it is not used during * scanning. * * @return A reference to this. @@ -181,7 +181,7 @@ public: * @param maxConnectionInterval Maximum connection interval. * @param slaveLatency Maximum number of packets the slave can drop. * @param connectionSupervisionTimeout Time after which the connection is - * considered lost if no data exchanged have taken place. + * considered lost if no data has been exchanged. * @param minEventLength Minimum duration of a connection event. * @param maxEventLength Maximum duration of a connection event. * @@ -223,7 +223,7 @@ public: } /** - * Enable or disable phys. + * Enable or disable PHYs. * * @param phy1M true to enable the 1M PHY and false to disable it. * @param phy2M true to enable the 2M PHY and false to disable it. @@ -312,7 +312,7 @@ public: return set; } - /* these return pointers to arrays of settings valid only across the number of active PHYs */ + /* These return pointers to arrays of settings valid only across the number of active PHYs */ const uint16_t *getScanIntervalArray() const { @@ -366,15 +366,15 @@ private: } else if (_enabledPhy[LE_CODED_INDEX]) { return LE_CODED_INDEX; } - /* this should never happen, it means you were trying to start a connection with a blank set - * of paramters - you need to enabled at least one PHY */ + /* This should never happen; it means you were trying to start a connection with a blank set + * of parameters - you need to enable at least one PHY */ MBED_ASSERT("Trying to use connection parameters without any PHY defined."); return 0; } /** Handle toggling PHYs on and off and return the correct index to use to set the configuration elements. * - * @param phy Which PHY is being toggle. + * @param phy Which PHY is being toggled. * @param enable On or Off. * @return The index to the array of settings. */ @@ -393,7 +393,7 @@ private: } if (is_swapped && index == LE_CODED_INDEX) { - /* to keep the data contiguous coded params are in place of the missing 2M params */ + /* To keep the data contiguous, coded params are in place of the missing 2M params */ index = LE_2M_INDEX; } From b4c34557d9ab405be1b856273b87c3bc8001292b Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 18:47:49 -0600 Subject: [PATCH 355/361] Edit Events.h Edit file for person, capitalization and to fix typos. --- features/FEATURE_BLE/ble/gap/Events.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Events.h b/features/FEATURE_BLE/ble/gap/Events.h index 369e45ae61..3c09137517 100644 --- a/features/FEATURE_BLE/ble/gap/Events.h +++ b/features/FEATURE_BLE/ble/gap/Events.h @@ -39,7 +39,7 @@ namespace ble { struct AdvertisingReportEvent { #if !defined(DOXYGEN_ONLY) - /** Create a advertising report event. + /** Create an advertising report event. * * @param type Type of advertising used. * @param peerAddressType Peer address type of advertiser. @@ -173,7 +173,7 @@ private: }; /** - * Event generated when a connection initiation end (successfully or not). + * Event generated when a connection initiation ends (successfully or not). * * @see ble::Gap::EventHandler::onConnectionComplete(). */ @@ -304,7 +304,7 @@ private: }; /** - * Event generated when we first receive a periodic advertisement. + * Event generated when you first receive a periodic advertisement. * * @see ble::Gap::EventHandler::onPeriodicAdvertisingSyncEstablished(). */ @@ -763,7 +763,7 @@ struct ConnectionParametersUpdateCompleteEvent { #endif /** - * Get The status of the operation. It is equal to BLE_ERROR_NONE in case of + * Get the status of the operation. It is equal to BLE_ERROR_NONE in case of * success. */ ble_error_t getStatus() const From 431402c14d8417c3c2251e1ecd351744fe595e20 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 19:08:41 -0600 Subject: [PATCH 356/361] Edit Gap.h Edit most of file, mostly for U.S. spelling and typos. --- features/FEATURE_BLE/ble/gap/Gap.h | 94 +++++++++++++++--------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Gap.h b/features/FEATURE_BLE/ble/gap/Gap.h index 7c1fc6fe38..ecf281fc1b 100644 --- a/features/FEATURE_BLE/ble/gap/Gap.h +++ b/features/FEATURE_BLE/ble/gap/Gap.h @@ -79,26 +79,26 @@ namespace ble { * with a scan response packet containing additional information. * * Advertising parameters are updated using setAdvertisingParams(). The main - * advertising payload is updated using setAdvertisingPayload() and the scan response - * is updated using setAdvertisingScanResponse(). If the advertising is already active - * updated the data will take effect from the next advertising event. + * advertising payload is updated using setAdvertisingPayload(), and the scan response + * is updated using setAdvertisingScanResponse(). If the advertising is already + * updated, the data will take effect from the next advertising event. * - * To create a valid advertising payload and scan response you may use + * To create a valid advertising payload and scan response, you may use * AdvertisingDataBuilder. You must first allocate memory and create an mbed::Span and - * pass that into the AdvertisingDataBuilder which will only be able to add as much - * data as fits in the provided buffer. The builder will accept any size of the buffer - * but for the created data to be usable it must be smaller than the maximum data + * pass that into the AdvertisingDataBuilder, which will only be able to add as much + * data as fits in the provided buffer. The builder accepts any size of the buffer, + * but for the created data to be usable, it must be smaller than the maximum data * length returned from getMaxAdvertisingDataLength(). * - * Another option is to use AdvertisingDataSimpleBuilder that allocates memory + * Another option is to use AdvertisingDataSimpleBuilder, which allocates memory * on the stack and offers a fluent interface at the expense of a reduced set of * APIs and error management options. * - * @note Prior to Bluetooth 5; advertising and scanning payload size were limited - * to LEGACY_ADVERTISING_MAX_SIZE. It changed with Bluetooth 5 and now the maximum + * @note Prior to Bluetooth 5, advertising and scanning payload size were limited + * to LEGACY_ADVERTISING_MAX_SIZE. It changed with Bluetooth 5, and now the maximum * size of data that can be advertised depends on the controller. If you wish - * to be compatible with older devices you may wish to advertise with the - * LEGACY_ADVERTISING_HANDLE and uses payloads no larger than LEGACY_ADVERTISING_MAX_SIZE + * to be compatible with older devices, you may wish to advertise with the + * LEGACY_ADVERTISING_HANDLE. This uses payloads no larger than LEGACY_ADVERTISING_MAX_SIZE * with that advertising set. * * @par Extended advertising @@ -111,14 +111,14 @@ namespace ble { * regular advertising channels and the rest of the 37 channels normally used by * connected devices. * - * The 3 channels used in legacy advertising are called Primary Advertisement channels. + * The 3 channels used in legacy advertising are called primary advertisement channels. * The remaining 37 channels are used for secondary advertising. Unlike sending data - * during a connection this allows the device to broadcast data to multiple devices. + * during a connection, this allows the device to broadcast data to multiple devices. * - * The advertising starts on the Primary channels (which you may select) and continues - * on the secondary channels as indicated in the packet sent on the Primary channel. - * This way the advertising can send large payloads without saturating the advertising - * channels. Primary channels are limited to 1M and coded PHYs but Secondary channels + * The advertising starts on the primary channels (which you may select) and continues + * on the secondary channels as indicated in the packet sent on the primary channel. + * This way, the advertising can send large payloads without saturating the advertising + * channels. Primary channels are limited to 1M and coded PHYs, but secondary channels * may use the increased throughput 2M PHY. * * @par Periodic advertising @@ -126,9 +126,9 @@ namespace ble { * Similarly, you can use periodic advertising to transfer regular data to multiple * devices. * - * The advertiser will use primary channels to advertise the information needed to + * The advertiser uses primary channels to advertise the information needed to * listen to the periodic advertisements on secondary channels. This sync information - * will be used by the scanner who can now optimise for power consumption and only + * will be used by the scanner who can now optimize for power consumption and only * listen for the periodic advertisements at specified times. * * Like extended advertising, periodic advertising offers extra PHY options of 2M @@ -140,29 +140,29 @@ namespace ble { * Advertisers may advertise multiple payloads at the same time. The configuration * and identification of these is done through advertising sets. Use a handle * obtained from createAvertisingSet() for advertising operations. After ending - * all advertising operations you should remove the handle from the system using + * all advertising operations, remove the handle from the system using * destroyAdvertisingHandle(). * - * Extended advertising and periodic advertising is an optional feature and not all - * devices support it and will only be able to see the now called legacy advertising. + * Extended advertising and periodic advertising is an optional feature, and not all + * devices support it. Some will only be able to see the now-called legacy advertising. * - * Legacy advertising is available through a special handle LEGACY_ADVERTISING_HANDLE. - * This handle is always available and doesn't need to be created and cannot be + * Legacy advertising is available through a special handle, LEGACY_ADVERTISING_HANDLE. + * This handle is always available, doesn't need to be created and can't be * destroyed. * - * There is a limited number of advertising sets available since they require support + * There is a limited number of advertising sets available because they require support * from the controller. Their availability is dynamic and may be queried at any time * using getMaxAdvertisingSetNumber(). Advertising sets take up resources even if - * they are not actively advertising right now so it's important to destroy the set + * they are not actively advertising right now, so it's important to destroy the set * when you're done with it (or reuse it in the next advertisement). * * Periodic advertising and extended advertising share the same set but not the same - * data. Periodic advertising synchronization information are carried out by - * extended advertising therefore to let other devices be aware that your device - * exposes periodic advertising you should start extended advertising of the set. - * Subsequently you may disable extended advertising and the periodic advertising + * data. Extended advertising carries out periodic advertising synchronization + * information. Therefore, to let other devices be aware that your device + * exposes periodic advertising, you should start extended advertising of the set. + * Subsequently, you may disable extended advertising, and the periodic advertising * will continue. If you start periodic advertising while extended advertising is - * inactive, periodic advertising will not start until you start extended advertising + * inactive, periodic advertising won't start until you start extended advertising * at a later time. * * @par Privacy @@ -170,34 +170,34 @@ namespace ble { * Privacy is a feature that allows a device to avoid being tracked by other * (untrusted) devices. The device achieves it by periodically generating a * new random address. The random address may be a resolvable random address, - * enabling trusted devices to recognise it as belonging to the same + * enabling trusted devices to recognize it as belonging to the same * device. These trusted devices receive an Identity Resolution Key (IRK) * during pairing. This is handled by the SecurityManager and relies on the * other device accepting and storing the IRK. * - * Privacy needs to be enabled by calling enablePrivacy() after having - * initialised the SecurityManager since privacy requires SecurityManager - * to handle IRKs. The behaviour of privacy enabled devices is set by - * using setCentralPrivacyConfiguration() which specifies what the device + * You need to enable privacy by calling enablePrivacy() after having + * initialized the SecurityManager because privacy requires SecurityManager + * to handle IRKs. The behavior of privacy enabled devices is set by + * using setCentralPrivacyConfiguration(), which specifies what the device * should be with devices using random addresses. Random addresses - * generated by privacy enabled device can be of two types: resolvable + * generated by privacy enabled devices can be of two types: resolvable * (by devices who have the IRK) and unresolvable. Unresolvable addresses - * can't be used for connecting and connectable advertising therefore a + * can't be used for connecting and connectable advertising. Therefore, a * resolvable one will be used for these regardless of the privacy * configuration. * * @par Scanning * - * Scanning consist of listening for peer advertising packets. From a scan, a + * Scanning consists of listening for peer advertising packets. From a scan, a * device can identify devices available in its environment. * * If the device scans actively, then it will send scan request to scannable - * advertisers and collect their scan response. + * advertisers and collect their scan responses. * - * Scanning is done by creating ScanParameters and applying then with - * setScanParameters(). One configure you may call startScan(). + * Scanning is done by creating ScanParameters and applying them with + * setScanParameters(). One configured, you may call startScan(). * - * When a scanning device receives an advertising packet it will call + * When a scanning device receives an advertising packet, it will call * onAdvertisingReport() in the registered event handler. A whitelist may be used * to limit the advertising reports by setting the correct policy in the scan * parameters. @@ -740,7 +740,7 @@ public: */ virtual ble_error_t stopScan(); - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + /** Synchronize with periodic advertising from an advertiser and begin receiving periodic * advertising packets. * * @param peerAddressType Peer address type. @@ -769,7 +769,7 @@ public: sync_timeout_t timeout ); - /** Synchronise with periodic advertising from an advertiser and begin receiving periodic + /** Synchronize with periodic advertising from an advertiser and begin receiving periodic * advertising packets. Use periodic advertising sync list to determine who to sync with. * * @param maxPacketSkip Number of consecutive periodic advertising packets that the receiver @@ -1113,7 +1113,7 @@ public: * @par Default configuration of peripheral role * * By default private resolvable addresses are used for all procedures; - * including advertisement of non connectable packets. Connection request + * including advertisement of nonconnectable packets. Connection request * from an unknown initiator with a private resolvable address triggers the * pairing procedure. * From 08ef3f7209e3b3b978349dc1e73bd48f7474103b Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 19:14:14 -0600 Subject: [PATCH 357/361] Edit iBeacon.h Add commas between two independent clauses joined by a coordinating conjunction. --- features/FEATURE_BLE/ble/services/iBeacon.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/features/FEATURE_BLE/ble/services/iBeacon.h b/features/FEATURE_BLE/ble/services/iBeacon.h index ba5b1b2560..bed6d13eae 100644 --- a/features/FEATURE_BLE/ble/services/iBeacon.h +++ b/features/FEATURE_BLE/ble/services/iBeacon.h @@ -82,11 +82,11 @@ * * @note More information at https://developer.apple.com/ibeacon/Getting-Started-with-iBeacon.pdf * - * @deprecated This service is deprecated and no replacement is currently available. + * @deprecated This service is deprecated, and no replacement is currently available. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11", - "This service is deprecated and no replacement is currently available." + "This service is deprecated, and no replacement is currently available." ) class iBeacon { @@ -204,11 +204,11 @@ public: * * @param[in] compID ID of the beacon manufacturer. * - * @deprecated This service is deprecated and no replacement is currently available. + * @deprecated This service is deprecated, and no replacement is currently available. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11", - "This service is deprecated and no replacement is currently available." + "This service is deprecated, and no replacement is currently available." ) iBeacon( BLE &_ble, From fa784c2aff545a660ee15ee6fcc0f6d9c2c41e88 Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 19:15:31 -0600 Subject: [PATCH 358/361] Edit URIBeaconCOnfigService.h Edit file for active voice and comma use. --- .../FEATURE_BLE/ble/services/URIBeaconConfigService.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h index 56b0ce2920..ba27c4b434 100644 --- a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h +++ b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h @@ -40,14 +40,14 @@ extern const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)]; /** * @class URIBeaconConfigService - * @brief UriBeacon Configuration Service. Can be used to set URL, adjust power levels, and set flags. + * @brief UriBeacon Configuration Service. You can use this to set URL, adjust power levels and set flags. * See http://uribeacon.org * - * @deprecated This service is deprecated and no replacement is currently available. + * @deprecated This service is deprecated, and no replacement is currently available. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11", - "This service is deprecated and no replacement is currently available." + "This service is deprecated, and no replacement is currently available." ) class URIBeaconConfigService { public: @@ -95,11 +95,11 @@ class URIBeaconConfigService { * @param[in] defaultAdvPowerLevelsIn * Default power-levels array. Applies only if the resetToDefaultsFlag is true. * - * @deprecated This service is deprecated and no replacement is currently available. + * @deprecated This service is deprecated, and no replacement is currently available. */ MBED_DEPRECATED_SINCE( "mbed-os-5.11", - "This service is deprecated and no replacement is currently available." + "This service is deprecated, and no replacement is currently available." ) URIBeaconConfigService(BLE &bleIn, Params_t ¶msIn, From d00ad8bc964ae6c008c4a9c4564dad9a130b324b Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 19:18:24 -0600 Subject: [PATCH 359/361] Edit ScanParameters.h Edit file, mostly to fix typos. --- features/FEATURE_BLE/ble/gap/ScanParameters.h | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/ScanParameters.h b/features/FEATURE_BLE/ble/gap/ScanParameters.h index e20db6aa85..494cc818f6 100644 --- a/features/FEATURE_BLE/ble/gap/ScanParameters.h +++ b/features/FEATURE_BLE/ble/gap/ScanParameters.h @@ -44,8 +44,8 @@ namespace ble { * requests to the advertiser that respond with a scan response. It is possible * to select what type of address is used to issue the scan request. * - * With Bluetooth 5, devices can advertise on more physical channels and by - * extension they can scan on more physical channel. It is possible to define + * With Bluetooth 5, devices can advertise on more physical channels, and by + * extension, they can scan on more physical channels. It is possible to define * independent scan parameters for every scannable physical channel. */ class ScanParameters { @@ -58,7 +58,7 @@ public: /** * Construct a phy_configuration_t. * @param scan_interval The scan interval. - * @param scan_window The scan window + * @param scan_window The scan window. * @param active_scanning True if scan request should be sent and false * otherwise. */ @@ -107,12 +107,12 @@ public: }; /** - * Construct a ScanParameters object that operate on a selected phy. + * Construct a ScanParameters object that operates on a selected PHY. * * @param phy The phy to configure. * @param scan_interval The scan interval. * @param scan_window The scan window. - * @param active_scanning active scanning flag + * @param active_scanning active scanning flag. * @param own_address_type Address type used in scan requests. * @param scanning_filter_policy Filter applied. */ @@ -159,7 +159,7 @@ public: /** * Set the filter to apply during scanning. - * @param filter_policy The filter to apply during scannong. + * @param filter_policy The filter to apply during scanning. * @return A reference to this object. */ ScanParameters &setFilter(scanning_filter_policy_t filter_policy) @@ -177,7 +177,7 @@ public: } /** - * Enable or disable phys that should be used during scanning . + * Enable or disable PHYs that should be used during scanning. * @param enable_1m True to enable the 1M phy and false to disable it. * @param enable_coded True to enable the coded phy and false to disable it. * @return A reference to this object. @@ -190,7 +190,7 @@ public: } /** - * Get the phys to use during scanning. + * Get the PHYs to use during scanning. */ phy_set_t getPhys() const { @@ -226,7 +226,7 @@ public: } /** - * Set the coded phy scan configuration. + * Set the coded PHY scan configuration. * @param interval The scan interval to use. * @param window The scan window to use. * @param active_scanning The active scanning flag. @@ -246,7 +246,7 @@ public: } /** - * Get the coded phy scan configuration. + * Get the coded PHY scan configuration. */ phy_configuration_t getCodedPhyConfiguration() const { From bbb67a69c8b28bee7fadfeb1de1172277a5322ed Mon Sep 17 00:00:00 2001 From: Amanda Butler Date: Mon, 26 Nov 2018 19:35:43 -0600 Subject: [PATCH 360/361] Edit Types.h Edit file. --- features/FEATURE_BLE/ble/gap/Types.h | 64 ++++++++++++++-------------- 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/features/FEATURE_BLE/ble/gap/Types.h b/features/FEATURE_BLE/ble/gap/Types.h index 21c50d7713..59f07ba91b 100644 --- a/features/FEATURE_BLE/ble/gap/Types.h +++ b/features/FEATURE_BLE/ble/gap/Types.h @@ -33,7 +33,7 @@ namespace ble { /* BLE units, using microseconds as the common denominator */ /** - * Time interval between two advertisement. + * Time interval between two advertisements. * * The duration is in unit of 625µs and ranges from 0x20 to 0xFFFFFF . * @@ -68,16 +68,16 @@ typedef Duration, /* forever */ Value > scan_period_t; /** - * Time interval between two scan. + * Time interval between two scans. * - * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF . + * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF. */ typedef Duration > scan_interval_t; /** * Duration of a scan. * - * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF . + * The duration is in unit of 625µs and ranges from 0x04 to 0xFFFF. */ typedef Duration > scan_window_t; @@ -105,15 +105,15 @@ typedef Duration > supervision_timeout_t; typedef Duration > conn_event_length_t; /** - * Time after which a periodic sync link is considered loss if the receiver hasn't - * receive anything from the advertiser. + * Time after which a periodic sync link is considered lost if the receiver hasn't + * received anything from the advertiser. * * The duration is in unit of 10 milliseconds and ranges from 0x0A to 0x4000. */ typedef Duration > sync_timeout_t; /** - * Interval between two periodic advertsising events. + * Interval between two periodic advertising events. * * The duration is in unit of 1.250ms and ranges from 0x06 to 0xFFFF. */ @@ -143,7 +143,7 @@ typedef uint16_t periodic_sync_handle_t; /** * Encapsulates the peripheral advertising modes. * - * It determine how the device appears to other scanner and peripheral + * It determines how the device appears to other scanner and peripheral * devices in the scanning range. */ struct advertising_type_t : SafeEnum { @@ -211,7 +211,7 @@ struct advertising_data_status_t : SafeEnum enum type { COMPLETE = 0x00, /// Advertising payload complete. INCOMPLETE_MORE_DATA = 0x01, /// Partial advertising payload, more to come. - INCOMPLETE_DATA_TRUNCATED = 0x02 /// Advertising payload incomplete and no more is coming. + INCOMPLETE_DATA_TRUNCATED = 0x02 /// Advertising payload incomplete, and no more is coming. }; /** @@ -370,8 +370,8 @@ typedef int8_t rssi_t; /** * Describe the advertising power. * - * Value comprised between -127 and +126 are considered power values in dBm while - * the special value 127 can be used as a wildcard to indicates that the host + * Values between -127 and +126 are considered power values in dBm while + * the special value 127 can be used as a wildcard to indicate that the host * has no preference or if the power information is not available. */ typedef int8_t advertising_power_t; @@ -392,18 +392,18 @@ struct advertising_filter_policy_t : SafeEnum { /// enumeration of scanning_filter_policy_t values enum type { /** - * Accept all advertising packets except directed advertising packet not + * Accept all advertising packets except directed advertising packets not * addressed to this device. */ NO_FILTER = 0x00, /** * Accept only advertising packets from devices in the whitelist except - * directed advertising packet not addressed to this device. + * directed advertising packets not addressed to this device. */ FILTER_ADVERTISING = 0x01, @@ -449,9 +449,9 @@ struct scanning_filter_policy_t : SafeEnum { /** * Accept all advertising packets except: - * - advertising packets where the advertiser's - * identity address is not in the White List, - * - directed advertising packets where the initiator's identity address + * - Advertising packets where the advertiser's + * identity address is not in the whitelist. + * - Directed advertising packets where the initiator's identity address * does not address this device. * * @note Directed advertising packets where the initiator's address is a @@ -471,7 +471,7 @@ struct scanning_filter_policy_t : SafeEnum { }; /** - * Filter policy which can be used during connection initiation. + * Filter policy that you can use during connection initiation. */ struct initiator_filter_policy_t : SafeEnum { /// enumeration of initiator_filter_policy_t values. @@ -482,7 +482,7 @@ struct initiator_filter_policy_t : SafeEnum NO_FILTER, /** - * Whitelist is used to determine which advertiser to connect to. + * The whitelist is used to determine which advertiser to connect to. */ USE_WHITE_LIST }; @@ -515,7 +515,7 @@ struct duplicates_filter_t : SafeEnum { ENABLE, /** - * Enable duplicate filtering, reset the cache periodically. + * Enable duplicate filtering, and reset the cache periodically. */ PERIODIC_RESET }; @@ -573,7 +573,7 @@ struct own_address_type_t : SafeEnum { /** * Type of an address to connect to. * - * It is used to connect to a device directly of with directed advertising. + * It is used to connect to a device directly with directed advertising. */ struct target_peer_address_type_t : SafeEnum { /// enumeration of target_peer_address_type_t values. @@ -710,7 +710,7 @@ struct connection_role_t : SafeEnum { /** * Peripheral Role. * - * The device can advertise and it can be connected by a central. It + * The device can advertise, and you can connect it by a central. It * acts as a slave when connected. * * @note A peripheral is a broadcaster. @@ -767,7 +767,7 @@ struct local_disconnection_reason_t : SafeEnum { */ struct peripheral_privacy_configuration_t { /** - * Indicates if non resolvable random address should be used when the - * peripheral advertises non connectable packets. + * Indicates if nonresolvable random address should be used when the + * peripheral advertises nonconnectable packets. * * Resolvable random address continues to be used for connectable packets. */ @@ -873,7 +873,7 @@ struct peripheral_privacy_configuration_t { /** * If a bond is present in the secure database and the address - * resolution fail then reject the connection request with the error + * resolution fails, then reject the connection request with the error * code AUTHENTICATION_FAILLURE. */ REJECT_NON_RESOLVED_ADDRESS, @@ -899,17 +899,17 @@ struct peripheral_privacy_configuration_t { }; /** - * Privacy Configuration of the central role. + * Privacy configuration of the central role. * * @note This configuration is also used when the local device operates as * an observer. */ struct central_privay_configuration_t { /** - * Indicates if non resolvable random address should be used when the + * Indicates if nonresolvable random address should be used when the * central or observer sends scan request packets. * - * Resolvable random address continue to be used for connection requests. + * Resolvable random address continues to be used for connection requests. */ bool use_non_resolvable_random_address; @@ -932,7 +932,7 @@ struct central_privay_configuration_t { RESOLVE_AND_FORWARD, /** - * Filter out packets containing a resolvable that cannot be resolved + * Filter out packets containing a resolvable address that cannot be resolved * by this device. * * @note Filtering is applied if the local device contains at least From 6677fab856223c53a289c25ee908293c6124dd36 Mon Sep 17 00:00:00 2001 From: Vincent Coubard Date: Tue, 27 Nov 2018 09:12:28 +0000 Subject: [PATCH 361/361] BLE: Move source/Gap.cpp -> source/LegacyGap.cpp --- features/FEATURE_BLE/source/{Gap.cpp => LegacyGap.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename features/FEATURE_BLE/source/{Gap.cpp => LegacyGap.cpp} (100%) diff --git a/features/FEATURE_BLE/source/Gap.cpp b/features/FEATURE_BLE/source/LegacyGap.cpp similarity index 100% rename from features/FEATURE_BLE/source/Gap.cpp rename to features/FEATURE_BLE/source/LegacyGap.cpp