diff --git a/features/FEATURE_BLE/ble/BLE.h b/features/FEATURE_BLE/ble/BLE.h index db5eb41baaf..1329a205d72 100644 --- a/features/FEATURE_BLE/ble/BLE.h +++ b/features/FEATURE_BLE/ble/BLE.h @@ -421,1539 +421,18 @@ class BLE { */ static const char *errorToString(ble_error_t error); - /* - * Deprecation alert! - * All of the following are deprecated and may be dropped in a future - * release. Documentation should refer to alternative APIs. - */ -public: +private: + friend class BLEInstanceBase; + /** * Constructor for a handle to a BLE instance (the BLE stack). BLE handles * are thin wrappers around a transport object (that is, ptr. to * BLEInstanceBase). * * @param[in] instanceID BLE Instance ID to get. - * - * It is better to create BLE objects as singletons accessed through the - * Instance() method. If multiple BLE handles are constructed for the same - * interface (using this constructor), they share the same underlying - * transport object. - * - * @deprecated Use the Instance() function instead of the constructor. */ - MBED_DEPRECATED("Use BLE::Instance() instead of BLE constructor.") BLE(InstanceID_t instanceID = DEFAULT_INSTANCE); - /** - * Yield control to the BLE stack or to other tasks waiting for events. - * - * This is a sleep function that returns when there is an application-specific - * interrupt. This is not interchangeable with WFE() considering that the - * MCU might wake up several times to service the stack before returning - * control to the caller. - * - * @deprecated This function blocks the CPU. Use the pair - * onEventsToProcess() and processEvents(). - */ - MBED_DEPRECATED("Use BLE::processEvents() and BLE::onEventsToProcess().") - void waitForEvent(void); - - /** - * Set the BTLE MAC address and type. - * - * @param[in] type Type of the address to set. - * @param[in] address Value of the address to set. It is ordered in - * little endian. - * - * @return BLE_ERROR_NONE on success. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::setAddress(). A former call to ble.setAddress(...) should be - * replaced with ble.gap().setAddress(...). - */ - MBED_DEPRECATED("Use ble.gap().setAddress(...)") - ble_error_t setAddress( - BLEProtocol::AddressType_t type, - const BLEProtocol::AddressBytes_t address - ); - - /** - * Fetch the Bluetooth Low Energy MAC address and type. - * - * @param[out] typeP Type of the current address set. - * @param[out] address Value of the current address. - * - * @return BLE_ERROR_NONE on success. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::getAddress(). A former call to ble.getAddress(...) should be - * replaced with ble.gap().getAddress(...). - */ - MBED_DEPRECATED("Use ble.gap().getAddress(...)") - ble_error_t getAddress( - BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address - ) - { - return gap().getAddress(typeP, address); - } - -#if BLE_ROLE_BROADCASTER - /** - * Set the GAP advertising mode to use for this device. - * - * @param[in] advType New type of advertising to use. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setAdvertisingType(). A former call to - * ble.setAdvertisingType(...) should be replaced with - * ble.gap().setAdvertisingType(...). - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingType(...)") - void setAdvertisingType(GapAdvertisingParams::AdvertisingType 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 more power being used by the radio - * due to the higher data transmit rate. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setAdvertisingInterval(). A former call to - * ble.setAdvertisingInterval(...) should be replaced with - * ble.gap().setAdvertisingInterval(...). - * - * @note WARNING: This API previously used 0.625ms as the unit for its - * 'interval' argument. That required an explicit conversion from - * milliseconds using Gap::MSEC_TO_GAP_DURATION_UNITS(). This conversion is - * no longer required as the new units are milliseconds. Any application - * code depending on the old semantics needs to be updated accordingly. - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingInterval(...)") - void setAdvertisingInterval(uint16_t interval); - - /** - * Get the minimum advertising interval in milliseconds, which can be used - * for connectable advertising types. - * - * @return Minimum Advertising interval in milliseconds. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::getMinAdvertisingInterval(). A former call to - * ble.getMinAdvertisingInterval(...) should be replaced with - * ble.gap().getMinAdvertisingInterval(...). - */ - MBED_DEPRECATED("Use ble.gap().getMinAdvertisingInterval(...)") - uint16_t getMinAdvertisingInterval(void) const - { - return gap().getMinAdvertisingInterval(); - } - - /** - * Get the minimum advertising interval in milliseconds, which can be - * used for nonconnectable advertising type. - * - * @return Minimum Advertising interval in milliseconds for nonconnectible mode. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::MinNonConnectableAdvertisingInterval(). A former call to - * ble.getMinNonConnectableAdvertisingInterval(...) should be replaced with - * ble.gap().getMinNonConnectableAdvertisingInterval(...). - */ - MBED_DEPRECATED("Use ble.gap().getMinNonConnectableAdvertisingInterval(...)") - uint16_t getMinNonConnectableAdvertisingInterval(void) const - { - return gap().getMinNonConnectableAdvertisingInterval(); - } - - /** - * Get the maximum advertising interval in milliseconds. - * - * @return Maximum Advertising interval in milliseconds. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::getMaxAdvertisingInterval(). A former call to - * ble.getMaxAdvertisingInterval(...) should be replaced with - * ble.gap().getMaxAdvertisingInterval(...). - */ - MBED_DEPRECATED("Use ble.gap().getMaxAdvertisingInterval(...)") - uint16_t getMaxAdvertisingInterval(void) const - { - return gap().getMaxAdvertisingInterval(); - } - - /** - * 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 (1 - * and 16383). Use 0 to disable the advertising timeout. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setAdvertisingTimeout(). A former call to - * ble.setAdvertisingTimeout(...) should be replaced with - * ble.gap().setAdvertisingTimeout(...). - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingTimeout(...)") - void setAdvertisingTimeout(uint16_t timeout); - - /** - * Set up a particular, user-constructed set of advertisement parameters for - * the underlying stack. It would be uncommon for this API to be used - * directly; there are other APIs to tweak advertisement parameters - * individually (see above). - * - * @param[in] advParams The new advertising parameters. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setAdvertisingParams(). A former call to - * ble.setAdvertisingParams(...) should be replaced with - * ble.gap().setAdvertisingParams(...). - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingParams(...)") - void setAdvertisingParams(const GapAdvertisingParams &advParams); - - /** - * Get the current advertising parameters. - * - * @return Read back advertising parameters. Useful for storing and - * restoring parameters rapidly. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::getAdvertisingParams(). A former call to - * ble.getAdvertisingParams(...) should be replaced with - * ble.gap().getAdvertisingParams(...). - */ - MBED_DEPRECATED("Use ble.gap().getAdvertisingParams(...)") - const GapAdvertisingParams &getAdvertisingParams(void) const; - - /** - * Accumulate an AD structure in the advertising payload. Please note that - * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used - * as an additional 31 bytes if the advertising payload is too - * small. - * - * @param[in] flags - * The flags to add. Please refer to - * GapAdvertisingData::Flags for valid flags. Multiple - * flags may be specified in combination. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::accumulateAdvertisingPayload(uint8_t). A former call to - * ble.accumulateAdvertisingPayload(flags) should be replaced with - * ble.gap().accumulateAdvertisingPayload(flags). - */ - MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(flags)") - ble_error_t accumulateAdvertisingPayload(uint8_t flags); - - /** - * Accumulate an AD structure in the advertising payload. Please note that - * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used - * as an additional 31 bytes if the advertising payload is too - * small. - * - * @param[in] app - * The appearance of the peripheral. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::accumulateAdvertisingPayload(GapAdvertisingData::Appearance). - * A former call to ble.accumulateAdvertisingPayload(appearance) - * should be replaced with - * ble.gap().accumulateAdvertisingPayload(appearance). - */ - MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayload(appearance)") - ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app); - - /** - * Accumulate an AD structure in the advertising payload. Please note that - * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used - * as an additional 31 bytes if the advertising payload is too - * small. - * - * @param[in] power - * The max transmit power to be used by the controller. This - * is only a hint. - * - * @return BLE_ERROR_NONE if the data was successfully added to the - * advertising payload. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::accumulateAdvertisingPayloadTxPower(). A former call to - * ble.accumulateAdvertisingPayloadTxPower(txPower) should be replaced with - * ble.gap().accumulateAdvertisingPayloadTxPower(txPower). - */ - MBED_DEPRECATED("Use ble.gap().accumulateAdvertisingPayloadTxPower(...)") - ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power); - - /** - * Accumulate a variable length byte-stream as an AD structure in the - * advertising payload. Please note that the payload is limited to 31 bytes. - * The SCAN_RESPONSE message may be used as an additional 31 bytes if the - * advertising payload is too small. - * - * @param type The type that describes the variable length data. - * @param data Data bytes. - * @param len Data length. - * - * @return BLE_ERROR_NONE if the advertisement payload was updated based on - * matching AD type; otherwise, an appropriate error. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::accumulateAdvertisingPayload(GapAdvertisingData::DataType, const uint8_t, uint8_t). - * A former call to ble.accumulateAdvertisingPayload(...) should - * 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); - - /** - * Set up a particular, user-constructed advertisement payload for the - * underlying stack. It would be uncommon for this API to be used directly; - * there are other APIs to build an advertisement payload (see above). - * - * @param[in] advData Advertising data to set. - * - * @return BLE_ERROR_NONE if the advertising data was set successfully. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::setAdvertisingData(). A former call to - * ble.setAdvertisingData(...) should be replaced with - * ble.gap().setAdvertisingPayload(...). - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingData(...)") - ble_error_t setAdvertisingData(const GapAdvertisingData &advData); - - /** - * Get a reference to the current advertising payload. - * - * @return Read back advertising data. Useful for storing and - * restoring payload. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::getAdvertisingData(). A former call to - * ble.getAdvertisingData(...) should be replaced with - * ble.gap().getAdvertisingPayload()(...). - */ - MBED_DEPRECATED("Use ble.gap().getAdvertisingData(...)") - const GapAdvertisingData &getAdvertisingData(void) const; - - /** - * Reset any advertising payload prepared from prior calls to - * accumulateAdvertisingPayload(). This automatically propagates the re- - * initialized advertising payload to the underlying stack. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::clearAdvertisingPayload(). A former call to - * ble.clearAdvertisingPayload(...) should be replaced with - * ble.gap().clearAdvertisingPayload(...). - */ - MBED_DEPRECATED("Use ble.gap().clearAdvertisingPayload(...)") - void clearAdvertisingPayload(void); - - /** - * Dynamically reset the accumulated advertising - * payload and scanResponse. The application must clear and re- - * accumulate a new advertising payload (and scanResponse) before using this - * API. - * - * @return BLE_ERROR_NONE when the advertising payload is set successfully. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::setAdvertisingPayload(). - * - * @note The new APIs in Gap update the underlying advertisement payload - * implicitly. - */ - MBED_DEPRECATED("Use ble.gap().setAdvertisingPayload(...)") - ble_error_t setAdvertisingPayload(void); - - /** - * Accumulate a variable length byte-stream as an AD structure in the - * scanResponse payload. - * - * @param[in] type The type that describes the variable length data. - * @param[in] data Data bytes. - * @param[in] len Data length. - * - * @return BLE_ERROR_NONE if the data was successfully added to the scan - * response payload. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::accumulateScanResponse(). A former call to - * ble.accumulateScanResponse(...) should be replaced with - * ble.gap().accumulateScanResponse(...). - */ - MBED_DEPRECATED("Use ble.gap().accumulateScanResponse(...)") - ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len); - - /** - * Reset any scan response prepared from prior calls to - * accumulateScanResponse(). - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::clearScanResponse(). A former call to - * ble.clearScanResponse(...) should be replaced with - * ble.gap().clearScanResponse(...). - */ - MBED_DEPRECATED("Use ble.gap().clearScanResponse(...)") - void clearScanResponse(void); - - /** - * Start advertising. - * - * @return BLE_ERROR_NONE if the advertising procedure successfully - * started. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::startAdvertising(). A former call to - * ble.startAdvertising(...) should be replaced with - * ble.gap().startAdvertising(...). - */ - MBED_DEPRECATED("Use ble.gap().startAdvertising(...)") - ble_error_t startAdvertising(void); - - /** - * Stop advertising. - * - * @return BLE_ERROR_NONE if the advertising procedure has been successfully - * stopped. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::stopAdvertising(). A former call to - * ble.stopAdvertising(...) should be replaced with - * ble.gap().stopAdvertising(...). - */ - MBED_DEPRECATED("Use ble.gap().stopAdvertising(...)") - ble_error_t stopAdvertising(void); -#endif // BLE_ROLE_BROADCASTER - -#if BLE_ROLE_OBSERVER - /** - * Set up parameters for GAP scanning (observer mode). - * - * @param[in] interval - * Scan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s]. - * @param[in] window - * Scan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s]. - * @param[in] timeout - * Scan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables timeout. - * @param[in] activeScanning - * Set to True if active-scanning is required. This is used to fetch the - * scan response from a peer if possible. - * - * @return BLE_ERROR_NONE if the scan parameters were correctly set. - * - * 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 will scan for 10 percent of the time. It is possible - * to have the interval and window set to the same value. In this case, - * scanning is continuous, with a change of scanning frequency once every - * interval. - * - * 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. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setScanParams(). A former call to - * ble.setScanParams(...) should be replaced with - * 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 - ); - - /** - * Set up the scanInterval parameter for GAP scanning (observer mode). - * - * @param[in] interval - * Scan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s]. - * - * @return BLE_ERROR_NONE if the scan interval was correctly set. - * - * 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 will scan for 10 percent of the time. It is possible - * to have the interval and window set to the same value. In this case, - * scanning is continuous, with a change of scanning frequency once every - * interval. - * - * Once the scanning parameters have been configured, scanning can be - * enabled by using startScan(). - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setScanInterval(). A former call to - * ble.setScanInterval(interval) should be replaced with - * ble.gap().setScanInterval(interval). - */ - MBED_DEPRECATED("Use ble.gap().setScanInterval(...)") - ble_error_t setScanInterval(uint16_t interval); - - /** - * Set up the scanWindow parameter for GAP scanning (observer mode). - * - * @param[in] window - * Scan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s]. - * - * @return BLE_ERROR_NONE if the scan window was correctly set. - * - * 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 will scan for 10 percent of the time. It is possible - * to have the interval and window set to the same value. In this case, - * scanning is continuous, with a change of scanning frequency once every - * interval. - * - * Once the scanning parameters have been configured, scanning can be - * enabled by using startScan(). - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setScanWindow(). A former call to - * ble.setScanWindow(window) should be replaced with - * ble.gap().setScanWindow(window). - */ - MBED_DEPRECATED("Use ble.gap().setScanWindow(...)") - ble_error_t setScanWindow(uint16_t window); - - /** - * Set up parameters for GAP scanning (observer mode). - * - * @param[in] timeout - * Scan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables timeout. - * - * @return BLE_ERROR_NONE if the scan timeout was correctly set. - * - * 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 will scan for 10 percent of the time. It is possible - * to have the interval and window set to the same value. In this case, - * scanning is continuous, with a change of scanning frequency once every - * interval. - * - * 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. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setScanTimeout(). A former call to - * ble.setScanTimeout(...) should be replaced with - * ble.gap().setScanTimeout(...). - */ - MBED_DEPRECATED("Use ble.gap().setScanTimeout(...)") - ble_error_t setScanTimeout(uint16_t timeout); - - /** - * Set up parameters for GAP scanning (observer mode). - * - * @param[in] activeScanning - * Set to True if active-scanning is required. This is used to fetch the - * scan response from a peer if possible. - * - * Once the scanning parameters have been configured, scanning can be - * enabled by using startScan(). - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::setActiveScan(). A former call to - * ble.setActiveScan(...) should be replaced with - * ble.gap().setActiveScanning(...). - */ - MBED_DEPRECATED("Use ble.gap().setActiveScan(...)") - void setActiveScan(bool activeScanning); - - /** - * Start scanning (Observer Procedure) based on the parameters currently in - * effect. - * - * @param[in] callback - * The application-specific callback to be invoked upon - * receiving every advertisement report. This can be passed in - * as NULL, in which case scanning may not be enabled at all. - * - * @return BLE_ERROR_NONE if the device successfully started the scan - * procedure. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::startScan(). A former call to - * ble.startScan(callback) should be replaced with - * ble.gap().startScan(callback). - */ - MBED_DEPRECATED("Use ble.gap().startScan(callback)") - ble_error_t startScan(void (*callback)(const Gap::AdvertisementCallbackParams_t *params)); - - /** - * 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] memberCallback 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. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::startScan(). A former call to - * ble.startScan(callback) should be replaced with - * ble.gap().startScan(object, callback). - */ - template - MBED_DEPRECATED("Use ble.gap().startScan(object, callback)") - ble_error_t startScan(T *object, void (T::*memberCallback)(const Gap::AdvertisementCallbackParams_t *params)); - - /** - * Stop scanning. The current scanning parameters remain in effect. - * - * @return BLE_ERROR_NONE if successfully stopped scanning procedure. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::stopScan(). A former call to - * ble.stopScan() should be replaced with - * ble.gap().stopScan(). - */ - MBED_DEPRECATED("Use ble.gap().stopScan()") - ble_error_t stopScan(void) - { - return gap().stopScan(); - } -#endif // BLE_ROLE_OBSERVER - -#if BLE_ROLE_CENTRAL - /** - * Create a connection (GAP Link Establishment). - * - * @param peerAddr - * 48-bit address, LSB format. - * @param peerAddrType - * Address type of the peer. - * @param connectionParams - * Connection parameters. - * @param scanParams - * Parameters to use while scanning for the peer. - * - * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The onConnection callback (if set) is invoked upon - * a connection event. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::connect(). A former call to - * ble.connect(...) should be replaced with - * 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 - ); -#endif // BLE_ROLE_CENTRAL - -#if BLE_FEATURE_CONNECTABLE - /** - * This call initiates the disconnection procedure, and its completion is - * communicated to the application with an invocation of the - * onDisconnection callback. - * - * @param[in] connectionHandle - * @param[in] reason - * The reason for disconnection; sent back to the peer. - * - * @return BLE_ERROR_NONE if the disconnection procedure successfully - * started. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * GAP::disconnect(). A former call to - * ble.disconnect(...) should be replaced with - * ble.gap().disconnect(...). - */ - MBED_DEPRECATED("Use ble.gap().disconnect(...)") - ble_error_t disconnect(Gap::Handle_t connectionHandle, Gap::DisconnectionReason_t reason); - - /** - * This call initiates the disconnection procedure, and its completion - * is communicated to the application with an invocation of the - * onDisconnection callback. - * - * @param reason - * The reason for disconnection; sent back to the peer. - * - * @return BLE_ERROR_NONE if the disconnection procedure successfully - * started. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::disconnect(). A former call to - * ble.disconnect(reason) should be replaced with - * ble.gap().disconnect(reason). - * - * @note This version of disconnect() doesn't take a connection handle. It - * works reliably only for stacks that are limited to a single - * connection. - */ - MBED_DEPRECATED("Use ble.gap().disconnect(...)") - ble_error_t disconnect(Gap::DisconnectionReason_t reason); -#endif // BLE_FEATURE_CONNECTABLE - - /** - * Returns the current Gap state of the device using a bitmask that - * describes whether the device is advertising or connected. - * - * @return The current GAP state of the device. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::getState(). A former call to - * ble.getGapState() should be replaced with - * ble.gap().getState(). - */ - MBED_DEPRECATED("Use ble.gap().getState()") - Gap::GapState_t getGapState(void) const; - -#if BLE_FEATURE_CONNECTABLE -#if BLE_FEATURE_GATT_SERVER - /** - * Get the GAP peripheral's preferred connection parameters. These are the - * defaults that the peripheral would like to have in a connection. The - * choice of the connection parameters is eventually up to the central. - * - * @param[out] params - * The structure where the parameters will be stored. The caller owns memory - * for this. - * - * @return BLE_ERROR_NONE if the parameters were successfully filled into - * the given structure pointed to by params. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::getPreferredConnectionParams(). A former call to - * ble.getPreferredConnectionParams() should be replaced with - * ble.gap().getPreferredConnectionParams(). - */ - MBED_DEPRECATED("Use ble.gap().getPreferredConnectionParams(...)") - ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params) - { - return gap().getPreferredConnectionParams(params); - } - - /** - * Set the GAP peripheral's preferred connection parameters. These are the - * defaults that the peripheral would like to have in a connection. The - * choice of the connection parameters is eventually up to the central. - * - * @param[in] params - * The structure containing the desired parameters. - * - * @return BLE_ERROR_NONE if the preferred connection parameters were set - * correctly. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setPreferredConnectionParams(). A former call to - * ble.setPreferredConnectionParams() should be replaced with - * ble.gap().setPreferredConnectionParams(). - */ - MBED_DEPRECATED("Use ble.gap().setPreferredConnectionParams(...)") - ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params) - { - return gap().setPreferredConnectionParams(params); - } -#endif // BLE_FEATURE_GATT_SERVER - - /** - * Update connection parameters while in the peripheral role. - * - * @details In the peripheral role, this will send the corresponding L2CAP request to the connected peer and wait for - * the central to perform the procedure. - * - * @param[in] handle - * Connection Handle - * @param[in] params - * Pointer to desired connection parameters. If NULL is provided on a peripheral role, - * the parameters in the PPCP characteristic of the GAP service will be used instead. - * - * @return BLE_ERROR_NONE if the connection parameters were updated correctly. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::updateConnectionParams(). A former call to - * ble.updateConnectionParams() should be replaced with - * ble.gap().updateConnectionParams(). - */ - MBED_DEPRECATED("Use ble.gap().updateConnectionParams(...)") - ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params); -#endif // BLE_FEATURE_CONNECTABLE - -#if BLE_FEATURE_GATT_SERVER - /** - * Set the device name characteristic in the Gap 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. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setDeviceName(). A former call to - * ble.setDeviceName() should be replaced with - * ble.gap().setDeviceName(). - */ - MBED_DEPRECATED("Use ble.gap().setDeviceName(...)") - ble_error_t setDeviceName(const uint8_t *deviceName) - { - return gap().setDeviceName(deviceName); - } - - /** - * Get the value of the device name characteristic in the Gap service. - * - * @param[out] deviceName - * Pointer to an empty buffer where the UTF-8 *non NULL- - * terminated* string will be placed. Set this - * value to NULL to obtain the deviceName-length - * from the 'length' parameter. - * - * @param[in,out] lengthP - * (on input) Length of the buffer pointed to by deviceName; - * (on output) the complete device name length (without the - * null terminator). - * - * @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, - * the length will return 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. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::getDeviceName(). A former call to - * ble.getDeviceName() should be replaced with - * ble.gap().getDeviceName(). - */ - MBED_DEPRECATED("Use ble.gap().getDeviceName(...)") - ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) - { - return gap().getDeviceName(deviceName, lengthP); - } - - /** - * Set 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. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setAppearance(). A former call to - * ble.setAppearance() should be replaced with - * ble.gap().setAppearance(). - */ - MBED_DEPRECATED("Use ble.gap().setAppearance(...)") - ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) - { - return gap().setAppearance(appearance); - } - - /** - * Get the appearance characteristic in the Gap service. - * - * @param[out] appearanceP - * The new value for the device-appearance. - * - * @return BLE_ERROR_NONE if the device-appearance was fetched correctly - * from the underlying BLE stack. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::getAppearance(). A former call to - * ble.getAppearance() should be replaced with - * ble.gap().getAppearance(). - */ - MBED_DEPRECATED("Use ble.gap().getAppearance(...)") - ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) - { - return gap().getAppearance(appearanceP); - } -#endif // BLE_FEATURE_GATT_SERVER - - /** - * Set the radio's transmit power. - * - * @param[in] txPower Radio transmit power in dBm. - * - * @return BLE_ERROR_NONE if the new radio's transmit power was set - * correctly. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::setTxPower(). A former call to - * ble.setTxPower() should be replaced with - * ble.gap().setTxPower(). - */ - MBED_DEPRECATED("Use ble.gap().setTxPower(...)") - ble_error_t setTxPower(int8_t txPower); - - /** - * Query the underlying stack for permitted arguments for setTxPower(). - * - * @param[out] valueArrayPP - * Out parameter to receive the immutable array of Tx values. - * @param[out] countP - * Out parameter to receive the array's size. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::getPermittedTxPowerValues(). A former call to - * ble.getPermittedTxPowerValues() should be replaced with - * ble.gap().getPermittedTxPowerValues(). - */ - MBED_DEPRECATED("Use ble.gap().getPermittedTxPowerValues(...)") - void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP); - -#if BLE_FEATURE_GATT_SERVER - /** - * Add a service declaration to the local server ATT table. Also add the - * characteristics contained within. - * - * @param[in] service The service to be added; attribute handle of services, - * characteristic and characteristic descriptors are updated by the - * process. - * - * @return BLE_ERROR_NONE if the service was successfully added. - * - * @deprecated You should use the parallel API from GattServer directly, refer to - * GattServer::addService(). A former call - * to ble.addService() should be replaced with - * ble.gattServer().addService(). - */ - MBED_DEPRECATED("Use ble.gattServer().addService(...)") - ble_error_t addService(GattService &service) - { - return gattServer().addService(service); - } - - /** - * Read the value of a characteristic from the local GattServer. - * - * @param[in] attributeHandle - * Attribute handle for the value attribute of the characteristic. - * @param[out] buffer - * A buffer to hold the value being read. - * @param[in,out] lengthP - * Length of the buffer being supplied. If the attribute - * value is longer than the size of the supplied buffer, - * this variable will return the total attribute value length - * (excluding offset). The application may use this - * information to allocate a suitable buffer size. - * - * @return BLE_ERROR_NONE if a value was read successfully into the buffer. - * - * @deprecated You should use the parallel API from GattServer directly, - * GattServer::read(GattAttribute::Handle_t,uint8_t,uint16_t). A former call - * to ble.readCharacteristicValue() should be replaced with - * ble.gattServer().read(). - */ - MBED_DEPRECATED("Use ble.gattServer().read(...)") - ble_error_t readCharacteristicValue(GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP) - { - return gattServer().read(attributeHandle, buffer, lengthP); - } - - /** - * Read the value of a characteristic from the local GattServer. - * - * @param[in] connectionHandle - * Connection Handle. - * @param[in] attributeHandle - * Attribute handle for the value attribute of the characteristic. - * @param[out] buffer - * A buffer to hold the value being read. - * @param[in,out] lengthP - * Length of the buffer being supplied. If the attribute - * value is longer than the size of the supplied buffer, - * this variable will return the total attribute value length - * (excluding offset). The application may use this - * information to allocate a suitable buffer size. - * - * @return BLE_ERROR_NONE if a value was read successfully into the buffer. - * - * @note This API is a version of the above, with an additional connection handle - * parameter to allow fetches for connection-specific multivalued - * attributes (such as the CCCDs). - * - * @deprecated You should use the parallel API from GattServer directly, refer to - * GattServer::read(Gap::Handle_t,GattAttribute::Handle_t,uint8_t,uint16_t). - * A former call to ble.readCharacteristicValue() should be replaced with - * 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 - ) - { - return gattServer().read(connectionHandle, attributeHandle, buffer, lengthP); - } - - /** - * Update the value of a characteristic on the local GattServer. - * - * @param[in] attributeHandle - * Handle for the value attribute of the characteristic. - * @param[in] value - * A pointer to a buffer holding the new value. - * @param[in] size - * Size of the new value (in bytes). - * @param[in] localOnly - * Should this update be kept on the local - * GattServer regardless of the state of the - * notify/indicate flag in the CCCD for this - * characteristic? If set to true, no notification - * or indication is generated. - * - * @return BLE_ERROR_NONE if we have successfully set the value of the attribute. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::write(GattAttribute::Handle_t,const uint8_t,uint16_t,bool). - * A former call to ble.updateCharacteristicValue() should be replaced with - * 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 - ) - { - return gattServer().write(attributeHandle, value, size, localOnly); - } - - /** - * Update the value of a characteristic on the local GattServer. A version - * of the above, with a connection handle parameter to allow updates - * for connection-specific multivalued attributes (such as the CCCDs). - * - * @param[in] connectionHandle - * Connection Handle. - * @param[in] attributeHandle - * Handle for the value attribute of the Characteristic. - * @param[in] value - * A pointer to a buffer holding the new value. - * @param[in] size - * Size of the new value (in bytes). - * @param[in] localOnly - * Should this update be kept on the local - * GattServer regardless of the state of the - * notify/indicate flag in the CCCD for this - * Characteristic? If set to true, no notification - * or indication is generated. - * - * @return BLE_ERROR_NONE if we have successfully set the value of the attribute. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::write(Gap::Handle_t,GattAttribute::Handle_t,const uint8_t,uint16_t,bool). - * A former call to ble.updateCharacteristicValue() should be replaced with - * 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 - ) - { - return gattServer().write(connectionHandle, attributeHandle, value, size, localOnly); - } -#endif // BLE_FEATURE_GATT_SERVER - -#if BLE_FEATURE_SECURITY - /** - * Enable the BLE stack's Security Manager. The Security Manager implements - * the cryptographic algorithms and protocol exchanges that allow two - * devices to securely exchange data and privately detect each other. - * Calling this API is a prerequisite for encryption and pairing (bonding). - * - * @param[in] enableBonding Allow for bonding. - * @param[in] requireMITM Require protection against man-in-the-middle attacks. - * @param[in] iocaps To specify the I/O capabilities of this peripheral, - * such as availability of a display or keyboard, to - * support out-of-band exchanges of security data. - * @param[in] passkey To specify a static passkey. - * - * @return BLE_ERROR_NONE on success. - * - * @deprecated You should use the parallel API from SecurityManager directly, refer to - * SecurityManager.init(). A former - * call to ble.initializeSecurity(...) should be replaced with - * ble.securityManager().init(...). - */ - MBED_DEPRECATED("Use ble.securityManager().init(...)") - 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); - } - - /** - * Get the security status of a connection. - * - * @param[in] connectionHandle Handle to identify the connection. - * @param[out] securityStatusP Security status. - * - * @return BLE_SUCCESS or appropriate error code indicating the reason of failure. - * - * @deprecated You should use the parallel API from SecurityManager directly, refer to - * SecurityManager::getLinkSecurity(). A former - * call to ble.getLinkSecurity(...) should be replaced with - * ble.securityManager().getLinkSecurity(...). - */ - MBED_DEPRECATED("ble.securityManager().getLinkSecurity(...)") - ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, SecurityManager::LinkSecurityStatus_t *securityStatusP) - { - return securityManager().getLinkSecurity(connectionHandle, securityStatusP); - } - - /** - * Delete all peer device context and all related bonding information from - * the database within the security manager. - * - * @retval BLE_ERROR_NONE On success; else returns an error code indicating the reason for the failure. - * @retval BLE_ERROR_INVALID_STATE If the API is called without module initialization or - * application registration. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::purgeAllBondingState(). A former - * call to ble.purgeAllBondingState() should be replaced with - * ble.securityManager().purgeAllBondingState(). - */ - MBED_DEPRECATED("ble.securityManager().purgeAllBondingState(...)") - ble_error_t purgeAllBondingState(void) - { - return securityManager().purgeAllBondingState(); - } -#endif // BLE_FEATURE_SECURITY - - /** - * Set up a callback for timeout events. Refer to Gap::TimeoutSource_t for - * possible event types. - * - * @param[in] timeoutCallback Event handler being registered. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::onTimeout(). A former call - * to ble.onTimeout(callback) should be replaced with - * ble.gap().onTimeout(callback). - */ - MBED_DEPRECATED("ble.gap().onTimeout(callback)") - void onTimeout(Gap::TimeoutEventCallback_t timeoutCallback); - -#if BLE_FEATURE_CONNECTABLE - /** - * Set up a callback for connection events. Refer to Gap::ConnectionEventCallback_t. - * - * @param[in] connectionCallback Event handler being registered. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::onConnection(). A former call - * to ble.onConnection(callback) should be replaced with - * ble.gap().onConnection(callback). - */ - MBED_DEPRECATED("ble.gap().onConnection(callback)") - void onConnection(Gap::ConnectionEventCallback_t connectionCallback); - - /** - * Append to a chain of callbacks to be invoked upon GAP disconnection. - * - * @param[in] disconnectionCallback Event handler being registered. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::onDisconnection(). A former call - * to ble.onDisconnection(callback) should be replaced with - * ble.gap().onDisconnection(callback). - */ - MBED_DEPRECATED("ble.gap().onDisconnectionComplete(callback)") - void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback); - - /** - * The same as onDisconnection() but allows an object reference and member function - * to be added to the chain of callbacks. - * - * @param[in] tptr Instance used to invoke mptr. - * @param[in] mptr Event handler being registered. - * - * @deprecated You should use the parallel API from Gap directly and refer to - * Gap::onDisconnection(). A former call - * to ble.onDisconnection(callback) should be replaced with - * ble.gap().onDisconnection(callback). - */ - template - MBED_DEPRECATED("ble.gap().onDisconnectionComplete(callback)") - void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t *)) - { - gap().onDisconnection(tptr, mptr); - } -#endif // BLE_FEATURE_CONNECTABLE - - /** - * Radio Notification is a feature that enables ACTIVE and INACTIVE - * (nACTIVE) signals from the stack. These notify the application when the - * radio is in use. The signal is sent using software interrupt. - * - * The ACTIVE signal is sent before the radio event starts. The nACTIVE - * signal is sent at the end of the radio event. These signals can be used - * by the application programmer to synchronize application logic with radio - * activity. For example, the ACTIVE signal can be used to shut off external - * devices to manage peak current drawn during periods when the radio is on, - * or to trigger sensor data collection for transmission in the radio event. - * - * @param callback - * The application handler to be invoked in response to a radio - * ACTIVE/INACTIVE event. - * - * @deprecated You should use the parallel API from Gap directly, refer to - * Gap::onRadioNotification(). A former call - * to ble.onRadioNotification(...) should be replaced with - * ble.gap().onRadioNotification(...). - */ - MBED_DEPRECATED("ble.gap().onRadioNotification(...)") - void onRadioNotification(void (*callback)(bool)); - -#if BLE_FEATURE_GATT_SERVER - /** - * Add a callback for the GATT event DATA_SENT (which is triggered when - * updates are sent out by GATT in the form of notifications). - * - * @param[in] callback Event handler being registered. - * - * @note It is possible to chain together multiple onDataSent callbacks - * (potentially from different modules of an application) to receive updates - * to characteristics. - * - * @note It is also possible to set up a callback into a member function of - * some object. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onDataSent(). A former call - * to ble.onDataSent(...) should be replaced with - * ble.gattServer().onDataSent(...). - */ - MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(void (*callback)(unsigned count)) - { - gattServer().onDataSent(callback); - } - - /** - * The same as onDataSent() but allows an object reference and member function - * to be added to the chain of callbacks. - * - * @param[in] objPtr Pointer to the instance that is used to invoke the - * event handler. - * @param[in] memberPtr Event handler being registered. It is a member - * function. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onDataSent(). A former call - * to ble.onDataSent(...) should be replaced with - * ble.gattServer().onDataSent(...). - */ - template - MBED_DEPRECATED("ble.gattServer().onDataSent(...)") - void onDataSent(T *objPtr, void (T::*memberPtr)(unsigned count)) - { - gattServer().onDataSent(objPtr, memberPtr); - } - - /** - * Set up a callback for when an attribute has its value updated by or at the - * connected peer. For a peripheral, this callback is triggered when the local - * GATT server has an attribute updated by a write command from the peer. - * For a Central, this callback is triggered when a response is received for - * a write request. - * - * @param[in] callback The event handler being registered. - * - * @note It is possible to chain together multiple onDataWritten callbacks - * (potentially from different modules of an application) to receive updates - * to characteristics. Many services, such as DFU and UART, add their own - * onDataWritten callbacks behind the scenes to trap interesting events. - * - * @note It is also possible to set up a callback into a member function of - * some object. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onDataWritten(). A former call - * to ble.onDataWritten(...) should be replaced with - * ble.gattServer().onDataWritten(...). - */ - MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(void (*callback)(const GattWriteCallbackParams *eventDataP)) - { - gattServer().onDataWritten(callback); - } - - /** - * The same as onDataWritten() but allows an object reference and member function - * to be added to the chain of callbacks. - * - * @param[in] objPtr Pointer to the instance that is used to invoke the - * event handler (@p memberPtr). - * @param[in] memberPtr Event handler being registered. It is a member - * function. - * - * - * @deprecated You should use the parallel API from GattServer directly, refer to - * GattServer::onDataWritten(). A former call - * to ble.onDataWritten(...) should be replaced with - * ble.gattServer().onDataWritten(...). - */ - template - MBED_DEPRECATED("ble.gattServer().onDataWritten(...)") - void onDataWritten(T *objPtr, void (T::*memberPtr)(const GattWriteCallbackParams *context)) - { - gattServer().onDataWritten(objPtr, memberPtr); - } - - /** - * Set up a callback to be invoked on the peripheral when an attribute is - * being read by a remote client. - * - * @note This functionality may not be available on all underlying stacks. - * You could use GattCharacteristic::setReadAuthorizationCallback() as an - * alternative. - * - * @note It is possible to chain together multiple onDataRead callbacks - * (potentially from different modules of an application) to receive updates - * to characteristics. Services may add their own onDataRead callbacks - * behind the scenes to trap interesting events. - * - * @note It is also possible to set up a callback into a member function of - * some object. - * - * @param[in] callback Event handler being registered. - * - * @return BLE_ERROR_NOT_IMPLEMENTED if this functionality isn't available; - * else BLE_ERROR_NONE. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onDataRead(). A former call - * to ble.onDataRead(...) should be replaced with - * ble.gattServer().onDataRead(...). - */ - MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(void (*callback)(const GattReadCallbackParams *eventDataP)) - { - return gattServer().onDataRead(callback); - } - - /** - * The same as onDataRead() but allows an object reference and member function - * to be added to the chain of callbacks. - * - * @param[in] objPtr Pointer to the instance that is used to invoke the - * event handler (@p memberPtr). - * @param[in] memberPtr Event handler being registered. It is a member - * function. - * - * @return BLE_ERROR_NOT_IMPLEMENTED if this functionality isn't available; - * else BLE_ERROR_NONE. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onDataRead(). A former call - * to ble.onDataRead(...) should be replaced with - * ble.gattServer().onDataRead(...). - */ - template - MBED_DEPRECATED("ble.gattServer().onDataRead(...)") - ble_error_t onDataRead(T *objPtr, void (T::*memberPtr)(const GattReadCallbackParams *context)) - { - return gattServer().onDataRead(objPtr, memberPtr); - } - - /** - * Set up a callback for when notifications or indications are enabled for a - * characteristic on the local GattServer. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onUpdatesEnabled(). A former call - * to ble.onUpdatesEnabled(callback) should be replaced with - * ble.gattServer().onUpdatesEnabled(callback). - */ - MBED_DEPRECATED("ble.gattServer().onUpdatesEnabled(...)") - void onUpdatesEnabled(GattServer::EventCallback_t callback) - { - gattServer().onUpdatesEnabled(callback); - } - - /** - * Set up a callback for when notifications or indications are disabled for a - * characteristic on the local GattServer. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onUpdatesDisabled(). A former call - * to ble.onUpdatesDisabled(callback) should be replaced with - * ble.gattServer().onUpdatesDisabled(callback). - */ - MBED_DEPRECATED("ble.gattServer().onUpdatesDisabled(...)") - void onUpdatesDisabled(GattServer::EventCallback_t callback) - { - gattServer().onUpdatesDisabled(callback); - } - - /** - * Set up a callback for when the GATT server receives a response for an - * indication event sent previously. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from GattServer directly and refer to - * GattServer::onConfirmationReceived(). A former call - * to ble.onConfirmationReceived(callback) should be replaced with - * ble.gattServer().onConfirmationReceived(callback). - */ - MBED_DEPRECATED("ble.gattServer().onConfirmationReceived(...)") - void onConfirmationReceived(GattServer::EventCallback_t callback) - { - gattServer().onConfirmationReceived(callback); - } -#endif // BLE_FEATURE_GATT_SERVER - -#if BLE_FEATURE_SECURITY - /** - * Set up a callback for when the security setup procedure (key generation - * and exchange) for a link has started. This will be skipped for bonded - * devices. The callback is passed in parameters received from the peer's - * security request: bool allowBonding, bool requireMITM and - * SecurityIOCapabilities_t. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::onSecuritySetupInitiated(). A former - * call to ble.onSecuritySetupInitiated(callback) should be replaced with - * ble.securityManager().onSecuritySetupInitiated(callback). - */ - MBED_DEPRECATED("ble.securityManager().onSecuritySetupInitiated(callback)") - void onSecuritySetupInitiated(SecurityManager::SecuritySetupInitiatedCallback_t callback) - { - securityManager().onSecuritySetupInitiated(callback); - } - - /** - * Set up a callback for when the security setup procedure (key generation - * and exchange) for a link has completed. This will be skipped for bonded - * devices. The callback is passed in the success/failure status of the - * security setup procedure. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::onSecuritySetupCompleted(). A former - * call to ble.onSecuritySetupCompleted(callback) should be replaced with - * ble.securityManager().onSecuritySetupCompleted(callback). - */ - MBED_DEPRECATED("ble.securityManager().onSecuritySetupCompleted(callback)") - void onSecuritySetupCompleted(SecurityManager::SecuritySetupCompletedCallback_t callback) - { - securityManager().onSecuritySetupCompleted(callback); - } - - /** - * Set up a callback for when a link with the peer is secured. For bonded - * devices, subsequent reconnections with a bonded peer will result only in - * this callback when the link is secured, and setup procedures will not - * occur unless the bonding information is either lost or deleted on either - * or both sides. The callback is passed in a SecurityManager::SecurityMode_t according - * to the level of security in effect for the secured link. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::onLinkSecured(). A former - * call to ble.onLinkSecured(callback) should be replaced with - * ble.securityManager().onLinkSecured(callback). - */ - MBED_DEPRECATED("ble.securityManager().onLinkSecured(callback)") - void onLinkSecured(SecurityManager::LinkSecuredCallback_t callback) - { - securityManager().onLinkSecured(callback); - } - - /** - * Set up a callback for successful bonding, meaning that link-specific security - * context is stored persistently for a peer device. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::onSecurityContextStored(). A former - * call to ble.onSecurityContextStored(callback) should be replaced with - * ble.securityManager().onSecurityContextStored(callback). - */ - MBED_DEPRECATED("ble.securityManager().onSecurityContextStored(callback)") - void onSecurityContextStored(SecurityManager::HandleSpecificEvent_t callback) - { - securityManager().onSecurityContextStored(callback); - } - - /** - * Set up a callback for when the passkey needs to be displayed on a - * peripheral with DISPLAY capability. This happens when security is - * configured to prevent man-in-the-middle attacks, and the peers need to exchange - * a passkey (or PIN) to authenticate the connection - * attempt. - * - * @param[in] callback Event handler being registered. - * - * @deprecated You should use the parallel API from SecurityManager directly and refer to - * SecurityManager::onPasskeyDisplay(). A former - * call to ble.onPasskeyDisplay(callback) should be replaced with - * ble.securityManager().onPasskeyDisplay(callback). - */ - MBED_DEPRECATED("ble.securityManager().onPasskeyDisplay(callback)") - void onPasskeyDisplay(SecurityManager::PasskeyDisplayCallback_t callback) - { - return securityManager().onPasskeyDisplay(callback); - } -#endif // BLE_FEATURE_SECURITY - -private: - friend class BLEInstanceBase; - /** * This function allows the BLE stack to signal that there is work to do and * event processing should be done (BLE::processEvent()). diff --git a/features/FEATURE_BLE/ble/services/DFUService.h b/features/FEATURE_BLE/ble/services/DFUService.h deleted file mode 100644 index a0284178d78..00000000000 --- a/features/FEATURE_BLE/ble/services/DFUService.h +++ /dev/null @@ -1,150 +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. - */ - -#ifdef TARGET_NRF51822 /* DFU only supported on nrf51 platforms */ - -#ifndef __BLE_DFU_SERVICE_H__ -#define __BLE_DFU_SERVICE_H__ - -#if BLE_FEATURE_GATT_SERVER - -#include "ble/BLE.h" -#include "ble/UUID.h" - -extern "C" { -#include "dfu_app_handler.h" -} - -extern const uint8_t DFUServiceBaseUUID[]; -extern const uint16_t DFUServiceShortUUID; -extern const uint16_t DFUServiceControlCharacteristicShortUUID; - -extern const uint8_t DFUServiceUUID[]; -extern const uint8_t DFUServiceControlCharacteristicUUID[]; -extern const uint8_t DFUServicePacketCharacteristicUUID[]; - -/** -* @class DFUService -* @brief Device Firmware Update Service. -*/ -class DFUService { -public: - /** - * @brief Signature for the handover callback. The application may provide this - * callback when setting up the DFU service. The callback is then - * invoked before handing control over to the bootloader. - */ - typedef void (*ResetPrepare_t)(void); - -public: - /** - * @brief Adds Device Firmware Update Service to an existing BLE object. - * - * @param[ref] _ble - * BLE object for the underlying controller. - * @param[in] _handoverCallback - * Application-specific handover callback. - */ - DFUService(BLE &_ble, ResetPrepare_t _handoverCallback = NULL) : - ble(_ble), - controlPoint(DFUServiceControlCharacteristicUUID, controlBytes, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - packet(DFUServicePacketCharacteristicUUID, packetBytes, SIZEOF_PACKET_BYTES, SIZEOF_PACKET_BYTES, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), - controlBytes(), - packetBytes() { - static bool serviceAdded = false; /* We only add the DFU service once. */ - if (serviceAdded) { - return; - } - - /* Set an initial value for control bytes, so that the application's DFU service can - * be distinguished from the real DFU service provided by the bootloader. */ - controlBytes[0] = 0xFF; - controlBytes[1] = 0xFF; - - GattCharacteristic *dfuChars[] = {&controlPoint, &packet}; - GattService dfuService(DFUServiceUUID, dfuChars, sizeof(dfuChars) / sizeof(GattCharacteristic *)); - - ble.addService(dfuService); - handoverCallback = _handoverCallback; - serviceAdded = true; - - ble.onDataWritten(this, &DFUService::onDataWritten); - } - - /** - * @brief Get the handle for the value attribute of the control characteristic. - */ - uint16_t getControlHandle(void) const { - return controlPoint.getValueHandle(); - } - - /** - * @brief This callback allows the DFU service to receive the initial trigger to - * hand control over to the bootloader. First, the application is given a - * chance to clean up. - * - * @param[in] params - * Information about the characteristic being updated. - */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == controlPoint.getValueHandle()) { - /* At present, writing anything will do the trick - this needs to be improved. */ - if (handoverCallback) { - handoverCallback(); - } - - // Call bootloader_start implicitly trough a event handler call - // it is a work around for bootloader_start not being public in sdk 8.1 - ble_dfu_t p_dfu; - ble_dfu_evt_t p_evt; - - p_dfu.conn_handle = params->connHandle; - p_evt.ble_dfu_evt_type = BLE_DFU_START; - - dfu_app_on_dfu_evt(&p_dfu, &p_evt); - } - } - -protected: - static const unsigned SIZEOF_CONTROL_BYTES = 2; - static const unsigned SIZEOF_PACKET_BYTES = 20; - -protected: - BLE &ble; - - /** Writing to the control characteristic triggers the handover to DFU - * bootloader. At present, writing anything will do the trick - this needs - * to be improved. */ - WriteOnlyArrayGattCharacteristic controlPoint; - - /** The packet characteristic in this service doesn't do anything meaningful; - * it is only a placeholder to mimic the corresponding characteristic in the - * actual DFU service implemented by the bootloader. Without this, some - * FOTA clients might get confused, because service definitions change after - * handing control over to the bootloader. */ - GattCharacteristic packet; - - uint8_t controlBytes[SIZEOF_CONTROL_BYTES]; - uint8_t packetBytes[SIZEOF_PACKET_BYTES]; - - static ResetPrepare_t handoverCallback; /**< Application-specific handover callback. */ -}; - -#endif // BLE_FEATURE_GATT_SERVER - -#endif /* #ifndef __BLE_DFU_SERVICE_H__*/ -#endif /* #ifdef TARGET_NRF51822 */ diff --git a/features/FEATURE_BLE/ble/services/DeviceInformationService.h b/features/FEATURE_BLE/ble/services/DeviceInformationService.h index f4f215cab33..d9d04f4f5ca 100644 --- a/features/FEATURE_BLE/ble/services/DeviceInformationService.h +++ b/features/FEATURE_BLE/ble/services/DeviceInformationService.h @@ -101,7 +101,7 @@ class DeviceInformationService { GattService deviceInformationService(GattService::UUID_DEVICE_INFORMATION_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - ble.addService(deviceInformationService); + ble.gattServer().addService(deviceInformationService); serviceAdded = true; } diff --git a/features/FEATURE_BLE/ble/services/EddystoneConfigService.h b/features/FEATURE_BLE/ble/services/EddystoneConfigService.h deleted file mode 100644 index 3d706afdac8..00000000000 --- a/features/FEATURE_BLE/ble/services/EddystoneConfigService.h +++ /dev/null @@ -1,550 +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 SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ -#define SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ - -#warning ble/services/EddystoneConfigService.h is deprecated. Please use the example in 'github.com/ARMmbed/ble-examples/tree/master/BLE_EddystoneService'. - -#if BLE_FEATURE_GATT_SERVER - -#include "ble/BLE.h" -#include "ble/services/EddystoneService.h" -#include "Timer.h" -#include "Ticker.h" - -#define UUID_URI_BEACON(FIRST, SECOND) { \ - 0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba, \ - 0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8, \ -} - -static const uint8_t UUID_URI_BEACON_SERVICE[] = UUID_URI_BEACON(0x20, 0x80); -static const uint8_t UUID_LOCK_STATE_CHAR[] = UUID_URI_BEACON(0x20, 0x81); -static const uint8_t UUID_LOCK_CHAR[] = UUID_URI_BEACON(0x20, 0x82); -static const uint8_t UUID_UNLOCK_CHAR[] = UUID_URI_BEACON(0x20, 0x83); -static const uint8_t UUID_URI_DATA_CHAR[] = UUID_URI_BEACON(0x20, 0x84); -static const uint8_t UUID_FLAGS_CHAR[] = UUID_URI_BEACON(0x20, 0x85); -static const uint8_t UUID_ADV_POWER_LEVELS_CHAR[] = UUID_URI_BEACON(0x20, 0x86); -static const uint8_t UUID_TX_POWER_MODE_CHAR[] = UUID_URI_BEACON(0x20, 0x87); -static const uint8_t UUID_BEACON_PERIOD_CHAR[] = UUID_URI_BEACON(0x20, 0x88); -static const uint8_t UUID_RESET_CHAR[] = UUID_URI_BEACON(0x20, 0x89); -extern const uint8_t BEACON_EDDYSTONE[2]; - -/** -* @class EddystoneConfigService -* @brief Eddystone Configuration Service. Used to set URL, adjust power levels, and set flags. -* See https://github.com/google/eddystone -* -*/ -class EddystoneConfigService -{ -public: - /** - * @brief Transmission Power Modes for UriBeacon - */ - enum { - TX_POWER_MODE_LOWEST, - TX_POWER_MODE_LOW, - TX_POWER_MODE_MEDIUM, - TX_POWER_MODE_HIGH, - NUM_POWER_MODES - }; - - static const unsigned ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. - static const unsigned SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets. - - typedef uint8_t Lock_t[16]; /* 128 bits. */ - typedef int8_t PowerLevels_t[NUM_POWER_MODES]; - - // There are currently three subframes defined: URI, UID, and TLM. -#define EDDYSTONE_MAX_FRAMETYPE 3 - static const unsigned URI_DATA_MAX = 18; - typedef uint8_t UriData_t[URI_DATA_MAX]; - - // UID Frame Type subfields. - static const size_t UID_NAMESPACEID_SIZE = 10; - typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE]; - static const size_t UID_INSTANCEID_SIZE = 6; - typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE]; - - // Eddystone Frame Type ID. - static const uint8_t FRAME_TYPE_UID = 0x00; - static const uint8_t FRAME_TYPE_URL = 0x10; - static const uint8_t FRAME_TYPE_TLM = 0x20; - - static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14B. - static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes. - - struct Params_t { - // Config Data - bool isConfigured; // Flag for configuration being complete: - // True = configured, False = not configured. Reset at instantiation, used for external callbacks. - uint8_t lockedState; - Lock_t lock; - uint8_t flags; - PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels. - uint8_t txPowerMode; // Firmware power levels used with setTxPower(). - uint16_t beaconPeriod; - // TLM Frame Data - uint8_t tlmVersion; // Version of TLM packet. - bool tlmEnabled; - float tlmBeaconPeriod; // How often to broadcat TLM frame, in seconds. - // URI Frame Data - uint8_t uriDataLength; - UriData_t uriData; - bool uriEnabled; - float uriBeaconPeriod; // How often to broadcast URIFrame, in seconds. - // UID Frame Data - UIDNamespaceID_t uidNamespaceID; // UUID type, Namespace ID, 10B. - UIDInstanceID_t uidInstanceID; // UUID type, Instance ID, 6B. - bool uidEnabled; - float uidBeaconPeriod; // How often to broadcast UID Frame, in seconds. - }; - - /** - * @param[in] bleIn - * BLEDevice object for the underlying controller. - * @param[in,out] paramsIn - * Reference to application-visible beacon state, loaded - * from persistent storage at startup. - * @param[in] defaultAdvPowerLevelsIn - * Default power-levels array; applies only if resetToDefaultsFlag is true. - * - * @param[in] radioPowerLevelsIn - * Transmission power-levels to use in TX. - */ - EddystoneConfigService(BLEDevice &bleIn, - Params_t ¶msIn, - PowerLevels_t &defaultAdvPowerLevelsIn, - PowerLevels_t &radioPowerLevelsIn) : - ble(bleIn), - params(paramsIn), // Initialize URL data. - defaultAdvPowerLevels(defaultAdvPowerLevelsIn), - radioPowerLevels(radioPowerLevelsIn), - initSucceeded(false), - resetFlag(), - defaultUidNamespaceID(), // Initialize UID data. - defaultUidInstanceID(), - defaultUidPower(defaultAdvPowerLevelsIn[params.txPowerMode]), - uidIsSet(false), - defaultUriDataLength(), - defaultUriData(), - defaultUrlPower(defaultAdvPowerLevelsIn[params.txPowerMode]), - urlIsSet(false), - tlmIsSet(false), - lockedStateChar(UUID_LOCK_STATE_CHAR, ¶ms.lockedState), - lockChar(UUID_LOCK_CHAR, ¶ms.lock), - uriDataChar(UUID_URI_DATA_CHAR, params.uriData, 0, URI_DATA_MAX, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE), - unlockChar(UUID_UNLOCK_CHAR, ¶ms.lock), - flagsChar(UUID_FLAGS_CHAR, ¶ms.flags), - advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), - txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), - beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), - resetChar(UUID_RESET_CHAR, &resetFlag) { - // Set Eddystone as not configured yet. Used to exit config before timeout if GATT services are written to. - params.isConfigured = false; - - lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback); - unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback); - uriDataChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::uriDataWriteAuthorizationCallback); - flagsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); - advPowerLevelsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); - txPowerModeChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::powerModeAuthorizationCallback); - beaconPeriodChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); - resetChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); - - static GattCharacteristic *charTable[] = { - &lockedStateChar, &lockChar, &unlockChar, &uriDataChar, - &flagsChar, &advPowerLevelsChar, &txPowerModeChar, &beaconPeriodChar, &resetChar - }; - - GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(configService); - ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback); - } - - /** - * @brief Start EddystoneConfig advertising. This function should be called - * after the EddystoneConfig constructor and after all the frames have been added. - * - * @param[in] resetToDefaultsFlag - * Applies to the state of the 'paramsIn' parameter. - * If true, it indicates that paramsIn is potentially - * un-initialized, and default values should be used - * instead. Otherwise, paramsIn overrides the defaults. - */ - void start(bool resetToDefaultsFlag){ - INFO("reset to defaults flag = %d", resetToDefaultsFlag); - if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { - INFO("Reset to Defaults triggered"); - resetToDefaultsFlag = true; - } - - if (resetToDefaultsFlag) { - resetToDefaults(); - } else { - updateCharacteristicValues(); - } - - setupEddystoneConfigAdvertisements(); /* Set up advertising for the config service. */ - initSucceeded = true; - } - - /* - * Check if Eddystone initialized successfully. - */ - bool initSuccessfully(void) const { - return initSucceeded; - } - - /* - * @brief Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied. - * - * @param[in] tlmVersionIn Version of the TLM frame being used. - * @param[in] advPeriodInMin How long between TLM frames being advertised, measured in minutes. - * - */ - void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){ - DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f", tlmVersionIn, advPeriodInSec); - defaultTlmVersion = tlmVersionIn; - TlmBatteryVoltage = 0; - TlmBeaconTemp = 0x8000; - TlmPduCount = 0; - TlmTimeSinceBoot = 0; - defaultTlmAdvPeriod = advPeriodInSec; - tlmIsSet = true; // Flag to add this to Eddystone service when config is done. - } - - /* - * @brief Function to update the default values for the URI frame. Only applied if Reset Defaults is applied. - * - * @param[in] uriIn URL to advertise. - * @param[in] advPeriod How long to advertise the URL, measured in number of ADV frames. - * - */ - void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1){ - DBG("Setting Default URI Data"); - // Set URL Frame - EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength); // Encode URL to URL Formatting. - if (defaultUriDataLength > URI_DATA_MAX) { - return; - } - INFO("\t URI input = %s : %d", uriIn, defaultUriDataLength); - INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength ); - defaultUriAdvPeriod = advPeriod; - urlIsSet = true; // Flag to add this to Eddystone service when config is done. - } - - /* - * @brief Function to update the default values for the UID frame. Only applied if Reset Defaults is applied. - * - * @param[in] namespaceID 10Byte Namespace ID. - * @param[in] instanceID 6Byte Instance ID. - * @param[in] advPeriod How long to advertise the URL, measured in the number of ADV frames. - * - */ - void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10){ - //Set UID frame - DBG("Setting default UID Data"); - memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); - memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); - defaultUidAdvPeriod = advPeriod; - uidIsSet = true; // Flag to add this to Eddystone service when config is done. - } - - /* Start out by advertising the config service for a limited time after - * startup, then switch to the normal non-connectible beacon functionality. - */ - void setupEddystoneConfigAdvertisements() { - const char DEVICE_NAME[] = "eddystone Config"; - - ble.clearAdvertisingPayload(); - - ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); - - // UUID is in a different order in the ADV frame (!) - uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)]; - for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) { - reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1]; - } - ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID)); - ble.accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG); - ble.accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast(&DEVICE_NAME), sizeof(DEVICE_NAME)); - ble.accumulateScanResponse( - GapAdvertisingData::TX_POWER_LEVEL, - reinterpret_cast(&defaultAdvPowerLevels[EddystoneConfigService::TX_POWER_MODE_LOW]), - sizeof(uint8_t)); - - ble.setTxPower(radioPowerLevels[params.txPowerMode]); - ble.setDeviceName(reinterpret_cast(&DEVICE_NAME)); - ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); - ble.setAdvertisingInterval(ADVERTISING_INTERVAL_MSEC); - } - - /* - * This function actually impliments the Eddystone Beacon service. It can be called with the help of the wrapper function - * to load saved config params, or it can be called explicitly to reset the Eddystone beacon to hardcoded values on each reset. - * - */ - void setupEddystoneAdvertisements() { - DBG("Switching Config -> adv"); - // Save params to storage. - extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */ - saveURIBeaconConfigParams(¶ms); - INFO("Saved Params to Memory.") - // Set up Eddystone Service. - static EddystoneService eddyServ(ble, params.beaconPeriod, radioPowerLevels[params.txPowerMode]); - // Set configured frames (TLM, UID, URI and so on). - if (params.tlmEnabled) { - eddyServ.setTLMFrameData(params.tlmVersion, params.tlmBeaconPeriod); - } - if (params.uriEnabled) { - eddyServ.setURLFrameEncodedData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriDataLength, params.uriBeaconPeriod); - } - if (params.uidEnabled) { - eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode], - (uint8_t *)params.uidNamespaceID, - (uint8_t *)params.uidInstanceID, - params.uidBeaconPeriod); - } - // Start advertising the Eddystone service. - eddyServ.start(); - } - -private: - /* - * This callback is invoked when a GATT client attempts to modify any of the - * characteristics of this service. Attempts to do so are also applied to - * the internal state of this service object. - */ - void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) { - uint16_t handle = writeParams->handle; - - if (handle == lockChar.getValueHandle()) { - // Validated earlier. - memcpy(params.lock, writeParams->data, sizeof(Lock_t)); - // Set the state to be locked by the lock code (note: zeros are a valid lock). - params.lockedState = true; - INFO("Device Locked"); - } else if (handle == unlockChar.getValueHandle()) { - // Validated earlier. - params.lockedState = false; - INFO("Device Unlocked"); - } else if (handle == uriDataChar.getValueHandle()) { - params.uriDataLength = writeParams->len; - memset(params.uriData, 0x00, URI_DATA_MAX); // Clear URI string. - memcpy(params.uriData, writeParams->data, writeParams->len); // Set URI string. - params.uriEnabled = true; - INFO("URI = %s, URILen = %d", writeParams->data, writeParams->len); - } else if (handle == flagsChar.getValueHandle()) { - params.flags = *(writeParams->data); - INFO("flagsChar = 0x%x", params.flags); - } else if (handle == advPowerLevelsChar.getValueHandle()) { - memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t)); - INFO("PowerLevelsChar = %4x", params.advPowerLevels); - } else if (handle == txPowerModeChar.getValueHandle()) { - params.txPowerMode = *(writeParams->data); - INFO("TxPowerModeChar = %d", params.txPowerMode); - } else if (handle == beaconPeriodChar.getValueHandle()) { - params.beaconPeriod = *((uint16_t *)(writeParams->data)); - INFO("BeaconPeriod = %d", params.beaconPeriod); - - /* Re-map beaconPeriod to within permissible bounds if necessary. */ - if (params.beaconPeriod != 0) { - bool paramsUpdated = false; - if (params.beaconPeriod < ble.getMinAdvertisingInterval()) { - params.beaconPeriod = ble.getMinAdvertisingInterval(); - paramsUpdated = true; - } else if (params.beaconPeriod > ble.getMaxAdvertisingInterval()) { - params.beaconPeriod = ble.getMaxAdvertisingInterval(); - paramsUpdated = true; - } - if (paramsUpdated) { - ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); - } - } - } else if (handle == resetChar.getValueHandle()) { - INFO("Reset triggered from Config Service, resetting to defaults"); - resetToDefaults(); - } - updateCharacteristicValues(); - params.isConfigured = true; // Some configuration data has been passed; on disconnect switch to advertising mode. - } - - /* - * Reset the default values. - */ - void resetToDefaults(void) { - INFO("Resetting to defaults"); - // General. - params.lockedState = false; - memset(params.lock, 0, sizeof(Lock_t)); - params.flags = 0x10; - memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t)); - params.txPowerMode = TX_POWER_MODE_LOW; - params.beaconPeriod = (uint16_t) defaultUriAdvPeriod * 1000; - - // TLM Frame. - params.tlmVersion = defaultTlmVersion; - params.tlmBeaconPeriod = defaultTlmAdvPeriod; - params.tlmEnabled = tlmIsSet; - - // URL Frame. - memcpy(params.uriData, defaultUriData, URI_DATA_MAX); - params.uriDataLength = defaultUriDataLength; - params.uriBeaconPeriod = defaultUriAdvPeriod; - params.uriEnabled = urlIsSet; - - // UID Frame. - memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE); - memcpy(params.uidInstanceID, defaultUidInstanceID, UID_INSTANCEID_SIZE); - params.uidBeaconPeriod = defaultUidAdvPeriod; - params.uidEnabled = uidIsSet; - - updateCharacteristicValues(); - } - - /* - * Internal helper function used to update the GATT database following any - * change to the internal state of the service object. - */ - void updateCharacteristicValues(void) { - ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), ¶ms.lockedState, 1); - ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); - ble.updateCharacteristicValue(flagsChar.getValueHandle(), ¶ms.flags, 1); - ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), - reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); - ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); - ble.updateCharacteristicValue(advPowerLevelsChar.getValueHandle(), - reinterpret_cast(params.advPowerLevels), sizeof(PowerLevels_t)); - } - -private: - void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (params.lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(Lock_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } else if (authParams->len != sizeof(Lock_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else if (memcmp(authParams->data, params.lock, sizeof(Lock_t)) != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (params.lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (params.lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(uint8_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else if (*((uint8_t *)authParams->data) >= NUM_POWER_MODES) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - template - void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (params.lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(T)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - BLEDevice &ble; - Params_t ¶ms; - mbed::Ticker timeSinceBootTick; - mbed::Timeout switchFrame; - // Default value that is restored on reset. - PowerLevels_t &defaultAdvPowerLevels; // This goes into the advertising frames (radio power measured at 1m from device). - PowerLevels_t &radioPowerLevels; // This configures the power levels of the radio. - uint8_t lockedState; - bool initSucceeded; - uint8_t resetFlag; - bool switchFlag; - - //UID default value that is restored on reset. - UIDNamespaceID_t defaultUidNamespaceID; - UIDInstanceID_t defaultUidInstanceID; - float defaultUidAdvPeriod; - int8_t defaultUidPower; - uint16_t uidRFU; - bool uidIsSet; - - //URI default value that is restored on reset. - uint8_t defaultUriDataLength; - UriData_t defaultUriData; - int8_t defaultUrlPower; - float defaultUriAdvPeriod; - bool urlIsSet; - - //TLM default value that is restored on reset. - uint8_t defaultTlmVersion; - float defaultTlmAdvPeriod; - volatile uint16_t TlmBatteryVoltage; - volatile uint16_t TlmBeaconTemp; - volatile uint32_t TlmPduCount; - volatile uint32_t TlmTimeSinceBoot; - bool tlmIsSet; - - ReadOnlyGattCharacteristic lockedStateChar; - WriteOnlyGattCharacteristic lockChar; - GattCharacteristic uriDataChar; - WriteOnlyGattCharacteristic unlockChar; - ReadWriteGattCharacteristic flagsChar; - ReadWriteGattCharacteristic advPowerLevelsChar; - ReadWriteGattCharacteristic txPowerModeChar; - ReadWriteGattCharacteristic beaconPeriodChar; - WriteOnlyGattCharacteristic resetChar; -}; - -#endif // BLE_FEATURE_GATT_SERVER - -#endif // SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ diff --git a/features/FEATURE_BLE/ble/services/EddystoneService.h b/features/FEATURE_BLE/ble/services/EddystoneService.h deleted file mode 100644 index 4e306d4d2d6..00000000000 --- a/features/FEATURE_BLE/ble/services/EddystoneService.h +++ /dev/null @@ -1,661 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2015 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 SERVICES_EDDYSTONEBEACON_H_ -#define SERVICES_EDDYSTONEBEACON_H_ - -#warning ble/services/EddystoneService.h is deprecated. Please use the example in 'github.com/ARMmbed/ble-examples/tree/master/BLE_EddystoneService'. - -#include "ble/BLE.h" -#include "CircularBuffer.h" -#include "Timer.h" -#include "Ticker.h" -#include "Timeout.h" - -#if BLE_FEATURE_GATT_SERVER - -static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; - -//Debug is disabled by default -#if 0 -#define DBG(MSG, ...) printf("[EddyStone: DBG]" MSG " \t[%s,%d]\r\n", \ - ## __VA_ARGS__, \ - __FILE__, \ - __LINE__); -#define WARN(MSG, ...) printf("[EddyStone: WARN]" MSG " \t[%s,%d]\r\n", \ - ## __VA_ARGS__, \ - __FILE__, \ - __LINE__); -#define ERR(MSG, ...) printf("[EddyStone: ERR]" MSG " \t[%s,%d]\r\n", \ - ## __VA_ARGS__, \ - __FILE__, \ - __LINE__); -#else // if 0 -#define DBG(x, ...) //wait_us(10); -#define WARN(x, ...) //wait_us(10); -#define ERR(x, ...) -#endif // if 0 - -#if 0 -#define INFO(x, ...) printf("[EddyStone: INFO]"x " \t[%s,%d]\r\n", \ - ## __VA_ARGS__, \ - __FILE__, \ - __LINE__); -#else // if 0 -#define INFO(x, ...) -#endif // if 0 - -/** -* @class Eddystone -* @brief Eddystone Configuration Service. Can be used to set URL, adjust power levels, and set flags. -* See https://github.com/google/eddystone -* -*/ -class EddystoneService -{ -public: - enum FrameTypes { - NONE, - url, - uid, - tlm - }; - - static const int SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets - - // There are currently 3 subframes defined, URI, UID, and TLM -#define EDDYSTONE_MAX_FRAMETYPE 3 - void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t); - static const int URI_DATA_MAX = 18; - typedef uint8_t UriData_t[URI_DATA_MAX]; - mbed::CircularBuffer overflow; - - // UID Frame Type subfields - static const int UID_NAMESPACEID_SIZE = 10; - typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE]; - static const int UID_INSTANCEID_SIZE = 6; - typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE]; - - // Eddystone Frame Type ID - static const uint8_t FRAME_TYPE_UID = 0x00; - static const uint8_t FRAME_TYPE_URL = 0x10; - static const uint8_t FRAME_TYPE_TLM = 0x20; - - static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14Bytes - static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes - - /** - * Set Eddystone UID Frame information. - * - * @param[in] power TX Power in dB measured at 0 meters from the device. Range of -100 to +20 dB. - * @param[in] namespaceID 10B namespace ID - * @param[in] instanceID 6B instance ID - * @param[in] uidAdvPeriodIn Advertising period of UID frames. - * @param[in] RFU 2B of RFU, initialized to 0x0000 and not broadcast, included for future reference. - */ - void setUIDFrameData(int8_t power, - UIDNamespaceID_t namespaceID, - UIDInstanceID_t instanceID, - float uidAdvPeriodIn, - uint16_t RFU = 0x0000) { - if (0.0f == uidAdvPeriodIn) { - uidIsSet = false; - return; - } - if (power > 20) { - power = 20; - } - if (power < -100) { - power = -100; - } - - defaultUidPower = power; - memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); - memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); - uidRFU = (uint16_t)RFU; // this is probably bad form, but it doesn't really matter yet. - uidAdvPeriod = uidAdvPeriodIn; - uidIsSet = true; // set toggle to advertise UID frames - } - - /* - * Construct UID frame from private variables - * @param[in/out] Data pointer to array to store constructed frame in - * @param[in] maxSize number of bytes left in array, effectively how much empty space is available to write to - * @return number of bytes used. negative number indicates error message. - */ - unsigned constructUIDFrame(uint8_t *Data, uint8_t maxSize) { - unsigned index = 0; - - Data[index++] = FRAME_TYPE_UID; // 1B Type - - if (defaultUidPower > 20) { - defaultUidPower = 20; // enforce range of vaild values. - } - if (defaultUidPower < -100) { - defaultUidPower = -100; - } - Data[index++] = defaultUidPower; // 1B Power @ 0meter - - DBG("UID NamespaceID = '0x"); - for (size_t x = 0; x < UID_NAMESPACEID_SIZE; x++) { // 10B Namespace ID - Data[index++] = defaultUidNamespaceID[x]; - DBG("%x,", defaultUidNamespaceID[x]); - } - DBG("'\r\n"); - - DBG("UID InstanceID = '0x"); - for (size_t x = 0; x< UID_INSTANCEID_SIZE; x++) { // 6B Instance ID - Data[index++] = defaultUidInstanceID[x]; - DBG("%x,", defaultUidInstanceID[x]); - } - DBG("'\r\n"); - - if (0 != uidRFU) { // 2B RFU, include if non-zero, otherwise ignore - Data[index++] = (uint8_t)(uidRFU >> 0); - Data[index++] = (uint8_t)(uidRFU >> 8); - } - DBG("construcUIDFrame %d, %d", maxSize, index); - return index; - } - - /** - * Set Eddystone URL Frame information. - * @param[in] power TX Power in dB measured at 0 meters from the device. - * @param[in] urlIn URL to encode - * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) - * @return false on success, true on failure. - */ - bool setURLFrameData(int8_t power, const char *urlIn, float urlAdvPeriodIn) { - if (0.0f == urlAdvPeriodIn) { - urlIsSet = false; - return false; - } - encodeURL(urlIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting - if (defaultUriDataLength > URI_DATA_MAX) { - return true; // error, URL is too big - } - defaultUrlPower = power; - urlAdvPeriod = urlAdvPeriodIn; - urlIsSet = true; - return false; - } - - /** - * Set Eddystone URL Frame information. - * @param[in] power TX Power in dB measured at 0 meters from the device. - * @param[in] encodedUrlIn Encoded URL - * @param[in] encodedUrlInLength Length of the encoded URL - * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) - * @return false on success, true on failure. - */ - bool setURLFrameEncodedData(int8_t power, const char *encodedUrlIn, uint8_t encodedUrlInLength, float urlAdvPeriodIn) { - if (0.0f == urlAdvPeriodIn) { - urlIsSet = false; - return false; - } - memcpy(defaultUriData, encodedUrlIn, encodedUrlInLength); - if (defaultUriDataLength > URI_DATA_MAX) { - return true; // error, URL is too big - } - defaultUrlPower = power; - defaultUriDataLength = encodedUrlInLength; - urlAdvPeriod = urlAdvPeriodIn; - urlIsSet = true; - return false; - } - - /* - * Construct URL frame from private variables - * @param[in/out] Data pointer to array to store constructed frame in - * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to - * @return number of bytes used. negative number indicates error message. - */ - int constructURLFrame(uint8_t *Data, uint8_t maxSize) { - int index = 0; - Data[index++] = FRAME_TYPE_URL; // 1B Type - Data[index++] = defaultUrlPower; // 1B TX Power - for (int x = 0; x < defaultUriDataLength; x++) { // 18B of URL Prefix + encoded URL - Data[index++] = defaultUriData[x]; - } - DBG("constructURLFrame: %d, %d", maxSize, index); - return index; - } - - /* - * Set Eddystone TLM Frame information. - * @param[in] Version of the TLM beacon data format - * @param[in] advPeriod how often to advertise the TLM frame for (in minutes) - * @param batteryVoltage in milivolts - * @param beaconTemp in 8.8 floating point notation - * - */ - void setTLMFrameData(uint8_t version = 0, - float advPeriod = 60.0f, - uint16_t batteryVoltage = 0, - uint16_t beaconTemp = 0x8000, - uint32_t pduCount = 0, - uint32_t timeSinceBoot = 0) { - if (0.0f == advPeriod) { - tlmIsSet = false; - return; - } - TlmVersion = version; - TlmBatteryVoltage = batteryVoltage; - TlmBeaconTemp = beaconTemp; - TlmPduCount = pduCount; // reset - TlmTimeSinceBoot = timeSinceBoot; // reset - TlmAdvPeriod = advPeriod; - tlmIsSet = true; // TLM Data has been enabled - } - - /* - * Construct TLM frame from private variables - * @param[in/out] Data pointer to array to store constructed frame in - * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to - * @return number of bytes used. negative number indicates error message. - */ - int constructTLMFrame(uint8_t *Data, uint8_t maxSize) { - uint32_t now = timeSinceBootTimer.read_ms(); - TlmTimeSinceBoot += (now - lastBootTimerRead) / 100; - lastBootTimerRead = now; - - int index = 0; - Data[index++] = FRAME_TYPE_TLM; // Eddystone frame type = Telemetry - Data[index++] = TlmVersion; // TLM Version Number - Data[index++] = (uint8_t)(TlmBatteryVoltage >> 8); // Battery Voltage[0] - Data[index++] = (uint8_t)(TlmBatteryVoltage >> 0); // Battery Voltage[1] - Data[index++] = (uint8_t)(TlmBeaconTemp >> 8); // Beacon Temp[0] - Data[index++] = (uint8_t)(TlmBeaconTemp >> 0); // Beacon Temp[1] - Data[index++] = (uint8_t)(TlmPduCount >> 24); // PDU Count [0] - Data[index++] = (uint8_t)(TlmPduCount >> 16); // PDU Count [1] - Data[index++] = (uint8_t)(TlmPduCount >> 8); // PDU Count [2] - Data[index++] = (uint8_t)(TlmPduCount >> 0); // PDU Count [3] - Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 24); // Time Since Boot [0] - Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 16); // Time Since Boot [1] - Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 8); // Time Since Boot [2] - Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 0); // Time Since Boot [3] - DBG("constructURLFrame: %d, %d", maxSize, index); - return index; - } - - /* - * Update the TLM frame battery voltage value - * @param[in] voltagemv Voltage to update the TLM field battery voltage with (in mV) - * @return nothing - */ - void updateTlmBatteryVoltage(uint16_t voltagemv) { - TlmBatteryVoltage = voltagemv; - } - - /* - * Update the TLM frame beacon temperature - * @param[in] temp Temperature of beacon (in 8.8fpn) - * @return nothing - */ - void updateTlmBeaconTemp(uint16_t temp) { - TlmBeaconTemp = temp; - } - - /* - * Update the TLM frame PDU Count field - * @param[in] pduCount Number of Advertisiting frames sent since powerup - * @return nothing - */ - void updateTlmPduCount(uint32_t pduCount) { - TlmPduCount = pduCount; - } - - /* - * Update the TLM frame Time since boot in 0.1s incriments - * @param[in] timeSinceBoot Time since boot in 0.1s incriments - * @return nothing - */ - void updateTlmTimeSinceBoot(uint32_t timeSinceBoot) { - TlmTimeSinceBoot = timeSinceBoot; - } - - /* - * Update advertising data - * @return true on success, false on failure - */ - bool updateAdvPacket(uint8_t serviceData[], unsigned serviceDataLen) { - // Fields from the Service - DBG("Updating AdvFrame: %d", serviceDataLen); - - ble.clearAdvertisingPayload(); - ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); - ble.setAdvertisingInterval(100); - ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); - ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, BEACON_EDDYSTONE, sizeof(BEACON_EDDYSTONE)); - ble.accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, serviceData, serviceDataLen); - - - return true; - } - - /* - * State machine for switching out frames. - * This function is called by the radioNotificationCallback when a frame needs to get swapped out. - * This function exists because of time constraints in the radioNotificationCallback, so it is effectively - * broken up into two functions. - */ - void swapOutFrames(FrameTypes frameType) { - uint8_t serviceData[SERVICE_DATA_MAX]; - unsigned serviceDataLen = 0; - //hard code in the eddystone UUID - serviceData[serviceDataLen++] = BEACON_EDDYSTONE[0]; - serviceData[serviceDataLen++] = BEACON_EDDYSTONE[1]; - - // if certain frames are not enabled, then skip them. Worst case TLM is always enabled - switch (frameType) { - case tlm: - // TLM frame - if (tlmIsSet) { - DBG("Swapping in TLM Frame: version=%x, Batt=%d, Temp = %d, PDUCnt = %d, TimeSinceBoot=%d", - TlmVersion, - TlmBatteryVoltage, - TlmBeaconTemp, - TlmPduCount, - TlmTimeSinceBoot); - serviceDataLen += constructTLMFrame(serviceData + serviceDataLen, 20); - DBG("\t Swapping in TLM Frame: len=%d", serviceDataLen); - updateAdvPacket(serviceData, serviceDataLen); - } - break; - case url: - // URL Frame - if (urlIsSet) { - DBG("Swapping in URL Frame: Power: %d", defaultUrlPower); - serviceDataLen += constructURLFrame(serviceData + serviceDataLen, 20); - DBG("\t Swapping in URL Frame: len=%d ", serviceDataLen); - updateAdvPacket(serviceData, serviceDataLen); - //switchFlag = false; - } - break; - case uid: - // UID Frame - if (uidIsSet) { - DBG("Swapping in UID Frame: Power: %d", defaultUidPower); - serviceDataLen += constructUIDFrame(serviceData + serviceDataLen, 20); - DBG("\t Swapping in UID Frame: len=%d", serviceDataLen); - updateAdvPacket(serviceData, serviceDataLen); - //switchFlag = false; - } - break; - default: - ERR("You have not initialized a Frame yet, please initialize one before starting a beacon"); - ERR("uidIsSet = %d, urlIsSet = %d, tlmIsSet = %d", uidIsSet, urlIsSet, tlmIsSet); - } - } - - /* - * Callback to swap in URL frame - */ - void urlCallback(void) { - DBG("urlCallback"); - if (false == advLock) { - advLock = true; - DBG("advLock = url") - frameIndex = url; - swapOutFrames(frameIndex); - ble.startAdvertising(); - } else { - // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free - INFO("URI(%d) cannot complete, %d is currently broadcasting", url, frameIndex); - FrameTypes x = url; - overflow.push(x); - } - } - - /* - * Callback to swap in UID frame - */ - void uidCallback(void) { - DBG("uidCallback"); - if (false == advLock) { - advLock = true; - DBG("advLock = uid") - frameIndex = uid; - swapOutFrames(frameIndex); - ble.startAdvertising(); - } else { - // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free - INFO("UID(%d) cannot complete, %d is currently broadcasting", uid, frameIndex); - FrameTypes x = uid; // have to do this to satisfy cont vs volatile keywords... sigh... - overflow.push(x); - } - } - - /* - * Callback to swap in TLM frame - */ - void tlmCallback(void) { - DBG("tlmCallback"); - if (false == advLock) { - // OK to broadcast - advLock = true; - DBG("advLock = tlm") - frameIndex = tlm; - swapOutFrames(frameIndex); - ble.startAdvertising(); - } else { - // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free - INFO("TLM(%d) cannot complete, %d is currently broadcasting", tlm, frameIndex); - FrameTypes x = tlm; - overflow.push(x); - } - } - - void stopAdvCallback(void) { - if (overflow.empty()) { - // if nothing left to transmit, stop - ble.stopAdvertising(); - advLock = false; // unlock lock - } else { - // transmit other packets at current time index - FrameTypes x = NONE; - overflow.pop(x); - INFO("Re-Transmitting %d", x); - swapOutFrames(x); - } - } - - /* - * Callback from onRadioNotification(), used to update the PDUCounter and process next state. - */ -#define EDDYSTONE_SWAPFRAME_DELAYMS 1 - void radioNotificationCallback(bool radioActive) { - // Update PDUCount - TlmPduCount++; - // True just before an frame is sent, false just after a frame is sent - if (radioActive) { - // Do Nothing - } else { - // Packet has been sent, disable advertising - stopAdv.attach_us(this, &EddystoneService::stopAdvCallback, 1); - } - } - - /* - * This function explicityly sets the parameters used by the Eddystone beacon. - * this function should be used in leu of the config service. - * - * @param bleIn ble object used to broadcast eddystone information - * @param beaconPeriodus is how often ble broadcasts are mde, in mili seconds - * @param txPowerLevel sets the broadcasting power level. - * - */ - EddystoneService(BLEDevice &bleIn, - uint16_t beaconPeriodus = 100, - uint8_t txPowerIn = 0) : - ble(bleIn), - advPeriodus(beaconPeriodus), - txPower(txPowerIn), - advLock(false), - frameIndex(NONE) { - } - - /* - * @breif this function starts eddystone advertising based on configured frames. - */ - void start(void) { - // Initialize Frame transition, start with URL to pass eddystone validator app on first try - if (urlIsSet) { - frameIndex = url; - urlTicker.attach(this, &EddystoneService::urlCallback, (float) advPeriodus / 1000.0f); - DBG("attached urlCallback every %d seconds", urlAdvPeriod); - } - if (uidIsSet) { - frameIndex = uid; - uidTicker.attach(this, &EddystoneService::uidCallback, uidAdvPeriod); - DBG("attached uidCallback every %d seconds", uidAdvPeriod); - } - if (tlmIsSet) { - frameIndex = tlm; - // Make double sure the PDUCount and TimeSinceBoot fields are set to zero at reset - updateTlmPduCount(0); - updateTlmTimeSinceBoot(0); - lastBootTimerRead = 0; - timeSinceBootTimer.start(); - tlmTicker.attach(this, &EddystoneService::tlmCallback, TlmAdvPeriod); - DBG("attached tlmCallback every %d seconds", TlmAdvPeriod); - } - if (NONE == frameIndex) { - MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_BLE, MBED_ERROR_CODE_BLE_NO_FRAME_INITIALIZED), "No Frames were Initialized! Please initialize a frame before starting an eddystone beacon."); - } - //uidRFU = 0; - - ble.setTxPower(txPower); - ble.gap().onRadioNotification(this, &EddystoneService::radioNotificationCallback); - } - -private: - - // Eddystone Variables - BLEDevice &ble; - uint16_t advPeriodus; - uint8_t txPower; - mbed::Timer timeSinceBootTimer; - volatile uint32_t lastBootTimerRead; - volatile bool advLock; - volatile FrameTypes frameIndex; - mbed::Timeout stopAdv; - - - // URI Frame Variables - uint8_t defaultUriDataLength; - UriData_t defaultUriData; - int8_t defaultUrlPower; - bool urlIsSet; // flag that enables / disable URI Frames - float urlAdvPeriod; // how long the url frame will be advertised for - mbed::Ticker urlTicker; - - // UID Frame Variables - UIDNamespaceID_t defaultUidNamespaceID; - UIDInstanceID_t defaultUidInstanceID; - int8_t defaultUidPower; - uint16_t uidRFU; - bool uidIsSet; // flag that enables / disable UID Frames - float uidAdvPeriod; // how long the uid frame will be advertised for - mbed::Ticker uidTicker; - - // TLM Frame Variables - uint8_t TlmVersion; - volatile uint16_t TlmBatteryVoltage; - volatile uint16_t TlmBeaconTemp; - volatile uint32_t TlmPduCount; - volatile uint32_t TlmTimeSinceBoot; - bool tlmIsSet; // flag that enables / disables TLM frames - float TlmAdvPeriod; // number of minutes between adv frames - mbed::Ticker tlmTicker; - -public: - /* - * Encode a human-readable URI into the binary format defined by URIBeacon spec (https://github.com/google/uribeacon/tree/master/specification). - */ - static void encodeURL(const char *uriDataIn, UriData_t uriDataOut, uint8_t &sizeofURIDataOut) { - DBG("Encode URL = %s", uriDataIn); - const char *prefixes[] = { - "http://www.", - "https://www.", - "http://", - "https://", - }; - const size_t NUM_PREFIXES = sizeof(prefixes) / sizeof(char *); - const char *suffixes[] = { - ".com/", - ".org/", - ".edu/", - ".net/", - ".info/", - ".biz/", - ".gov/", - ".com", - ".org", - ".edu", - ".net", - ".info", - ".biz", - ".gov" - }; - const size_t NUM_SUFFIXES = sizeof(suffixes) / sizeof(char *); - - sizeofURIDataOut = 0; - memset(uriDataOut, 0, sizeof(UriData_t)); - - if ((uriDataIn == NULL) || (strlen(uriDataIn) == 0)) { - return; - } - - /* - * handle prefix - */ - for (unsigned i = 0; i < NUM_PREFIXES; i++) { - size_t prefixLen = strlen(prefixes[i]); - if (strncmp(uriDataIn, prefixes[i], prefixLen) == 0) { - uriDataOut[sizeofURIDataOut++] = i; - uriDataIn += prefixLen; - break; - } - } - - /* - * handle suffixes - */ - while (*uriDataIn && (sizeofURIDataOut < URI_DATA_MAX)) { - /* check for suffix match */ - unsigned i; - for (i = 0; i < NUM_SUFFIXES; i++) { - size_t suffixLen = strlen(suffixes[i]); - if (strncmp(uriDataIn, suffixes[i], suffixLen) == 0) { - uriDataOut[sizeofURIDataOut++] = i; - uriDataIn += suffixLen; - break; /* from the for loop for checking against suffixes */ - } - } - /* This is the default case where we've got an ordinary character which doesn't match a suffix. */ - INFO("Encoding URI: No Suffix Found"); - if (i == NUM_SUFFIXES) { - uriDataOut[sizeofURIDataOut++] = *uriDataIn; - ++uriDataIn; - } - } - } -}; - -#endif // BLE_FEATURE_GATT_SERVER - -#endif // SERVICES_EDDYSTONEBEACON_H_ diff --git a/features/FEATURE_BLE/ble/services/UARTService.h b/features/FEATURE_BLE/ble/services/UARTService.h deleted file mode 100644 index 317bb29231b..00000000000 --- a/features/FEATURE_BLE/ble/services/UARTService.h +++ /dev/null @@ -1,233 +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 __BLE_UART_SERVICE_H__ -#define __BLE_UART_SERVICE_H__ - -#ifdef YOTTA_CFG_MBED_OS -#include "mbed-drivers/mbed.h" -#include "mbed-drivers/Stream.h" -#else -#include "Stream.h" -#endif - -#include "ble/UUID.h" -#include "ble/BLE.h" -#include "ble/pal/Deprecated.h" - -#if BLE_FEATURE_GATT_SERVER - -BLE_DEPRECATED_API_USE_BEGIN() - -extern const uint8_t UARTServiceBaseUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint16_t UARTServiceShortUUID; -extern const uint16_t UARTServiceTXCharacteristicShortUUID; -extern const uint16_t UARTServiceRXCharacteristicShortUUID; - -extern const uint8_t UARTServiceUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UARTServiceUUID_reversed[UUID::LENGTH_OF_LONG_UUID]; - -extern const uint8_t UARTServiceTXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UARTServiceRXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID]; - -/** - * @class UARTService. - * @brief BLE Service to enable UART over BLE. - * - * @deprecated This service is deprecated, and no replacement is currently available. - */ -MBED_DEPRECATED_SINCE( - "mbed-os-5.13", - "This service is deprecated, and no replacement is currently available." -) -class UARTService { -public: - /** Maximum length of data (in bytes) that the UART service module can transmit to the peer. */ - static const unsigned BLE_UART_SERVICE_MAX_DATA_LEN = (BLE_GATT_MTU_SIZE_DEFAULT - 3); - -public: - - /** - * @param _ble - * BLE object for the underlying controller. - */ - UARTService(BLE &_ble) : - ble(_ble), - receiveBuffer(), - sendBuffer(), - sendBufferIndex(0), - numBytesReceived(0), - receiveBufferIndex(0), - txCharacteristic(UARTServiceTXCharacteristicUUID, receiveBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), - rxCharacteristic(UARTServiceRXCharacteristicUUID, sendBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) { - GattCharacteristic *charTable[] = {&txCharacteristic, &rxCharacteristic}; - GattService uartService(UARTServiceUUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(uartService); - ble.onDataWritten(this, &UARTService::onDataWritten); - } - - /** - * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. - */ - uint16_t getTXCharacteristicHandle() { - return txCharacteristic.getValueAttribute().getHandle(); - } - - /** - * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. - */ - uint16_t getRXCharacteristicHandle() { - return rxCharacteristic.getValueAttribute().getHandle(); - } - - /** - * We attempt to collect bytes before pushing them to the UART RX - * characteristic; writing to the RX characteristic then generates - * notifications for the client. Updates made in quick succession to a - * notification-generating characteristic result in data being buffered - * in the Bluetooth stack as notifications are sent out. The stack has - * its limits for this buffering - typically a small number under 10. - * Collecting data into the sendBuffer buffer helps mitigate the rate of - * updates. But we shouldn't buffer a large amount of data before updating - * the characteristic, otherwise the client needs to turn around and make - * a long read request; this is because notifications include only the first - * 20 bytes of the updated data. - * - * @param _buffer The received update. - * @param length Number of characters to be appended. - * @return Number of characters appended to the rxCharacteristic. - */ - size_t write(const void *_buffer, size_t length) { - size_t origLength = length; - const uint8_t *buffer = static_cast(_buffer); - - if (ble.getGapState().connected) { - unsigned bufferIndex = 0; - while (length) { - unsigned bytesRemainingInSendBuffer = BLE_UART_SERVICE_MAX_DATA_LEN - sendBufferIndex; - unsigned bytesToCopy = (length < bytesRemainingInSendBuffer) ? length : bytesRemainingInSendBuffer; - - /* Copy bytes into sendBuffer. */ - memcpy(&sendBuffer[sendBufferIndex], &buffer[bufferIndex], bytesToCopy); - length -= bytesToCopy; - sendBufferIndex += bytesToCopy; - bufferIndex += bytesToCopy; - - /* Have we collected enough? */ - if ((sendBufferIndex == BLE_UART_SERVICE_MAX_DATA_LEN) || - // (sendBuffer[sendBufferIndex - 1] == '\r') || - (sendBuffer[sendBufferIndex - 1] == '\n')) { - ble.gattServer().write(getRXCharacteristicHandle(), static_cast(sendBuffer), sendBufferIndex); - sendBufferIndex = 0; - } - } - } - - return origLength; - } - - /** - * Helper function to write out strings. - * @param str The received string. - * @return Number of characters appended to the rxCharacteristic. - */ - size_t writeString(const char *str) { - return write(str, strlen(str)); - } - - /** - * Flush sendBuffer, i.e., forcefully write its contents to the UART RX - * characteristic even if the buffer is not full. - */ - void flush() { - if (ble.getGapState().connected) { - if (sendBufferIndex != 0) { - ble.gattServer().write(getRXCharacteristicHandle(), static_cast(sendBuffer), sendBufferIndex); - sendBufferIndex = 0; - } - } - } - - /** - * Override for Stream::_putc(). - * @param c - * This function writes the character c, cast to an unsigned char, to stream. - * @return - * The character written as an unsigned char cast to an int or EOF on error. - */ - int _putc(int c) { - return (write(&c, 1) == 1) ? 1 : EOF; - } - - /** - * Override for Stream::_getc(). - * @return - * The character read. - */ - int _getc() { - if (receiveBufferIndex == numBytesReceived) { - return EOF; - } - - return receiveBuffer[receiveBufferIndex++]; - } - -protected: - /** - * This callback allows the UART service to receive updates to the - * txCharacteristic. The application should forward the call to this - * function from the global onDataWritten() callback handler; if that's - * not used, this method can be used as a callback directly. - */ - void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == getTXCharacteristicHandle()) { - uint16_t bytesRead = params->len; - if (bytesRead <= BLE_UART_SERVICE_MAX_DATA_LEN) { - numBytesReceived = bytesRead; - receiveBufferIndex = 0; - memcpy(receiveBuffer, params->data, numBytesReceived); - } - } - } - -protected: - BLE &ble; - - uint8_t receiveBuffer[BLE_UART_SERVICE_MAX_DATA_LEN]; /**< The local buffer into which we receive - * inbound data before forwarding it to the - * application. */ - - uint8_t sendBuffer[BLE_UART_SERVICE_MAX_DATA_LEN]; /**< The local buffer into which outbound data is - * accumulated before being pushed to the - * rxCharacteristic. */ - uint8_t sendBufferIndex; - uint8_t numBytesReceived; - uint8_t receiveBufferIndex; - - GattCharacteristic txCharacteristic; /**< From the point of view of the external client, this is the characteristic - * they'd write into in order to communicate with this application. */ - GattCharacteristic rxCharacteristic; /**< From the point of view of the external client, this is the characteristic - * they'd read from in order to receive the bytes transmitted by this - * application. */ -}; - -BLE_DEPRECATED_API_USE_END() - -#endif // BLE_FEATURE_GATT_SERVER - -#endif /* #ifndef __BLE_UART_SERVICE_H__*/ diff --git a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h b/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h deleted file mode 100644 index 952ef1d2fed..00000000000 --- a/features/FEATURE_BLE/ble/services/URIBeaconConfigService.h +++ /dev/null @@ -1,494 +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 SERVICES_URIBEACONCONFIGSERVICE_H_ -#define SERVICES_URIBEACONCONFIGSERVICE_H_ - -#include "ble/BLE.h" -#include "ble/pal/Deprecated.h" - -#ifdef YOTTA_CFG_MBED_OS -#include "mbed-drivers/mbed.h" -#else - -#endif - -#if BLE_FEATURE_GATT_SERVER -#if BLE_ROLE_BROADCASTER - -BLE_DEPRECATED_API_USE_BEGIN() - -extern const uint8_t UUID_URI_BEACON_SERVICE[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_LOCK_STATE_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_LOCK_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_UNLOCK_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_URI_DATA_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_FLAGS_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_ADV_POWER_LEVELS_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_TX_POWER_MODE_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_BEACON_PERIOD_CHAR[UUID::LENGTH_OF_LONG_UUID]; -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. 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. - */ -MBED_DEPRECATED_SINCE( - "mbed-os-5.11", - "This service is deprecated, and no replacement is currently available." -) -class URIBeaconConfigService { - public: - /** - * @brief Transmission power modes for UriBeacon. - */ - static const uint8_t TX_POWER_MODE_LOWEST = 0; /*!< Lowest TX power mode. */ - static const uint8_t TX_POWER_MODE_LOW = 1; /*!< Low TX power mode. */ - static const uint8_t TX_POWER_MODE_MEDIUM = 2; /*!< Medium TX power mode. */ - static const uint8_t TX_POWER_MODE_HIGH = 3; /*!< High TX power mode. */ - static const unsigned NUM_POWER_MODES = 4; /*!< Number of power modes defined. */ - - static const int ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. - static const int SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets. - - typedef uint8_t Lock_t[16]; /* 128 bits. */ - typedef int8_t PowerLevels_t[NUM_POWER_MODES]; - - static const int URI_DATA_MAX = 18; - typedef uint8_t UriData_t[URI_DATA_MAX]; - - struct Params_t { - Lock_t lock; - uint8_t uriDataLength; - UriData_t uriData; - uint8_t flags; - PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels. - uint8_t txPowerMode; // Firmware power levels used with setTxPower(). - uint16_t beaconPeriod; - }; - - /** - * @param[in] bleIn - * BLE object for the underlying controller. - * @param[in,out] paramsIn - * Reference to application-visible beacon state, loaded - * from persistent storage at startup. - * @param[in] resetToDefaultsFlag - * Applies to the state of the 'paramsIn' parameter. - * If true, it indicates that paramsIn is potentially - * un-initialized, and default values should be used - * instead. Otherwise, paramsIn overrides the defaults. - * @param[in] defaultURIDataIn - * 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, - const char *defaultURIDataIn, - PowerLevels_t &defaultAdvPowerLevelsIn) : - ble(bleIn), - params(paramsIn), - defaultUriDataLength(), - defaultUriData(), - defaultAdvPowerLevels(defaultAdvPowerLevelsIn), - initSucceeded(false), - resetFlag(), - lockedStateChar(UUID_LOCK_STATE_CHAR, &lockedState), - lockChar(UUID_LOCK_CHAR, ¶ms.lock), - uriDataChar(UUID_URI_DATA_CHAR, params.uriData, 0, URI_DATA_MAX, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE), - unlockChar(UUID_UNLOCK_CHAR, ¶ms.lock), - flagsChar(UUID_FLAGS_CHAR, ¶ms.flags), - advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), - txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), - beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), - resetChar(UUID_RESET_CHAR, &resetFlag) { - - encodeURI(defaultURIDataIn, defaultUriData, defaultUriDataLength); - if (defaultUriDataLength > URI_DATA_MAX) { - return; - } - - if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { - resetToDefaultsFlag = true; - } - if (resetToDefaultsFlag) { - resetToDefaults(); - } else { - updateCharacteristicValues(); - } - - lockedState = isLocked(); - - lockChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::lockAuthorizationCallback); - unlockChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::unlockAuthorizationCallback); - uriDataChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::uriDataWriteAuthorizationCallback); - flagsChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback); - advPowerLevelsChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback); - txPowerModeChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::powerModeAuthorizationCallback); - beaconPeriodChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback); - resetChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback); - - static GattCharacteristic *charTable[] = { - &lockedStateChar, &lockChar, &unlockChar, &uriDataChar, - &flagsChar, &advPowerLevelsChar, &txPowerModeChar, &beaconPeriodChar, &resetChar - }; - - GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(configService); - ble.onDataWritten(this, &URIBeaconConfigService::onDataWrittenCallback); - - setupURIBeaconConfigAdvertisements(); /* Set up advertising for the config service. */ - - initSucceeded = true; - } - - bool configuredSuccessfully(void) const { - return initSucceeded; - } - - /* Start out by advertising the config service for a limited time after - * startup. Then switch to the normal non-connectible beacon functionality. - */ - void setupURIBeaconConfigAdvertisements() - { - const char DEVICE_NAME[] = "mUriBeacon Config"; - - ble.gap().clearAdvertisingPayload(); - - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); - - // UUID is in different order in the ADV frame (!) - uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)]; - for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) { - reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1]; - } - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID)); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG); - ble.gap().accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast(&DEVICE_NAME), sizeof(DEVICE_NAME)); - ble.gap().accumulateScanResponse(GapAdvertisingData::TX_POWER_LEVEL, - reinterpret_cast(&defaultAdvPowerLevels[URIBeaconConfigService::TX_POWER_MODE_LOW]), - sizeof(uint8_t)); - - ble.gap().setTxPower(params.advPowerLevels[params.txPowerMode]); - ble.gap().setDeviceName(reinterpret_cast(&DEVICE_NAME)); - ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); - ble.gap().setAdvertisingInterval(GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(ADVERTISING_INTERVAL_MSEC)); - } - - /* Helper function to switch to the non-connectible normal mode for UriBeacon. This gets called after a timeout. */ - void setupURIBeaconAdvertisements() - { - /* Reinitialize the BLE stack. This will clear away the existing services and advertising state. */ - ble.shutdown(); - ble.init(); - - // Fields from the service. - unsigned beaconPeriod = params.beaconPeriod; - unsigned txPowerMode = params.txPowerMode; - unsigned uriDataLength = params.uriDataLength; - URIBeaconConfigService::UriData_t &uriData = params.uriData; - URIBeaconConfigService::PowerLevels_t &advPowerLevels = params.advPowerLevels; - uint8_t flags = params.flags; - - extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* Forward declaration; necessary to avoid a circular dependency. */ - saveURIBeaconConfigParams(¶ms); - - ble.gap().clearAdvertisingPayload(); - ble.gap().setTxPower(params.advPowerLevels[params.txPowerMode]); - ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); - ble.gap().setAdvertisingInterval(beaconPeriod); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, BEACON_UUID, sizeof(BEACON_UUID)); - - uint8_t serviceData[SERVICE_DATA_MAX]; - unsigned serviceDataLen = 0; - serviceData[serviceDataLen++] = BEACON_UUID[0]; - serviceData[serviceDataLen++] = BEACON_UUID[1]; - serviceData[serviceDataLen++] = flags; - serviceData[serviceDataLen++] = advPowerLevels[txPowerMode]; - for (unsigned j = 0; j < uriDataLength; j++) { - serviceData[serviceDataLen++] = uriData[j]; - } - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, serviceData, serviceDataLen); - } - - private: - // True if the lock bits are non-zero. - bool isLocked() { - Lock_t testLock; - memset(testLock, 0, sizeof(Lock_t)); - return memcmp(params.lock, testLock, sizeof(Lock_t)); - } - - /* - * This callback is invoked when a GATT client attempts to modify any of the - * characteristics of this service. These attempts are also applied to - * the internal state of this service object. - */ - void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) { - uint16_t handle = writeParams->handle; - - if (handle == lockChar.getValueHandle()) { - // Validated earlier, - memcpy(params.lock, writeParams->data, sizeof(Lock_t)); - // Use isLocked() in case bits are being set to all zeros. - lockedState = isLocked(); - } else if (handle == unlockChar.getValueHandle()) { - // Validated earlier. - memset(params.lock, 0, sizeof(Lock_t)); - lockedState = false; - } else if (handle == uriDataChar.getValueHandle()) { - params.uriDataLength = writeParams->len; - memcpy(params.uriData, writeParams->data, params.uriDataLength); - } else if (handle == flagsChar.getValueHandle()) { - params.flags = *(writeParams->data); - } else if (handle == advPowerLevelsChar.getValueHandle()) { - memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t)); - } else if (handle == txPowerModeChar.getValueHandle()) { - params.txPowerMode = *(writeParams->data); - } else if (handle == beaconPeriodChar.getValueHandle()) { - params.beaconPeriod = *((uint16_t *)(writeParams->data)); - - /* Remap beaconPeriod to within permissible bounds if necessary. */ - if (params.beaconPeriod != 0) { - bool paramsUpdated = false; - if (params.beaconPeriod < ble.gap().getMinAdvertisingInterval()) { - params.beaconPeriod = ble.gap().getMinAdvertisingInterval(); - paramsUpdated = true; - } else if (params.beaconPeriod > ble.gap().getMaxAdvertisingInterval()) { - params.beaconPeriod = ble.gap().getMaxAdvertisingInterval(); - paramsUpdated = true; - } - if (paramsUpdated) { - ble.gattServer().write(beaconPeriodChar.getValueHandle(), reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); - } - } - } else if (handle == resetChar.getValueHandle()) { - resetToDefaults(); - } - } - - /* - * Reset the default values. - */ - void resetToDefaults(void) { - lockedState = false; - memset(params.lock, 0, sizeof(Lock_t)); - memcpy(params.uriData, defaultUriData, URI_DATA_MAX); - params.uriDataLength = defaultUriDataLength; - params.flags = 0; - memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t)); - params.txPowerMode = TX_POWER_MODE_LOW; - params.beaconPeriod = 1000; - updateCharacteristicValues(); - } - - /* - * Internal helper function used to update the GATT database following any - * change to the internal state of the service object. - */ - void updateCharacteristicValues(void) { - ble.gattServer().write(lockedStateChar.getValueHandle(), &lockedState, 1); - ble.gattServer().write(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); - ble.gattServer().write(flagsChar.getValueHandle(), ¶ms.flags, 1); - ble.gattServer().write(beaconPeriodChar.getValueHandle(), - reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); - ble.gattServer().write(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); - ble.gattServer().write(advPowerLevelsChar.getValueHandle(), - reinterpret_cast(params.advPowerLevels), sizeof(PowerLevels_t)); - } - -protected: - void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(Lock_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - - void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (!lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } else if (authParams->len != sizeof(Lock_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else if (memcmp(authParams->data, params.lock, sizeof(Lock_t)) != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(uint8_t)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else if (*((uint8_t *)authParams->data) >= NUM_POWER_MODES) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - - template - void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (lockedState) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; - } else if (authParams->len != sizeof(T)) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; - } else if (authParams->offset != 0) { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; - } else { - authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; - } - } - -protected: - BLE &ble; - Params_t ¶ms; - - size_t defaultUriDataLength; // Default value that is restored on reset. - UriData_t defaultUriData; // Default value that is restored on reset. - PowerLevels_t &defaultAdvPowerLevels; // Default value that is restored on reset. - - uint8_t lockedState; - bool initSucceeded; - uint8_t resetFlag; - - ReadOnlyGattCharacteristic lockedStateChar; - WriteOnlyGattCharacteristic lockChar; - GattCharacteristic uriDataChar; - WriteOnlyGattCharacteristic unlockChar; - ReadWriteGattCharacteristic flagsChar; - ReadWriteGattCharacteristic advPowerLevelsChar; - ReadWriteGattCharacteristic txPowerModeChar; - ReadWriteGattCharacteristic beaconPeriodChar; - WriteOnlyGattCharacteristic resetChar; - -public: - /* - * Encode a human-readable URI into the binary format defined by the UriBeacon spec (https://github.com/google/uribeacon/tree/master/specification). - */ - static void encodeURI(const char *uriDataIn, UriData_t uriDataOut, size_t &sizeofURIDataOut) { - const char *prefixes[] = { - "http://www.", - "https://www.", - "http://", - "https://", - "urn:uuid:" - }; - const size_t NUM_PREFIXES = sizeof(prefixes) / sizeof(char *); - const char *suffixes[] = { - ".com/", - ".org/", - ".edu/", - ".net/", - ".info/", - ".biz/", - ".gov/", - ".com", - ".org", - ".edu", - ".net", - ".info", - ".biz", - ".gov" - }; - const size_t NUM_SUFFIXES = sizeof(suffixes) / sizeof(char *); - - sizeofURIDataOut = 0; - memset(uriDataOut, 0, sizeof(UriData_t)); - - if ((uriDataIn == NULL) || (strlen(uriDataIn) == 0)) { - return; - } - - /* - * handle prefix - */ - for (unsigned i = 0; i < NUM_PREFIXES; i++) { - size_t prefixLen = strlen(prefixes[i]); - if (strncmp(uriDataIn, prefixes[i], prefixLen) == 0) { - uriDataOut[sizeofURIDataOut++] = i; - uriDataIn += prefixLen; - break; - } - } - - /* - * Handle suffixes. - */ - while (*uriDataIn && (sizeofURIDataOut < URI_DATA_MAX)) { - /* check for suffix match */ - unsigned i; - for (i = 0; i < NUM_SUFFIXES; i++) { - size_t suffixLen = strlen(suffixes[i]); - if (strncmp(uriDataIn, suffixes[i], suffixLen) == 0) { - uriDataOut[sizeofURIDataOut++] = i; - uriDataIn += suffixLen; - break; /* From the for loop for checking against suffixes. */ - } - } - /* This is the default case where we've got an ordinary character that doesn't match a suffix. */ - if (i == NUM_SUFFIXES) { - uriDataOut[sizeofURIDataOut++] = *uriDataIn; - ++uriDataIn; - } - } - } -}; - -BLE_DEPRECATED_API_USE_END() - -#endif // BLE_ROLE_BROADCASTER -#endif // BLE_FEATURE_GATT_SERVER - -#endif // SERVICES_URIBEACONCONFIGSERVICE_H_ diff --git a/features/FEATURE_BLE/ble/services/iBeacon.h b/features/FEATURE_BLE/ble/services/iBeacon.h deleted file mode 100644 index 9aac5b60b3d..00000000000 --- a/features/FEATURE_BLE/ble/services/iBeacon.h +++ /dev/null @@ -1,263 +0,0 @@ -/* mbed Microcontroller Library -* Copyright (c) 2006-2015 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_BLE_IBEACON_H__ -#define MBED_BLE_IBEACON_H__ - -#include "cmsis_compiler.h" -#include "ble/BLE.h" -#include "ble/pal/Deprecated.h" - -#if BLE_FEATURE_GATT_SERVER - -BLE_DEPRECATED_API_USE_BEGIN() - -/** - * iBeacon Service. - * - * @par Purpose - * - * iBeacons are Bluetooth Low Energy (BLE) devices advertising an identification - * number generally used to determine the location of devices or physical objects - * near a mobile phone user. - * - * iOS scans for iBeacon devices in a background task and notifies apps - * that subscribe to a specific region when a device enters or leaves an area. Apps may - * use this information to display context-aware content to users. - * - * As an example, a museum can deploy an app that informs the user when one of - * its exhibitions is entered and then displays specific information about exposed - * pieces of art when the user is sufficiently close to them. - * - * @par Positioning - * - * Location information is hierarchically structured. A UUID specific to the - * application and its deployment is used to identify a region. That region - * usually identifies an organization. The region is divided into subregions - * identified by a major ID. The subregion contains related points of interest - * which a minor ID distinguishes. - * - * As an example, a city willing to improve tourist's experience can deploy a fleet - * of iBeacons in relevant touristic locations it operates. The UUID may - * identify a place managed by the city. The major ID would identify the place; - * it can be a museum, a historic monument, a metro station and so on. The minor ID - * would identify a specific spot within a specific city place. It can be a - * piece of art, a ticket dispenser or a relevant point of interest. - * - * Each iBeacon device is physically attached to the spot it locates and - * advertises the triplet UUID, major ID and minor ID. - * - * @par Proximity - * - * The beacon advertises the signal strength measured by an iOS device at a - * distance of one meter. iOS uses this information to approximate the - * proximity to a given beacon: - * - Immediate: The beacon is less than one meter away from the user. - * - Near: The beacon is one to three meters away from the user. - * - Far: The user is not near the beacon; the distance highly depends on - * the physical environment. - * - * Ideally, beacons should be calibrated at their deployment location because the - * surrounding environment affects the strength of the advertised signal. - * - * @par Usage - * - * Mbed OS applications can use this class to configure a device to broadcast - * advertising packets mimicking an iBeacon. The construction automatically - * creates the payload identifying the beacon and registers it as part of the - * advertising payload of the device. - * - * Beacon configuration and advertising commencement is left to the user. - * - * @attention If you are interested in manufacturing iBeacons, you must obtain a - * license from Apple. More information at https://developer.apple.com/ibeacon/. - * The license 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: -#if !(DOXYGEN_ONLY) - /** - * Data buffer of a location UUID. - */ - typedef const uint8_t LocationUUID_t[16]; - - /** - * iBeacon payload builder. - * - * This data structure contains the payload of an iBeacon. The payload is - * built at construction time and application code can set up an iBeacon by - * injecting the raw field into the GAP advertising payload as a - * GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA. - */ - union Payload { - /** - * Raw data of the payload. - */ - uint8_t raw[25]; - struct { - /** - * Beacon manufacturer identifier. - */ - uint16_t companyID; - - /** - * Packet ID; equal to 2 for an iBeacon. - */ - uint8_t ID; - - /** - * Length of the remaining data present in the payload. - */ - uint8_t len; - - /** - * Beacon UUID. - */ - uint8_t proximityUUID[16]; - - /** - * Beacon major group ID. - */ - uint16_t majorNumber; - - /** - * Beacon minor ID. - */ - uint16_t minorNumber; - - /** - * Tx power received at 1 meter; in dBm. - */ - uint8_t txPower; - }; - - /** - * Assemble an iBeacon payload. - * - * @param[in] uuid Beacon network ID. iBeacon operators use this value - * to group their iBeacons into a single network, a single region, and - * identify their organization among others. - * - * @param[in] majNum Beacon major group ID. iBeacon exploitants may use - * this field to divide the region into subregions, and their network into - * subnetworks. - * - * @param[in] minNum Identifier of the Beacon in its subregion. - * - * @param[in] transmitPower Measured transmit power of the beacon at 1 - * meter. Scanners use this parameter to approximate the distance - * to the beacon. - * - * @param[in] companyIDIn ID of the beacon manufacturer. - */ - Payload( - LocationUUID_t uuid, - uint16_t majNum, - uint16_t minNum, - uint8_t transmitPower, - uint16_t companyIDIn - ) : companyID(companyIDIn), - ID(0x02), - len(0x15), - majorNumber(__REV16(majNum)), - minorNumber(__REV16(minNum)), - txPower(transmitPower) - { - memcpy(proximityUUID, uuid, sizeof(LocationUUID_t)); - } - }; -#endif //#if !(DOXYGEN_ONLY) -public: - /** - * Construct an iBeacon::Payload and register it into Gap. - * - * @param[in] _ble The BLE interface to configure with the iBeacon payload. - * - * @param[in] uuid Beacon network ID. iBeacon operators use this value - * to group their iBeacons into a single network, a single region, and - * identify their organization among others. - * - * @param[in] majNum Beacon major group ID. iBeacon fleet operators may use - * this field to divide the region into subregions, and their network into - * subnetworks. - * - * @param[in] minNum Identifier of the Beacon in its subregion. - * - * @param[in] txP Measured transmit power of the beacon at distance of - * one meter. Scanners use this parameter to approximate the distance - * 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, - uint16_t majNum, - uint16_t minNum, - uint8_t txP = 0xC8, - uint16_t compID = 0x004C - ) : ble(_ble), - data(uuid, majNum, minNum, txP, compID) - { - // Generate the 0x020106 part of the iBeacon Prefix. - ble.accumulateAdvertisingPayload( - GapAdvertisingData::BREDR_NOT_SUPPORTED | - GapAdvertisingData::LE_GENERAL_DISCOVERABLE - ); - // Generate the 0x1AFF part of the iBeacon Prefix. - ble.accumulateAdvertisingPayload( - GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, - data.raw, - sizeof(data.raw) - ); - - // Set advertising type. - ble.setAdvertisingType( - GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED - ); - } - -protected: - BLE &ble; - Payload data; -}; - -/** - * iBeacon alias. - * - * @deprecated Please use iBeacon directly. This alias may be dropped from a - * future release. - */ -typedef iBeacon iBeaconService; - -BLE_DEPRECATED_API_USE_END() - -#endif // BLE_FEATURE_GATT_SERVER - -#endif //MBED_BLE_IBEACON_H__ diff --git a/features/FEATURE_BLE/source/BLE.cpp b/features/FEATURE_BLE/source/BLE.cpp index 565716f7771..ddec04690a7 100644 --- a/features/FEATURE_BLE/source/BLE.cpp +++ b/features/FEATURE_BLE/source/BLE.cpp @@ -146,18 +146,14 @@ BLE::Instance(InstanceID_t id) static BLE *singletons[NUM_INSTANCES]; if (id < NUM_INSTANCES) { if (singletons[id] == NULL) { -BLE_DEPRECATED_API_USE_BEGIN() singletons[id] = new BLE(id); /* This object will never be freed. */ -BLE_DEPRECATED_API_USE_END() } return *singletons[id]; } /* we come here only in the case of a bad interfaceID. */ -BLE_DEPRECATED_API_USE_BEGIN() static BLE badSingleton(NUM_INSTANCES /* this is a bad index; and will result in a NULL transport. */); -BLE_DEPRECATED_API_USE_END() return badSingleton; } @@ -281,15 +277,6 @@ SecurityManager& BLE::securityManager() #endif // BLE_FEATURE_SECURITY -void BLE::waitForEvent(void) -{ - if (!transport) { - MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_BLE, MBED_ERROR_CODE_BLE_BACKEND_NOT_INITIALIZED), "bad handle to underlying transport"); - } - - transport->waitForEvent(); -} - void BLE::processEvents() { core_util_critical_section_enter(); @@ -341,11 +328,6 @@ void BLE::signalEventsToProcess() } } -// start of deprecated functions - -BLE_DEPRECATED_API_USE_BEGIN() - -// NOTE: move and remove deprecation once private BLE::BLE(InstanceID_t instanceIDIn) : instanceID(instanceIDIn), transport(), whenEventsToProcess(defaultSchedulingCallback), event_signaled(false) @@ -362,165 +344,3 @@ BLE::BLE(InstanceID_t instanceIDIn) : instanceID(instanceIDIn), transport(), } } -ble_error_t BLE::setAddress( - BLEProtocol::AddressType_t type, - const BLEProtocol::AddressBytes_t address -) { - return gap().setAddress(type, address); -} - -#if BLE_ROLE_CENTRAL -ble_error_t BLE::connect( - const BLEProtocol::AddressBytes_t peerAddr, - BLEProtocol::AddressType_t peerAddrType, - const Gap::ConnectionParams_t *connectionParams, - const GapScanningParams *scanParams -) { - return gap().connect(peerAddr, peerAddrType, connectionParams, scanParams); -} -#endif // BLE_ROLE_CENTRAL - -#if BLE_FEATURE_CONNECTABLE -ble_error_t BLE::disconnect(Gap::DisconnectionReason_t reason) { - return gap().disconnect(reason); -} -#endif // BLE_FEATURE_CONNECTABLE - -Gap::GapState_t BLE::getGapState(void) const { - return gap().getState(); -} - -#if BLE_ROLE_BROADCASTER -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(); -} -#endif // BLE_ROLE_BROADCASTER - -#if BLE_ROLE_OBSERVER -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); -} -#endif // BLE_ROLE_OBSERVER - -#if BLE_FEATURE_CONNECTABLE -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); -} -#endif // BLE_FEATURE_CONNECTABLE - -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); -} - -#if BLE_FEATURE_CONNECTABLE -void BLE::onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback) { - gap().onDisconnection(disconnectionCallback); -} -#endif // BLE_FEATURE_CONNECTABLE - -void BLE::onRadioNotification(void (*callback)(bool)) { - gap().onRadioNotification(callback); -} - - -BLE_DEPRECATED_API_USE_END() - diff --git a/features/FEATURE_BLE/source/services/DFUService.cpp b/features/FEATURE_BLE/source/services/DFUService.cpp deleted file mode 100644 index f00d80b252d..00000000000 --- a/features/FEATURE_BLE/source/services/DFUService.cpp +++ /dev/null @@ -1,48 +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. - */ - -#ifdef TARGET_NRF51822 /* DFU only supported on nrf51 platforms */ - -#if BLE_FEATURE_GATT_SERVER - -#include "ble/services/DFUService.h" - -const uint8_t DFUServiceBaseUUID[] = { - 0x00, 0x00, 0x00, 0x00, 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint16_t DFUServiceShortUUID = 0x1530; -const uint16_t DFUServiceControlCharacteristicShortUUID = 0x1531; -const uint16_t DFUServicePacketCharacteristicShortUUID = 0x1532; - -const uint8_t DFUServiceUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServiceShortUUID >> 8), (uint8_t)(DFUServiceShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint8_t DFUServiceControlCharacteristicUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServiceControlCharacteristicShortUUID >> 8), (uint8_t)(DFUServiceControlCharacteristicShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint8_t DFUServicePacketCharacteristicUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServicePacketCharacteristicShortUUID >> 8), (uint8_t)(DFUServicePacketCharacteristicShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; - -DFUService::ResetPrepare_t DFUService::handoverCallback = NULL; - -#endif // BLE_FEATURE_GATT_SERVER - -#endif /* #ifdef TARGET_NRF51822 */ diff --git a/features/FEATURE_BLE/source/services/UARTService.cpp b/features/FEATURE_BLE/source/services/UARTService.cpp deleted file mode 100644 index e8e6ba5002b..00000000000 --- a/features/FEATURE_BLE/source/services/UARTService.cpp +++ /dev/null @@ -1,46 +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. - */ - - -#if BLE_FEATURE_GATT_SERVER - -#include "ble/services/UARTService.h" - -const uint8_t UARTServiceBaseUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, 0x00, 0x00, 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint16_t UARTServiceShortUUID = 0x0001; -const uint16_t UARTServiceTXCharacteristicShortUUID = 0x0002; -const uint16_t UARTServiceRXCharacteristicShortUUID = 0x0003; -const uint8_t UARTServiceUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceShortUUID >> 8), (uint8_t)(UARTServiceShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint8_t UARTServiceUUID_reversed[UUID::LENGTH_OF_LONG_UUID] = { - 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, - 0x93, 0xF3, 0xA3, 0xB5, (uint8_t)(UARTServiceShortUUID & 0xFF), (uint8_t)(UARTServiceShortUUID >> 8), 0x40, 0x6E -}; -const uint8_t UARTServiceTXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceTXCharacteristicShortUUID >> 8), (uint8_t)(UARTServiceTXCharacteristicShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint8_t UARTServiceRXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceRXCharacteristicShortUUID >> 8), (uint8_t)(UARTServiceRXCharacteristicShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; - -#endif // BLE_FEATURE_GATT_SERVER diff --git a/features/FEATURE_BLE/source/services/URIBeaconConfigService.cpp b/features/FEATURE_BLE/source/services/URIBeaconConfigService.cpp deleted file mode 100644 index f94f6a4a7d7..00000000000 --- a/features/FEATURE_BLE/source/services/URIBeaconConfigService.cpp +++ /dev/null @@ -1,42 +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. - */ - - -#if BLE_FEATURE_GATT_SERVER -#if BLE_ROLE_BROADCASTER - -#include "ble/services/URIBeaconConfigService.h" - -#define UUID_URI_BEACON(FIRST, SECOND) { \ - 0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba, \ - 0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8, \ -} - -const uint8_t UUID_URI_BEACON_SERVICE[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x80); -const uint8_t UUID_LOCK_STATE_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x81); -const uint8_t UUID_LOCK_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x82); -const uint8_t UUID_UNLOCK_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x83); -const uint8_t UUID_URI_DATA_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x84); -const uint8_t UUID_FLAGS_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x85); -const uint8_t UUID_ADV_POWER_LEVELS_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x86); -const uint8_t UUID_TX_POWER_MODE_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x87); -const uint8_t UUID_BEACON_PERIOD_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x88); -const uint8_t UUID_RESET_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x89); - -const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)] = {0xD8, 0xFE}; - -#endif // BLE_ROLE_BROADCASTER -#endif // BLE_FEATURE_GATT_SERVER