takashi kadono / Mbed OS Nucleo_446

Dependencies:   ssd1331

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers Gap.h Source File

Gap.h

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2013 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #ifndef MBED_BLE_GAP_H__
00018 #define MBED_BLE_GAP_H__
00019 
00020 #include "BLETypes.h"
00021 #include "BLEProtocol.h"
00022 #include "GapAdvertisingData.h"
00023 #include "GapAdvertisingParams.h"
00024 #include "GapScanningParams.h"
00025 #include "GapEvents.h"
00026 #include "CallChainOfFunctionPointersWithContext.h"
00027 #include "FunctionPointerWithContext.h "
00028 #include "platform/mbed_toolchain.h"
00029 
00030 /* Forward declarations for classes that are only used for pointers or
00031    references. */
00032 class GapAdvertisingParams;
00033 class GapScanningParams;
00034 class GapAdvertisingData;
00035 
00036 /**
00037  * @addtogroup ble
00038  * @{
00039  * @addtogroup gap
00040  * @{
00041  */
00042 
00043 /**
00044  * Define device discovery, connection and link management procedures.
00045  *
00046  * - Device discovery: A device can advertise nearby peers of its existence,
00047  * identity and capabilities. Similarly, a device can scan its environment to
00048  * find advertising peers. The information acquired during the scan helps to
00049  * identify peers and understand their use. A scanner may acquire more information
00050  * about an advertising peer by sending a scan request. If the peer accepts scan
00051  * requests, it may reply with additional information about its state.
00052  *
00053  * - Connection: A bluetooth device can establish a connection to a connectable
00054  * advertising peer. Once the connection is established, both devices can
00055  * communicate using the GATT protocol. The GATT protocol allows connected
00056  * devices to expose a set of states that the other peer can discover, read and write.
00057  *
00058  * - Link Management: Connected devices may drop the connection and may adjust
00059  * connection parameters according to the power envelop needed for their
00060  * application.
00061  *
00062  * @par Accessing gap
00063  *
00064  * Instance of a Gap class for a given BLE device should be accessed using
00065  * BLE::gap(). The reference returned remains valid until the BLE instance
00066  * shut down (see BLE::shutdown()).
00067  *
00068  * @code
00069  * // assuming ble_device has been initialized
00070  * BLE& ble_device;
00071  *
00072  * Gap& gap = ble_device.gap();
00073  * @endcode
00074  *
00075  * @par Advertising
00076  *
00077  * Advertising consists of broadcasting at a regular interval a small amount of
00078  * data containing valuable informations about the device. These packets may be
00079  * scanned by peer devices listening on BLE advertising channels.
00080  *
00081  * Scanners may also request additional information from a device advertising by
00082  * sending a scan request. If the broadcaster accepts scan requests, it can reply
00083  * with a scan response packet containing additional information.
00084  *
00085  * @code
00086  * // assuming gap has been initialized
00087  * Gap& gap;
00088  *
00089  * // construct the packet to advertise
00090  * GapAdvertisingData advertising_data;
00091  *
00092  * // Add advertiser flags
00093  * advertising_data.addFlags(
00094  *    GapAdvertisingData::LE_GENERAL_DISCOVERABLE |
00095  *    GapAdvertisingData::BREDR_NOT_SUPPORTED
00096  * );
00097  *
00098  * // Add the name of the device to the advertising data
00099  * static const uint8_t device_name[] = "HRM";
00100  * advertising_data.addData(
00101  *     GapAdvertisingData::COMPLETE_LOCAL_NAME,
00102  *     device_name,
00103  *     sizeof(device_name)
00104  * );
00105  *
00106  * // set the advertising data in the gap instance, they will be used when
00107  * // advertising starts.
00108  * gap.setAdvertisingPayload(advertising_data);
00109  *
00110  * // Configure the advertising procedure
00111  * GapAdvertisingParams advertising_params(
00112  *     GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED, // type of advertising
00113  *     GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(1000), // interval
00114  *     0 // The advertising procedure will not timeout
00115  * );
00116  *
00117  * gap.setAdvertisingParams(advertising_params);
00118  *
00119  * // start the advertising procedure, the device will advertise its flag and the
00120  * // name "HRM". Other peers will also be allowed to connect to it.
00121  * gap.startAdvertising();
00122  * @endcode
00123  *
00124  * @par Privacy
00125  *
00126  * Privacy is a feature that allows a device to avoid being tracked by other
00127  * (untrusted) devices. The device achieves it by periodically generating a
00128  * new random address. The random address may be a resolvable random address,
00129  * enabling trusted devices to recognise it as belonging to the same
00130  * device. These trusted devices receive an Identity Resolution Key (IRK)
00131  * during pairing. This is handled by the SecurityManager and relies on the
00132  * other device accepting and storing the IRK.
00133  *
00134  * Privacy needs to be enabled by calling enablePrivacy() after having
00135  * initialised the SecurityManager since privacy requires SecurityManager
00136  * to handle IRKs. The behaviour of privacy enabled devices is set by
00137  * using setCentralPrivacyConfiguration() which specifies what the device
00138  * should be with devices using random addresses. Random addresses
00139  * generated by privacy enabled device can be of two types: resolvable
00140  * (by devices who have the IRK) and unresolvable. Unresolvable addresses
00141  * can't be used for connecting and connectable advertising therefore a
00142  * resolvable one will be used for these regardless of the privacy
00143  * configuration.
00144  *
00145  * @par Scanning
00146  *
00147  * Scanning consist of listening for peer advertising packets. From a scan, a
00148  * device can identify devices available in its environment.
00149  *
00150  * If the device scans actively, then it will send scan request to scannable
00151  * advertisers and collect their scan response.
00152  *
00153  * @code
00154  * // assuming gap has been initialized
00155  * Gap& gap;
00156  *
00157  * // Handle advertising packet by dumping their content
00158  * void handle_advertising_packet(const AdvertisementCallbackParams_t* packet)
00159  * {
00160  *    printf("Packet received: \r\n");
00161  *    printf("  - peer address: %02X:%02X:%02X:%02X:%02X:%02X\r\n",
00162  *           packet->peerAddr[5], packet->peerAddr[4], packet->peerAddr[3],
00163  *           packet->peerAddr[2], packet->peerAddr[1], packet->peerAddr[0]);
00164  *    printf("  - rssi: %d", packet->rssi);
00165  *    printf("  - scan response: %s\r\n", packet->isScanresponse ? "true" : "false");
00166  *    printf("  - advertising type: %d\r\n", packet->type);
00167  *    printf("  - advertising type: %d\r\n", packet->type);
00168  *    printf("  - Advertising data: \r\n");
00169  *
00170  *    // parse advertising data, it is a succession of AD structures where
00171  *    // the first byte is the size of the AD structure, the second byte the
00172  *    // type of the data and remaining bytes are the value.
00173  *
00174  *    for (size_t i = 0; i < packet->advertisingDataLen; i += packet->advertisingData[i]) {
00175  *        printf("    - type: 0X%02X, data: ", packet->advertisingData[i + 1]);
00176  *        for (size_t j = 0; j < packet->advertisingData[i] - 2; ++j) {
00177  *            printf("0X%02X ", packet->advertisingData[i + 2 + j]);
00178  *        }
00179  *        printf("\r\n");
00180  *    }
00181  * }
00182  *
00183  * // set the scan parameters
00184  * gap.setScanParams(
00185  *      100, // interval between two scan window in ms
00186  *      50,  // scan window: period during which the device listen for advertising packets.
00187  *      0,   // the scan process never ends
00188  *      true // the device sends scan request to scannable peers.
00189  * );
00190  *
00191  * // start the scan procedure
00192  * gap.startScan(handle_advertising_packet);
00193  * @endcode
00194  *
00195  * @par Connection event handling
00196  *
00197  * A peer may connect device advertising connectable packets. The
00198  * advertising procedure ends as soon as the device is connected.
00199  *
00200  * A device accepting a connection request from a peer is named a peripheral,
00201  * and the device initiating the connection is named a central.
00202  *
00203  * Peripheral and central receive a connection event when the connection is
00204  * effective.
00205  *
00206  * @code
00207  * Gap& gap;
00208  *
00209  * // handle connection event
00210  * void when_connected(const ConnectionCallbackParams_t *connection_event) {
00211  *    // If this callback is entered, then the connection to a peer is effective.
00212  * }
00213  *
00214  * // register connection event handler, which will be invoked whether the device
00215  * // acts as a central or a peripheral
00216  * gap.onConnection(when_connected);
00217  * @endcode
00218  *
00219  * @par Connection initiation
00220  *
00221  * Connection is initiated central devices.
00222  *
00223  * @code
00224  * // assuming gap has been initialized
00225  * Gap& gap;
00226  *
00227  * // Handle the connection event
00228  * void handle_connection(const ConnectionCallbackParams_t* connection_event)
00229  * {
00230  *    // event handling
00231  * }
00232  *
00233  * // Handle advertising packet: connect to the first connectable device
00234  * void handle_advertising_packet(const AdvertisementCallbackParams_t* packet)
00235  * {
00236  *    if (packet->type != GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED) {
00237  *       return;
00238  *    }
00239  *
00240  *    // register connection event handler
00241  *    gap.onConnection(handle_connection);
00242  *
00243  *    Gap::ConnectionParams_t connection_parameters = {
00244  *       50, // min connection interval
00245  *       100, // max connection interval
00246  *       0, // slave latency
00247  *       600 // connection supervision timeout
00248  *    };
00249  *
00250  *    // scan parameter used to find the device to connect to
00251  *    GapScanningParams scanning_params(
00252  *      100, // interval
00253  *      100, // window
00254  *      0, // timeout
00255  *      false // active
00256  *    );
00257  *
00258  *    // Initiate the connection procedure
00259  *    gap.connect(
00260  *       packet->peerAddr,
00261  *       packet->addressType,
00262  *       &connection_parameters,
00263  *       &scanning_params
00264  *    );
00265  * }
00266  *
00267  * // set the scan parameters
00268  * gap.setScanParams(
00269  *      100, // interval between two scan window in ms
00270  *      50,  // scan window: period during which the device listen for advertising packets.
00271  *      0,   // the scan process never ends
00272  *      true // the device sends scan request to scannable peers.
00273  * );
00274  *
00275  * // start the scan procedure
00276  * gap.startScan(handle_advertising_packet);
00277  * @endcode
00278  *
00279  * @par Changing the PHYsical transport of a connection
00280  *
00281  * Once a connection has been established, it is possible to change the physical
00282  * transport used between the local and the distant device. Changing the transport
00283  * can either increase the bandwidth or increase the communication range.
00284  * An increased bandwidth equals a better power consumption but also a loss in
00285  * sensibility and therefore a degraded range.
00286  * Symmetrically an increased range means a lowered bandwith and a degraded power
00287  * consumption.
00288  *
00289  * Applications can change the PHY used by calling the function setPhy. Once the
00290  * update has been made the result is forwarded to the application by calling the
00291  * function onPhyUpdateComplete of the event handler registered.
00292  *
00293  * @par disconnection
00294  *
00295  * The application code initiates a disconnection when it calls the
00296  * disconnect(Handle_t, DisconnectionReason_t) function.
00297  *
00298  * Disconnection may also be initiated by the remote peer or the local
00299  * controller/stack. To catch all disconnection events, application code may
00300  * set up an handler taking care of disconnection events by calling
00301  * onDisconnection().
00302  *
00303  * @par Modulation Schemes
00304  *
00305  * When supported by the host and controller you can select different modulation
00306  * schemes (@see BLUETOOTH SPECIFICATION Version 5.0 | Vol 1, Part A - 1.2):
00307  * - LE 1M PHY
00308  * - LE 2M PHY
00309  * - LE coded PHY
00310  *
00311  * You may set preferred PHYs (separately for RX and TX) using setPreferredPhys().
00312  * You may also set the currently used PHYs on a selected connection using setPhy().
00313  * Both of these settings are only advisory and the controller is allowed to make
00314  * its own decision on the best PHY to use based on your request, the peer's
00315  * supported features and the connection's physical conditions.
00316  *
00317  * You may query the currently used PHY using readPhy() which will return the
00318  * result through a call to the registered event handler. You may register the
00319  * handler with setEventHandler(). The events inform about the currently used
00320  * PHY and of any changes to PHYs which may be triggered autonomously by the
00321  * controller or by the peer.
00322  */
00323 class Gap {
00324     /*
00325      * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated.
00326      * They have been relocated to the class BLEProtocol.
00327      */
00328 public:
00329     /**
00330      * Address-type for BLEProtocol addresses.
00331      *
00332      * @deprecated Use BLEProtocol::AddressType_t instead.
00333      */
00334     typedef BLEProtocol::AddressType_t AddressType_t;
00335 
00336     /**
00337      * Address-type for BLEProtocol addresses.
00338      *
00339      * @deprecated Use BLEProtocol::AddressType_t instead.
00340      */
00341     typedef BLEProtocol::AddressType_t addr_type_t;
00342 
00343     /**
00344      * Address-type for BLEProtocol addresses.
00345      *
00346      * @deprecated Use BLEProtocol::AddressType_t instead. The following
00347      * constants have been left in their deprecated state to transparently
00348      * support existing applications that may have used Gap::ADDR_TYPE_*.
00349      */
00350     enum DeprecatedAddressType_t {
00351         ADDR_TYPE_PUBLIC = BLEProtocol::AddressType::PUBLIC,
00352         ADDR_TYPE_RANDOM_STATIC = BLEProtocol::AddressType::RANDOM_STATIC,
00353         ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE,
00354         ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE
00355     };
00356 
00357     /**
00358      * Length (in octets) of the BLE MAC address.
00359      */
00360     static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN;
00361 
00362     /**
00363      * 48-bit address, LSB format.
00364      *
00365      * @deprecated Use BLEProtocol::AddressBytes_t instead.
00366      */
00367     typedef BLEProtocol::AddressBytes_t Address_t;
00368 
00369     /**
00370      * 48-bit address, LSB format.
00371      *
00372      * @deprecated Use BLEProtocol::AddressBytes_t instead.
00373      */
00374     typedef BLEProtocol::AddressBytes_t address_t;
00375 
00376 public:
00377     /**
00378      * Enumeration of possible timeout sources.
00379      */
00380     enum TimeoutSource_t {
00381         /**
00382          * Advertising timeout.
00383          */
00384         TIMEOUT_SRC_ADVERTISING = 0x00,
00385 
00386         /**
00387          * Security request timeout.
00388          */
00389         TIMEOUT_SRC_SECURITY_REQUEST = 0x01,
00390 
00391         /**
00392          * Scanning timeout.
00393          */
00394         TIMEOUT_SRC_SCAN = 0x02,
00395 
00396         /**
00397          * Connection timeout.
00398          */
00399         TIMEOUT_SRC_CONN = 0x03,
00400     };
00401 
00402     /**
00403      * Enumeration of disconnection reasons.
00404      *
00405      * @attention There might be a mismatch between the disconnection reason
00406      * passed to disconnect() and the disconnection event generated locally
00407      * because the disconnection reason passed to disconnect() is the
00408      * disconnection reason to be transmitted to the peer.
00409      */
00410     enum DisconnectionReason_t {
00411 
00412         /**
00413          * GAP or GATT failed to authenticate the peer.
00414          */
00415         AUTHENTICATION_FAILURE = 0x05,
00416 
00417         /**
00418          * The connection timed out.
00419          *
00420          * @attention shall not be used as a reason in disconnect().
00421          */
00422         CONNECTION_TIMEOUT = 0x08,
00423 
00424         /**
00425          * Connection terminated by the user.
00426          */
00427         REMOTE_USER_TERMINATED_CONNECTION = 0x13,
00428 
00429         /**
00430          * Remote device terminated connection due to low resources.
00431          */
00432         REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES = 0x14,
00433 
00434         /**
00435          * Remote device terminated connection due to power off.
00436          */
00437         REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF = 0x15,
00438 
00439         /**
00440          * Indicate that the local user or the internal
00441          * Bluetooth subsystem terminated the connection.
00442          *
00443          * @attention shall not be used as a reason in disconnect().
00444          */
00445         LOCAL_HOST_TERMINATED_CONNECTION = 0x16,
00446 
00447         /**
00448          * Connection parameters were unacceptable.
00449          */
00450         CONN_INTERVAL_UNACCEPTABLE = 0x3B,
00451     };
00452 
00453     /**
00454      * Advertising policy filter modes.
00455      *
00456      * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.2.
00457      */
00458     enum AdvertisingPolicyMode_t {
00459         /**
00460          * The whitelist is not used to filter peer request during advertising.
00461          */
00462         ADV_POLICY_IGNORE_WHITELIST = 0,
00463 
00464         /**
00465          * The whitelist is used to filter peer scan requests.
00466          */
00467         ADV_POLICY_FILTER_SCAN_REQS = 1,
00468 
00469         /**
00470          * The whitelist is used to filter peer connection requests.
00471          */
00472         ADV_POLICY_FILTER_CONN_REQS = 2,
00473 
00474         /**
00475          * The whitelist is used to filter peer scan and connection requests.
00476          */
00477         ADV_POLICY_FILTER_ALL_REQS  = 3,
00478     };
00479 
00480     /**
00481      * Scanning policy filter mode.
00482      *
00483      * @see Bluetooth Core Specification 4.2 (Vol. 6), Part B, Section 4.3.3.
00484      */
00485     enum ScanningPolicyMode_t {
00486         /**
00487          * The whitelist is not used for scanning operations.
00488          */
00489         SCAN_POLICY_IGNORE_WHITELIST = 0,
00490 
00491         /**
00492          * The whitelist is used to filter incoming advertising.
00493          */
00494         SCAN_POLICY_FILTER_ALL_ADV = 1,
00495     };
00496 
00497     /**
00498      * Connection initiation policy filter mode.
00499      *
00500      * @see Bluetooth Core Specification 4.2 (vol. 6), Part B, Section 4.4.4.
00501      */
00502     enum InitiatorPolicyMode_t {
00503         /**
00504          * Connection can be initiated to any device.
00505          */
00506         INIT_POLICY_IGNORE_WHITELIST = 0,
00507 
00508         /**
00509          * Connection initiation is restricted to the devices present in the
00510          * whitelist.
00511          */
00512         INIT_POLICY_FILTER_ALL_ADV = 1,
00513     };
00514 
00515     /**
00516      * Representation of a whitelist of addresses.
00517      */
00518     struct Whitelist_t {
00519         /**
00520          * Pointer to the array of the addresses composing the whitelist.
00521          */
00522         BLEProtocol::Address_t *addresses;
00523 
00524         /**
00525          * Number addresses in this whitelist.
00526          */
00527         uint8_t size;
00528 
00529         /**
00530          * Capacity of the array holding the addresses.
00531          */
00532         uint8_t capacity;
00533     };
00534 
00535     /**
00536      * Description of the states of the device.
00537      */
00538     struct GapState_t {
00539         /**
00540          * If set, the device is currently advertising.
00541          */
00542         unsigned advertising : 1;
00543 
00544         /**
00545          * If set, the device is connected to at least one other peer.
00546          */
00547         unsigned connected : 1;
00548     };
00549 
00550     /**
00551      * Opaque value type representing a connection handle.
00552      *
00553      * It is used to identify to refer to a specific connection across Gap,
00554      * GattClient and GattEvent API.
00555      *
00556      * @note instances are generated by in the connection callback.
00557      */
00558     typedef ble::connection_handle_t Handle_t;
00559 
00560     /**
00561      * Enumeration of random address types.
00562      */
00563     typedef ble::random_address_type_t RandomAddressType_t;
00564 
00565     /**
00566      * Enumeration of peer address types
00567      */
00568     typedef ble::peer_address_type_t PeerAddressType_t;
00569 
00570     /**
00571      * Enumeration of BLE PHY
00572      */
00573     typedef ble::phy_t Phy_t;
00574 
00575     /**
00576      * Set of BLE PHYs
00577      */
00578     typedef ble::phy_set_t PhySet_t;
00579 
00580     /**
00581      * Enumeration of type of symbols that can be used with LE coded PHY.
00582      */
00583     typedef ble::coded_symbol_per_bit_t CodedSymbolPerBit_t;
00584 
00585     /**
00586      * Parameters of a BLE connection.
00587      */
00588     typedef struct {
00589         /**
00590          * Minimum interval between two connection events allowed for a
00591          * connection.
00592          *
00593          * It shall be less than or equal to maxConnectionInterval. This value,
00594          * in units of 1.25ms, is included in the range [0x0006 : 0x0C80].
00595          */
00596         uint16_t minConnectionInterval;
00597 
00598         /**
00599          * Maximum interval between two connection events allowed for a
00600          * connection.
00601          *
00602          * It shall be greater than or equal to minConnectionInterval. This
00603          * value is in unit of 1.25ms and is in the range [0x0006 : 0x0C80].
00604          */
00605         uint16_t maxConnectionInterval;
00606 
00607         /**
00608          * Number of connection events the slave can drop if it has nothing to
00609          * communicate to the master.
00610          *
00611          * This value shall be in the range [0x0000 : 0x01F3].
00612          */
00613         uint16_t slaveLatency;
00614 
00615         /**
00616          * Link supervision timeout for the connection.
00617          *
00618          * Time after which the connection is considered lost if the device
00619          * didn't receive a packet from its peer.
00620          *
00621          * It is larger than:
00622          *        (1 + slaveLatency) * maxConnectionInterval * 2
00623          *
00624          * This value is in the range [0x000A : 0x0C80] and is in unit of
00625          * 10 ms.
00626          *
00627          * @note maxConnectionInterval is in ms in the formulae above.
00628          */
00629         uint16_t connectionSupervisionTimeout;
00630     } ConnectionParams_t;
00631 
00632     /**
00633      * Enumeration of GAP roles.
00634      *
00635      * @note The BLE API does not express the broadcaster and scanner roles.
00636      *
00637      * @attention A device can fulfill different roles concurrently.
00638      */
00639     enum Role_t {
00640         /**
00641          * Peripheral Role.
00642          *
00643          * The device can advertise and it can be connected by a central. It
00644          * acts as a slave when connected.
00645          *
00646          * @note A peripheral is a broadcaster.
00647          */
00648         PERIPHERAL = 0x1,
00649 
00650         /**
00651          * Central Role.
00652          *
00653          * The device can scan and initiate connection to peripherals. It
00654          * acts as the master when a connection is established.
00655          *
00656          * @note A central is a scanner.
00657          */
00658         CENTRAL = 0x2,
00659     };
00660 
00661     /**
00662      * Representation of a scanned advertising packet.
00663      *
00664      * Instances of this type are passed to the callback registered in
00665      * startScan().
00666      */
00667     struct AdvertisementCallbackParams_t {
00668         /**
00669          * Default constructor.
00670          */
00671         AdvertisementCallbackParams_t();
00672 
00673         /**
00674          * BLE address of the device that has advertised the packet.
00675          */
00676         BLEProtocol::AddressBytes_t peerAddr;
00677 
00678         /**
00679          * RSSI value of the packet.
00680          */
00681         int8_t rssi;
00682 
00683         /**
00684          * Flag indicating if the packet is a response to a scan request.
00685          */
00686         bool isScanResponse;
00687 
00688         /**
00689          * Type of advertisement.
00690          */
00691         GapAdvertisingParams::AdvertisingType_t type;
00692 
00693         /**
00694          * Length of the advertisement data.
00695          */
00696         uint8_t advertisingDataLen;
00697 
00698         /**
00699          * Pointer to the advertisement packet's data.
00700          */
00701         const uint8_t *advertisingData;
00702 
00703         /**
00704          * Type of the address received.
00705          *
00706          * @deprecated AddressType_t do not carry enough information to be used
00707          * when privacy is enabled. Use peerAddressType instead.
00708          *
00709          * @note This value should be used in the connect function to establish
00710          * a connection with the peer that has sent this advertisement packet.
00711          */
00712         MBED_DEPRECATED_SINCE(
00713             "mbed-os-5.9.0",
00714             "addressType won't work in connect when privacy is enabled; please"
00715             "use peerAddrType"
00716         )
00717         AddressType_t addressType;
00718 
00719         /**
00720          * Type of the address received.
00721          *
00722          * @note This value should be used in the connect function to establish
00723          * a connection with the peer that has sent this advertisement packet.
00724          */
00725         PeerAddressType_t peerAddrType;
00726     };
00727 
00728     /**
00729      * Type of the callback handling scanned advertisement packets.
00730      *
00731      * @see Gap::startScan().
00732      */
00733     typedef FunctionPointerWithContext<const AdvertisementCallbackParams_t *>
00734         AdvertisementReportCallback_t ;
00735 
00736     /**
00737      * Connection events.
00738      *
00739      * It contains all the information related to a newly established connection.
00740      *
00741      * Instances of this structure are passed to handlers that
00742      * Gap::onConnection() registers when a connection is established.
00743      */
00744     struct ConnectionCallbackParams_t {
00745         /**
00746          * Connection handle.
00747          */
00748         Handle_t handle;
00749 
00750         /**
00751          * Connection Role of the local device.
00752          */
00753         Role_t role;
00754 
00755         /**
00756          * Type of the address the peer uses.
00757          *
00758          * @deprecated The type BLEProtocol::AddressType_t is not suitable when
00759          * privacy is enabled. Use peerAddressType instead.
00760          */
00761         MBED_DEPRECATED_SINCE(
00762             "mbed-os-5.9",
00763             "The type BLEProtocol::AddressType_t is not suitable when privacy is "
00764             "enabled. Use peerAddressType instead."
00765         )
00766         BLEProtocol::AddressType_t peerAddrType;
00767 
00768         /**
00769          * Address of the peer.
00770          */
00771         BLEProtocol::AddressBytes_t peerAddr;
00772 
00773         /**
00774          * Address type of the local device.
00775          */
00776         BLEProtocol::AddressType_t  ownAddrType;
00777 
00778         /**
00779          * Address of the local device.
00780          *
00781          * @deprecated The local address used for the connection may not be known,
00782          * Therefore this field is not reliable.
00783          *
00784          * @note All bytes of the address are set to 0 if not applicable
00785          */
00786         MBED_DEPRECATED_SINCE(
00787             "mbed-os-5.9",
00788             "A Bluetooth controller is not supposed to return the address it used"
00789             "to connect. With privacy enabled the controller address may be unknown"
00790             "to the host. There is no replacement for this deprecation."
00791         )
00792         BLEProtocol::AddressBytes_t ownAddr;
00793 
00794         /**
00795          * Connection parameters.
00796          */
00797         const ConnectionParams_t   *connectionParams;
00798 
00799         /**
00800          * Resolvable address used by the peer.
00801          *
00802          * @note All bytes of the address are set to 0 if not applicable
00803          */
00804         BLEProtocol::AddressBytes_t peerResolvableAddr;
00805 
00806         /**
00807          * resolvable address of the local device.
00808          *
00809          * @note All bytes of the address are set to 0 if not applicable
00810          */
00811         BLEProtocol::AddressBytes_t localResolvableAddr;
00812 
00813         /**
00814          * Type of the address the peer uses.
00815          */
00816         PeerAddressType_t peerAddressType;
00817 
00818         /**
00819          * Construct an instance of ConnectionCallbackParams_t.
00820          *
00821          * @param[in] handleIn Value to assign to handle.
00822          * @param[in] roleIn Value to assign to role.
00823          * @param[in] peerAddrTypeIn Value to assign to peerAddrType.
00824          * @param[in] peerAddrIn Value to assign to peerAddr.
00825          * @param[in] ownAddrTypeIn Value to assign to ownAddrType.
00826          * @param[in] ownAddrIn Value to assign to ownAddr. This may be NULL.
00827          * @param[in] connectionParamsIn Value to assign to connectionParams.
00828          * @param[in] peerResolvableAddrIn Value to assign to peerResolvableAddr.
00829          * @param[in] localResolvableAddrIn Value to assign to localResolvableAddr.
00830          *
00831          * @note Constructor is not meant to be called by user code.
00832          * The BLE API vendor code generates ConnectionCallbackParams_t.
00833          */
00834         ConnectionCallbackParams_t(
00835             Handle_t handleIn,
00836             Role_t roleIn,
00837             PeerAddressType_t peerAddrTypeIn,
00838             const uint8_t *peerAddrIn,
00839             BLEProtocol::AddressType_t ownAddrTypeIn,
00840             const uint8_t *ownAddrIn,
00841             const ConnectionParams_t *connectionParamsIn,
00842             const uint8_t *peerResolvableAddrIn = NULL,
00843             const uint8_t *localResolvableAddrIn = NULL
00844         );
00845 
00846         /**
00847          * Construct an instance of ConnectionCallbackParams_t.
00848          *
00849          * @param[in] handleIn Value to assign to handle.
00850          * @param[in] roleIn Value to assign to role.
00851          * @param[in] peerAddrTypeIn Value to assign to peerAddrType.
00852          * @param[in] peerAddrIn Value to assign to peerAddr.
00853          * @param[in] ownAddrTypeIn Value to assign to ownAddrType.
00854          * @param[in] ownAddrIn Value to assign to ownAddr.
00855          * @param[in] connectionParamsIn Value to assign to connectionParams.
00856          * @param[in] peerResolvableAddrIn Value to assign to peerResolvableAddr.
00857          * @param[in] localResolvableAddrIn Value to assign to localResolvableAddr.
00858          *
00859          * @note Constructor is not meant to be called by user code.
00860          * The BLE API vendor code generates ConnectionCallbackParams_t.
00861          *
00862          * @deprecated The type BLEProtocol::AddressType_t is not suitable when
00863          * privacy is enabled. Use the constructor that accepts a
00864          * PeerAddressType_t instead.
00865          */
00866         MBED_DEPRECATED_SINCE(
00867             "mbed-os-5.9.0",
00868             "The type BLEProtocol::AddressType_t is not suitable when privacy is "
00869             "enabled. Use the constructor that accepts a PeerAddressType_t instead."
00870         )
00871         ConnectionCallbackParams_t(
00872             Handle_t handleIn,
00873             Role_t roleIn,
00874             BLEProtocol::AddressType_t peerAddrTypeIn,
00875             const uint8_t *peerAddrIn,
00876             BLEProtocol::AddressType_t ownAddrTypeIn,
00877             const uint8_t *ownAddrIn,
00878             const ConnectionParams_t *connectionParamsIn,
00879             const uint8_t *peerResolvableAddrIn = NULL,
00880             const uint8_t *localResolvableAddrIn = NULL
00881         );
00882 
00883     private:
00884         void constructor_helper(
00885             const uint8_t *peerAddrIn,
00886             const uint8_t *ownAddrIn,
00887             const uint8_t *peerResolvableAddrIn,
00888             const uint8_t *localResolvableAddrIn
00889         );
00890     };
00891 
00892     /**
00893      * Disconnection event.
00894      *
00895      * Instances of this event are passed to callbacks registered with
00896      * Gap::onDisconnection() when a connection ends.
00897      *
00898      * @note Constructor is not meant to be called by user code.
00899      * The BLE API vendor code generates ConnectionCallbackParams_t.
00900      */
00901     struct DisconnectionCallbackParams_t {
00902         /**
00903          * ID of the connection that has ended.
00904          */
00905         Handle_t handle;
00906 
00907         /**
00908          * Reason of the disconnection.
00909          */
00910         DisconnectionReason_t reason;
00911 
00912         /**
00913          * Construct a DisconnectionCallbackParams_t.
00914          *
00915          * @param[in] handleIn Value assigned to handle.
00916          * @param[in] reasonIn Value assigned to reason.
00917          */
00918         DisconnectionCallbackParams_t(
00919             Handle_t handleIn,
00920             DisconnectionReason_t reasonIn
00921         ) : handle(handleIn),
00922             reason(reasonIn)
00923         {}
00924     };
00925 
00926     /**
00927      * Privacy Configuration of the peripheral role.
00928      *
00929      * @note This configuration also applies to the broadcaster role configuration.
00930      */
00931     struct PeripheralPrivacyConfiguration_t {
00932         /**
00933          * Indicates if non resolvable random address should be used when the
00934          * peripheral advertises non connectable packets.
00935          *
00936          * Resolvable random address continues to be used for connectable packets.
00937          */
00938         bool use_non_resolvable_random_address;
00939 
00940         /**
00941          * Resolution strategy for initiator resolvable addresses when a
00942          * connection request is received.
00943          */
00944         enum ResolutionStrategy {
00945             /**
00946              * Do not resolve the address of the initiator and accept the
00947              * connection request.
00948              */
00949             DO_NOT_RESOLVE,
00950 
00951             /**
00952              * If a bond is present in the secure database and the address
00953              * resolution fail then reject the connection request with the error
00954              * code AUTHENTICATION_FAILLURE.
00955              */
00956             REJECT_NON_RESOLVED_ADDRESS,
00957 
00958             /**
00959              * Perform the pairing procedure if the initiator resolvable
00960              * address failed the resolution process.
00961              */
00962             PERFORM_PAIRING_PROCEDURE,
00963 
00964             /**
00965              * Perform the authentication procedure if the initiator resolvable
00966              * address failed the resolution process.
00967              */
00968             PERFORM_AUTHENTICATION_PROCEDURE
00969         };
00970 
00971         /**
00972          * Connection strategy to use when a connection request contains a
00973          * private resolvable address.
00974          */
00975         ResolutionStrategy resolution_strategy;
00976     };
00977 
00978     /**
00979      * Privacy Configuration of the central role.
00980      *
00981      * @note This configuration is also used when the local device operates as
00982      * an observer.
00983      */
00984     struct CentralPrivacyConfiguration_t {
00985         /**
00986          * Indicates if non resolvable random address should be used when the
00987          * central or observer sends scan request packets.
00988          *
00989          * Resolvable random address continue to be used for connection requests.
00990          */
00991         bool use_non_resolvable_random_address;
00992 
00993 
00994         /**
00995          * Resolution strategy of resolvable addresses received in advertising
00996          * packets.
00997          */
00998         enum ResolutionStrategy {
00999             /**
01000              * Do not resolve the address received in advertising packets.
01001              */
01002             DO_NOT_RESOLVE,
01003 
01004             /**
01005              * Resolve the resolvable addresses in the advertising packet and
01006              * forward advertising packet to the application independently of
01007              * the address resolution procedure result.
01008              */
01009             RESOLVE_AND_FORWARD,
01010 
01011             /**
01012              * Filter out packets containing a resolvable that cannot be resolved
01013              * by this device.
01014              *
01015              * @note Filtering is applied if the local device contains at least
01016              * one bond.
01017              */
01018             RESOLVE_AND_FILTER
01019         };
01020 
01021         /**
01022          * Resolution strategy applied to advertising packets received by the
01023          * local device.
01024          */
01025         ResolutionStrategy resolution_strategy;
01026     };
01027 
01028     /**
01029      * Number of microseconds in 1.25 milliseconds.
01030      */
01031     static const uint16_t UNIT_1_25_MS  = 1250;
01032 
01033     static const PeripheralPrivacyConfiguration_t
01034         default_peripheral_privacy_configuration;
01035 
01036     static const CentralPrivacyConfiguration_t
01037         default_central_privacy_configuration;
01038 
01039     /**
01040      * Convert milliseconds into 1.25ms units.
01041      *
01042      * This function may be used to convert ms time of connection intervals into
01043      * the format expected for connection parameters.
01044      *
01045      * @param[in] durationInMillis The duration in milliseconds.
01046      *
01047      * @return The duration in unit of 1.25ms.
01048      */
01049     static uint16_t MSEC_TO_GAP_DURATION_UNITS(uint32_t durationInMillis)
01050     {
01051         return (durationInMillis * 1000) / UNIT_1_25_MS;
01052     }
01053 
01054     /**
01055      * Timeout event handler.
01056      *
01057      * @see Gap::onTimeout().
01058      */
01059     typedef FunctionPointerWithContext<TimeoutSource_t>  TimeoutEventCallback_t;
01060 
01061     /**
01062      * Callchain of timeout event handlers.
01063      *
01064      * @see Gap::onTimeout().
01065      */
01066     typedef CallChainOfFunctionPointersWithContext<TimeoutSource_t> 
01067         TimeoutEventCallbackChain_t;
01068 
01069     /**
01070      * Connection event handler.
01071      *
01072      * @see Gap::onConnection().
01073      */
01074     typedef FunctionPointerWithContext<const ConnectionCallbackParams_t *> 
01075         ConnectionEventCallback_t;
01076 
01077     /**
01078      * Callchain of connection event handlers.
01079      *
01080      * @see Gap::onConnection().
01081      */
01082     typedef CallChainOfFunctionPointersWithContext<const ConnectionCallbackParams_t *> 
01083         ConnectionEventCallbackChain_t;
01084 
01085     /**
01086      * Disconnection event handler.
01087      *
01088      * @see Gap::onDisconnection().
01089      */
01090     typedef FunctionPointerWithContext<const DisconnectionCallbackParams_t*> 
01091         DisconnectionEventCallback_t;
01092 
01093     /**
01094      * Callchain of disconnection event handlers.
01095      *
01096      * @see Gap::onDisconnection().
01097      */
01098     typedef CallChainOfFunctionPointersWithContext<const DisconnectionCallbackParams_t*> 
01099         DisconnectionEventCallbackChain_t;
01100 
01101     /**
01102      * Radio notification event handler.
01103      *
01104      * @see Gap::onRadioNotification().
01105      */
01106     typedef FunctionPointerWithContext<bool>  RadioNotificationEventCallback_t;
01107 
01108     /**
01109      * Gap shutdown event handler.
01110      *
01111      * @see Gap::onShutdown().
01112      */
01113     typedef FunctionPointerWithContext<const Gap *>  GapShutdownCallback_t;
01114 
01115     /**
01116      * Callchain of gap shutdown event handler.
01117      *
01118      * @see Gap::onShutdown().
01119      */
01120     typedef CallChainOfFunctionPointersWithContext<const Gap *> 
01121         GapShutdownCallbackChain_t;
01122 
01123 
01124     /**
01125      * Definition of the general handler of Gap related events.
01126      */
01127     struct EventHandler {
01128         /**
01129          * Function invoked when the current transmitter and receiver PHY have
01130          * been read for a given connection.
01131          *
01132          * @param status Status of the operation: BLE_ERROR_NONE in case of
01133          * success or an appropriate error code.
01134          *
01135          * @param connectionHandle: The handle of the connection for which the
01136          * PHYs have been read.
01137          *
01138          * @param txPhy PHY used by the transmitter.
01139          *
01140          * @param rxPhy PHY used by the receiver.
01141          */
01142         virtual void onReadPhy(
01143             ble_error_t status,
01144             Handle_t connectionHandle,
01145             Phy_t txPhy,
01146             Phy_t rxPhy
01147         ) {
01148             (void)status;
01149             (void)connectionHandle;
01150             (void)txPhy;
01151             (void)rxPhy;
01152         }
01153 
01154         /**
01155          * Function invoked when the update process of the PHY has been completed.
01156          *
01157          * The process can be initiated by a call to the function setPhy, the
01158          * local bluetooth subsystem or the peer.
01159          *
01160          * @param status Status of the operation: BLE_ERROR_NONE in case of
01161          * success or an appropriate error code.
01162          *
01163          * @param connectionHandle: The handle of the connection on which the
01164          * operation was made.
01165          *
01166          * @param txPhy PHY used by the transmitter.
01167          *
01168          * @param rxPhy PHY used by the receiver.
01169          *
01170          * @note Success doesn't mean the PHY has been updated it means both
01171          * ends have negociated the best phy according to their configuration and
01172          * capabilities. The PHY currently used are present in the txPhy and
01173          * rxPhy parameters.
01174          */
01175         virtual void onPhyUpdateComplete(
01176             ble_error_t status,
01177             Handle_t connectionHandle,
01178             Phy_t txPhy,
01179             Phy_t rxPhy
01180         ) {
01181             (void)status;
01182             (void)connectionHandle;
01183             (void)txPhy;
01184             (void)rxPhy;
01185         }
01186 
01187     protected:
01188         /**
01189          * Prevent polymorphic deletion and avoid uncessery virtual destructor
01190          * as the Gap class will never delete the instance it contains.
01191          */
01192         ~EventHandler() { }
01193     };
01194 
01195     /*
01196      * The following functions are meant to be overridden in the platform-specific subclass.
01197      */
01198 public:
01199     /**
01200      * Set the device MAC address and type.
01201      *
01202      * The address set is used in subsequent GAP operations: scanning,
01203      * advertising and connection initiation.
01204      *
01205      * @param[in] type Type of the address to set.
01206      * @param[in] address Value of the address to set. It is ordered in
01207      * little endian. This parameter is not considered if the address type
01208      * is RANDOM_PRIVATE_RESOLVABLE or RANDOM_PRIVATE_NON_RESOLVABLE. For those
01209      * types of address, the BLE API itself generates the address.
01210      *
01211      * @note Some implementation may refuse to set a new PUBLIC address.
01212      * @note Random static address set does not change.
01213      *
01214      * @deprecated Starting with mbed-os-5.9.0 this function is deprecated and
01215      * address management is delegated to implementation. Implementations may or
01216      * may not continue to support this function. Compliance with the Bluetooth
01217      * specification and unification of behaviour between implementations are
01218      * the key reasons behind this change:
01219      *   - Many implementations do not allow changing of the public address.
01220      *   Therefore programs relying on this function are not portable across BLE
01221      *   implementations.
01222      *   - The Bluetooth specification forbid replacement of the random static
01223      *   address; this address can be set once and only once: at startup.
01224      *   Depending on the underlying implementation the random address may or
01225      *   may not have been set automatically at startup; therefore update of the
01226      *   Random Static address after ble initialisation may be a fault. As a
01227      *   result calls to this function were not portable.
01228      *   Furthermore replacement of the random static address silently
01229      *   invalidates the bond stored in the secure database.
01230 
01231      * @return BLE_ERROR_NONE on success.
01232      */
01233     MBED_DEPRECATED_SINCE(
01234         "mbed-os-5.9.0",
01235         "Non portable API, use enablePrivacy to enable use of private addresses"
01236     )
01237     virtual ble_error_t setAddress(
01238         BLEProtocol::AddressType_t type,
01239         const BLEProtocol::AddressBytes_t address
01240     ) {
01241         /* avoid compiler warnings about unused variables */
01242         (void)type;
01243         (void)address;
01244 
01245         /* Requesting action from porter(s): override this API if this capability
01246            is supported. */
01247         return BLE_ERROR_NOT_IMPLEMENTED;
01248     }
01249 
01250     /**
01251      * Fetch the current address and its type.
01252      *
01253      * @param[out] typeP Type of the current address set.
01254      * @param[out] address Value of the current address.
01255      *
01256      * @note If privacy is enabled the device address may be unavailable to
01257      * application code.
01258      *
01259      * @return BLE_ERROR_NONE on success.
01260      */
01261     virtual ble_error_t getAddress(
01262         BLEProtocol::AddressType_t *typeP,
01263         BLEProtocol::AddressBytes_t address
01264     ) {
01265         /* Avoid compiler warnings about unused variables. */
01266         (void)typeP;
01267         (void)address;
01268 
01269         /* Requesting action from porter(s): override this API if this capability
01270            is supported. */
01271         return BLE_ERROR_NOT_IMPLEMENTED;
01272     }
01273 
01274     /**
01275      * Return the type of a random address.
01276      *
01277      * @param[in] address The random address to retrieve the type from. The
01278      * address must be ordered in little endian.
01279      *
01280      * @param[out] addressType Type of the address to fill.
01281      *
01282      * @return BLE_ERROR_NONE in case of success or BLE_ERROR_INVALID_PARAM if
01283      * the address in input was not identifiable as a random address.
01284      */
01285     static ble_error_t getRandomAddressType(
01286         const BLEProtocol::AddressBytes_t address,
01287         RandomAddressType_t* addressType
01288     );
01289 
01290     /**
01291      * Get the minimum advertising interval in milliseconds, which can be used
01292      * for connectable advertising types.
01293      *
01294      * @return Minimum Advertising interval in milliseconds for connectable
01295      * undirected and connectable directed advertising types.
01296      */
01297     virtual uint16_t getMinAdvertisingInterval(void) const
01298     {
01299         /* Requesting action from porter(s): override this API if this capability
01300            is supported. */
01301         return 0;
01302     }
01303 
01304     /**
01305      * Get the minimum advertising interval in milliseconds, which can be
01306      * used for nonconnectable advertising type.
01307      *
01308      * @return Minimum Advertising interval in milliseconds for scannable
01309      * undirected and nonconnectable undirected event types.
01310      */
01311     virtual uint16_t getMinNonConnectableAdvertisingInterval(void) const
01312     {
01313         /* Requesting action from porter(s): override this API if this capability
01314            is supported. */
01315         return 0;
01316     }
01317 
01318     /**
01319      * Get the maximum advertising interval in milliseconds.
01320      *
01321      * @return Maximum Advertising interval in milliseconds.
01322      */
01323     virtual uint16_t getMaxAdvertisingInterval(void) const
01324     {
01325         /* Requesting action from porter(s): override this API if this capability
01326            is supported. */
01327         return 0xFFFF;
01328     }
01329 
01330     /**
01331      * Stop the ongoing advertising procedure.
01332      *
01333      * @note The current advertising parameters remain in effect.
01334      *
01335      * @retval BLE_ERROR_NONE if the advertising procedure has been successfully
01336      * stopped.
01337      */
01338     virtual ble_error_t stopAdvertising(void)
01339     {
01340         /* Requesting action from porter(s): override this API if this capability
01341            is supported. */
01342         return BLE_ERROR_NOT_IMPLEMENTED;
01343     }
01344 
01345     /**
01346      * Stop the ongoing scanning procedure.
01347      *
01348      * The current scanning parameters remain in effect.
01349      *
01350      * @retval BLE_ERROR_NONE if successfully stopped scanning procedure.
01351      */
01352     virtual ble_error_t stopScan()
01353     {
01354         /* Requesting action from porter(s): override this API if this capability
01355            is supported. */
01356         return BLE_ERROR_NOT_IMPLEMENTED;
01357     }
01358 
01359     /**
01360      * Initiate a connection to a peer.
01361      *
01362      * Once the connection is established, a ConnectionCallbackParams_t event is
01363      * emitted to handlers that have been registered with onConnection().
01364      *
01365      * @param[in] peerAddr MAC address of the peer. It must be in LSB format.
01366      * @param[in] peerAddrType Address type of the peer. It is usually obtained
01367      * from advertising frames.
01368      * @param[in] connectionParams Connection parameters to use.
01369      * @param[in] scanParams Scan parameters used to find the peer.
01370      *
01371      * @return BLE_ERROR_NONE if connection establishment procedure is started
01372      * successfully. The connectionCallChain (if set) is invoked upon
01373      * a connection event.
01374      */
01375     virtual ble_error_t connect(
01376         const BLEProtocol::AddressBytes_t peerAddr,
01377         PeerAddressType_t peerAddrType,
01378         const ConnectionParams_t *connectionParams,
01379         const GapScanningParams *scanParams
01380     ) {
01381         /* Avoid compiler warnings about unused variables. */
01382         (void)peerAddr;
01383         (void)peerAddrType;
01384         (void)connectionParams;
01385         (void)scanParams;
01386 
01387         /* Requesting action from porter(s): override this API if this capability
01388            is supported. */
01389         return BLE_ERROR_NOT_IMPLEMENTED;
01390     }
01391 
01392     /**
01393      * Initiate a connection to a peer.
01394      *
01395      * Once the connection is established, a ConnectionCallbackParams_t event is
01396      * emitted to handlers that have been registered with onConnection().
01397      *
01398      * @param[in] peerAddr MAC address of the peer. It must be in LSB format.
01399      * @param[in] peerAddrType Address type of the peer.
01400      * @param[in] connectionParams Connection parameters to use.
01401      * @param[in] scanParams Scan parameters used to find the peer.
01402      *
01403      * @deprecated BLEProtocol::AddressType_t is not able to to carry accurate
01404      * meaning when privacy is in use. Please Uses the connect overload that
01405      * accept a PeerAddressType_t as the peer address type.
01406      *
01407      * @return BLE_ERROR_NONE if connection establishment procedure is started
01408      * successfully. The connectionCallChain (if set) is invoked upon
01409      * a connection event.
01410      */
01411     MBED_DEPRECATED_SINCE(
01412         "mbed-os-5.9.0",
01413         "This function won't work if privacy is enabled; You must use the overload "
01414         "accepting PeerAddressType_t."
01415     )
01416     virtual ble_error_t connect(
01417         const BLEProtocol::AddressBytes_t peerAddr,
01418         BLEProtocol::AddressType_t peerAddrType,
01419         const ConnectionParams_t *connectionParams,
01420         const GapScanningParams *scanParams
01421     ) {
01422         /* Avoid compiler warnings about unused variables. */
01423         (void)peerAddr;
01424         (void)peerAddrType;
01425         (void)connectionParams;
01426         (void)scanParams;
01427 
01428         /* Requesting action from porter(s): override this API if this capability
01429            is supported. */
01430         return BLE_ERROR_NOT_IMPLEMENTED;
01431     }
01432 
01433     /**
01434      * Initiate a connection to a peer.
01435      *
01436      * @see connect()
01437      *
01438      * @deprecated  This funtion overloads Gap::connect(
01439      *      const BLEProtocol::Address_t peerAddr,
01440      *      BLEProtocol::AddressType_t peerAddrType,
01441      *      const ConnectionParams_t *connectionParams,
01442      *      const GapScanningParams *scanParams
01443      * )
01444      * to maintain backward compatibility for changes from Gap::AddressType_t to
01445      * BLEProtocol::AddressType_t.
01446      */
01447     MBED_DEPRECATED("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead")
01448     ble_error_t connect(
01449         const BLEProtocol::AddressBytes_t peerAddr,
01450         DeprecatedAddressType_t peerAddrType,
01451         const ConnectionParams_t *connectionParams,
01452         const GapScanningParams *scanParams
01453     );
01454 
01455     /**
01456      * Read the PHY used by the transmitter and the receiver on a connection.
01457      *
01458      * Once the PHY has been read, it is reported back via the function onPhyRead
01459      * of the event handler registered by the application.
01460      *
01461      * @param connection Handle of the connection for which the PHY being used is
01462      * queried.
01463      *
01464      * @return BLE_ERROR_NONE if the read PHY procedure has been started or an
01465      * appropriate error code.
01466      */
01467     virtual ble_error_t readPhy(Handle_t connection) {
01468         return BLE_ERROR_NOT_IMPLEMENTED;
01469     }
01470 
01471     /**
01472      * Set the preferred PHYs to use in a connection.
01473      *
01474      * @param txPhys: Set of PHYs preferred for tx operations. If NULL then no
01475      * preferred PHYs are set and the default value of the subsytem is used.
01476      *
01477      * @param rxPhys: Set of PHYs preferred for rx operations. If NULL then no
01478      * preferred PHYs are set and the default value of the subsytem is used.
01479      *
01480      * @return BLE_ERROR_NONE if the preferences have been set or an appropriate
01481      * error code.
01482      */
01483     virtual ble_error_t setPreferredPhys(
01484         const PhySet_t* txPhys,
01485         const PhySet_t* rxPhys
01486     ) {
01487         return BLE_ERROR_NOT_IMPLEMENTED;
01488     }
01489 
01490     /**
01491      * Update the PHY used by a connection.
01492      *
01493      * Once the update process has been completed, it is reported back to the
01494      * application via the function onPhyUpdateComplete of the event handler
01495      * registered by the application.
01496      *
01497      * @param connection Handle of the connection to update.
01498      *
01499      * @param txPhys Set of PHYs preferred for tx operations. If NULL then the
01500      * choice is up to the Bluetooth subsystem.
01501      *
01502      * @param rxPhys Set of PHYs preferred for rx operations. If NULL then the
01503      * choice is up to the Bluetooth subsystem.
01504      *
01505      * @param codedSymbol Number of symbols used to code a bit when le coded is
01506      * used. If the value is UNDEFINED then the choice is up to the Bluetooth
01507      * subsystem.
01508      *
01509      * @return BLE_ERROR_NONE if the update PHY procedure has been successfully
01510      * started or an error code.
01511      */
01512     virtual ble_error_t setPhy(
01513         Handle_t connection,
01514         const PhySet_t* txPhys,
01515         const PhySet_t* rxPhys,
01516         CodedSymbolPerBit_t codedSymbol
01517     ) {
01518         return BLE_ERROR_NOT_IMPLEMENTED;
01519     }
01520 
01521     /**
01522      * Initiate a disconnection procedure.
01523      *
01524      * Once the disconnection procedure has completed a
01525      * DisconnectionCallbackParams_t, the event is emitted to handlers that
01526      * have been registered with onDisconnection().
01527      *
01528      * @param[in] reason Reason of the disconnection transmitted to the peer.
01529      * @param[in] connectionHandle Handle of the connection to end.
01530      *
01531      * @return  BLE_ERROR_NONE if the disconnection procedure successfully
01532      * started.
01533      */
01534     virtual ble_error_t disconnect(
01535         Handle_t connectionHandle, DisconnectionReason_t reason
01536     ) {
01537         /* avoid compiler warnings about unused variables */
01538         (void)connectionHandle;
01539         (void)reason;
01540 
01541         /* Requesting action from porter(s): override this API if this capability
01542            is supported. */
01543         return BLE_ERROR_NOT_IMPLEMENTED;
01544     }
01545 
01546     /**
01547      * Initiate a disconnection procedure.
01548      *
01549      * @deprecated This version of disconnect() doesn't take a connection handle.
01550      * It works reliably only for stacks that are limited to a single connection.
01551      * Use Gap::disconnect(Handle_t connectionHandle, DisconnectionReason_t reason)
01552      * instead.
01553      *
01554      * @param[in] reason The reason for disconnection; to be sent back to the peer.
01555      *
01556      * @return BLE_ERROR_NONE if disconnection was successful.
01557      */
01558     MBED_DEPRECATED("Use disconnect(Handle_t, DisconnectionReason_t) instead.")
01559     virtual ble_error_t disconnect(DisconnectionReason_t reason) {
01560         /* Avoid compiler warnings about unused variables. */
01561         (void)reason;
01562 
01563         /* Requesting action from porter(s): override this API if this capability
01564            is supported. */
01565         return BLE_ERROR_NOT_IMPLEMENTED;
01566     }
01567 
01568     /**
01569      * Returned the preferred connection parameters exposed in the GATT Generic
01570      * Access Service.
01571      *
01572      * @param[out] params Structure where the parameters are stored.
01573      *
01574      * @return BLE_ERROR_NONE if the parameters were successfully filled into
01575      * @p params.
01576      */
01577     virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params)
01578     {
01579         /* Avoid compiler warnings about unused variables. */
01580         (void)params;
01581 
01582         /* Requesting action from porter(s): override this API if this capability
01583            is supported. */
01584         return BLE_ERROR_NOT_IMPLEMENTED;
01585     }
01586 
01587     /**
01588      * Set the value of the preferred connection parameters exposed in the GATT
01589      * Generic Access Service.
01590      *
01591      * A connected peer may read the characteristic exposing these parameters
01592      * and request an update of the connection parameters to accomodate the
01593      * local device.
01594      *
01595      * @param[in] params Value of the preferred connection parameters.
01596      *
01597      * @return BLE_ERROR_NONE if the preferred connection params were set
01598      * correctly.
01599      */
01600     virtual ble_error_t setPreferredConnectionParams(
01601         const ConnectionParams_t *params
01602     ) {
01603         /* Avoid compiler warnings about unused variables. */
01604         (void)params;
01605 
01606         /* Requesting action from porter(s): override this API if this capability
01607            is supported. */
01608         return BLE_ERROR_NOT_IMPLEMENTED;
01609     }
01610 
01611     /**
01612      * Update connection parameters of an existing connection.
01613      *
01614      * In the central role, this initiates a Link Layer connection parameter
01615      * update procedure. In the peripheral role, this sends the corresponding
01616      * L2CAP request and waits for the central to perform the procedure.
01617      *
01618      * @param[in] handle Connection Handle.
01619      * @param[in] params Pointer to desired connection parameters.
01620      *
01621      * @return BLE_ERROR_NONE if the connection parameters were updated correctly.
01622      */
01623     virtual ble_error_t updateConnectionParams(
01624         Handle_t handle,
01625         const ConnectionParams_t *params
01626     ) {
01627         /* avoid compiler warnings about unused variables */
01628         (void)handle;
01629         (void)params;
01630 
01631         /* Requesting action from porter(s): override this API if this capability
01632            is supported. */
01633         return BLE_ERROR_NOT_IMPLEMENTED;
01634     }
01635 
01636     /**
01637      * Set the value of the device name characteristic in the Generic Access
01638      * Service.
01639      *
01640      * @param[in] deviceName The new value for the device-name. This is a
01641      * UTF-8 encoded, <b>NULL-terminated</b> string.
01642      *
01643      * @return BLE_ERROR_NONE if the device name was set correctly.
01644      */
01645     virtual ble_error_t setDeviceName(const uint8_t *deviceName) {
01646         /* Avoid compiler warnings about unused variables. */
01647         (void)deviceName;
01648 
01649         /* Requesting action from porter(s): override this API if this capability
01650            is supported. */
01651         return BLE_ERROR_NOT_IMPLEMENTED;
01652     }
01653 
01654     /**
01655      * Get the value of the device name characteristic in the Generic Access
01656      * Service.
01657      *
01658      * To obtain the length of the deviceName value, this function is
01659      * invoked with the @p deviceName parameter set to NULL.
01660      *
01661      * @param[out] deviceName Pointer to an empty buffer where the UTF-8
01662      * <b>non NULL-terminated</b> string is placed.
01663      *
01664      * @param[in,out] lengthP Length of the @p deviceName buffer. If the device
01665      * name is successfully copied, then the length of the device name
01666      * string (excluding the null terminator) replaces this value.
01667      *
01668      * @return BLE_ERROR_NONE if the device name was fetched correctly from the
01669      * underlying BLE stack.
01670      *
01671      * @note If the device name is longer than the size of the supplied buffer,
01672      * length returns the complete device name length and not the number of
01673      * bytes actually returned in deviceName. The application may use this
01674      * information to retry with a suitable buffer size.
01675      */
01676     virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP)
01677     {
01678         /* avoid compiler warnings about unused variables */
01679         (void)deviceName;
01680         (void)lengthP;
01681 
01682         /* Requesting action from porter(s): override this API if this capability
01683            is supported. */
01684         return BLE_ERROR_NOT_IMPLEMENTED;
01685     }
01686 
01687     /**
01688      * Set the value of the appearance characteristic in the GAP service.
01689      *
01690      * @param[in] appearance The new value for the device-appearance.
01691      *
01692      * @return BLE_ERROR_NONE if the new appearance was set correctly.
01693      */
01694     virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance)
01695     {
01696         /* Avoid compiler warnings about unused variables. */
01697         (void)appearance;
01698 
01699         /* Requesting action from porter(s): override this API if this capability
01700            is supported. */
01701         return BLE_ERROR_NOT_IMPLEMENTED;
01702     }
01703 
01704     /**
01705      * Get the value of the appearance characteristic in the GAP service.
01706      *
01707      * @param[out] appearanceP The current device-appearance value.
01708      *
01709      * @return BLE_ERROR_NONE if the device-appearance was fetched correctly
01710      * from the underlying BLE stack.
01711      */
01712     virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP)
01713     {
01714         /* Avoid compiler warnings about unused variables. */
01715         (void)appearanceP;
01716 
01717         /* Requesting action from porter(s): override this API if this capability
01718            is supported. */
01719         return BLE_ERROR_NOT_IMPLEMENTED;
01720     }
01721 
01722     /**
01723      * Set the radio's transmit power.
01724      *
01725      * @param[in] txPower Radio's transmit power in dBm.
01726      *
01727      * @return BLE_ERROR_NONE if the new radio's transmit power was set
01728      * correctly.
01729      */
01730     virtual ble_error_t setTxPower(int8_t txPower)
01731     {
01732         /* Avoid compiler warnings about unused variables. */
01733         (void)txPower;
01734 
01735         /* Requesting action from porter(s): override this API if this capability
01736            is supported. */
01737         return BLE_ERROR_NOT_IMPLEMENTED;
01738     }
01739 
01740     /**
01741      * Query the underlying stack for allowed Tx power values.
01742      *
01743      * @param[out] valueArrayPP Receive the immutable array of Tx values.
01744      * @param[out] countP Receive the array's size.
01745      */
01746     virtual void getPermittedTxPowerValues(
01747         const int8_t **valueArrayPP, size_t *countP
01748     ) {
01749         /* Avoid compiler warnings about unused variables. */
01750         (void)valueArrayPP;
01751         (void)countP;
01752 
01753         /* Requesting action from porter(s): override this API if this capability
01754            is supported. */
01755         *countP = 0;
01756     }
01757 
01758     /**
01759      * Get the maximum size of the whitelist.
01760      *
01761      * @return Maximum size of the whitelist.
01762      *
01763      * @note If using Mbed OS, you can configure the size of the whitelist by
01764      * setting the YOTTA_CFG_WHITELIST_MAX_SIZE macro in your yotta config file.
01765      */
01766     virtual uint8_t getMaxWhitelistSize(void) const
01767     {
01768         return 0;
01769     }
01770 
01771     /**
01772      * Get the Link Layer to use the internal whitelist when scanning,
01773      * advertising or initiating a connection depending on the filter policies.
01774      *
01775      * @param[in,out] whitelist Define the whitelist instance which is used
01776      * to store the whitelist requested. In input, the caller provisions memory.
01777      *
01778      * @return BLE_ERROR_NONE if the implementation's whitelist was successfully
01779      * copied into the supplied reference.
01780      */
01781     virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const
01782     {
01783         (void) whitelist;
01784         return BLE_ERROR_NOT_IMPLEMENTED;
01785     }
01786 
01787     /**
01788      * Set the value of the whitelist to be used during GAP procedures.
01789      *
01790      * @param[in] whitelist A reference to a whitelist containing the addresses
01791      * to be copied to the internal whitelist.
01792      *
01793      * @return BLE_ERROR_NONE if the implementation's whitelist was successfully
01794      * populated with the addresses in the given whitelist.
01795      *
01796      * @note The whitelist must not contain addresses of type @ref
01797      * BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE. This
01798      * results in a @ref BLE_ERROR_INVALID_PARAM because the remote peer might
01799      * change its private address at any time, and it is not possible to resolve
01800      * it.
01801      *
01802      * @note If the input whitelist is larger than @ref getMaxWhitelistSize(),
01803      * then @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned.
01804      */
01805     virtual ble_error_t setWhitelist(const Whitelist_t &whitelist)
01806     {
01807         (void) whitelist;
01808         return BLE_ERROR_NOT_IMPLEMENTED;
01809     }
01810 
01811     /**
01812      * Set the advertising policy filter mode to be used during the next
01813      * advertising procedure.
01814      *
01815      * @param[in] mode New advertising policy filter mode.
01816      *
01817      * @return BLE_ERROR_NONE if the specified policy filter mode was set
01818      * successfully.
01819      */
01820     virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode)
01821     {
01822         (void) mode;
01823         return BLE_ERROR_NOT_IMPLEMENTED;
01824     }
01825 
01826     /**
01827      * Set the scan policy filter mode to be used during the next scan procedure.
01828      *
01829      * @param[in] mode New scan policy filter mode.
01830      *
01831      * @return BLE_ERROR_NONE if the specified policy filter mode was set
01832      * successfully.
01833      */
01834     virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode)
01835     {
01836         (void) mode;
01837         return BLE_ERROR_NOT_IMPLEMENTED;
01838     }
01839 
01840     /**
01841      * Set the initiator policy filter mode to be used during the next connection
01842      * initiation.
01843      *
01844      * @param[in] mode New initiator policy filter mode.
01845      *
01846      * @return BLE_ERROR_NONE if the specified policy filter mode was set
01847      * successfully.
01848      */
01849     virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode)
01850     {
01851         (void) mode;
01852         return BLE_ERROR_NOT_IMPLEMENTED;
01853     }
01854 
01855     /**
01856      * Get the current advertising policy filter mode.
01857      *
01858      * @return The current advertising policy filter mode.
01859      */
01860     virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const
01861     {
01862         return ADV_POLICY_IGNORE_WHITELIST;
01863     }
01864 
01865     /**
01866      * Get the current scan policy filter mode.
01867      *
01868      * @return The current scan policy filter mode.
01869      */
01870     virtual ScanningPolicyMode_t getScanningPolicyMode(void) const
01871     {
01872         return SCAN_POLICY_IGNORE_WHITELIST;
01873     }
01874 
01875     /**
01876      * Get the current initiator policy filter mode.
01877      *
01878      * @return The current scan policy filter mode.
01879      */
01880     virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const
01881     {
01882         return INIT_POLICY_IGNORE_WHITELIST;
01883     }
01884 
01885 protected:
01886     /* Override the following in the underlying adaptation layer to provide the
01887       functionality of scanning. */
01888 
01889     /**
01890      * Start scanning procedure in the underlying BLE stack.
01891      *
01892      * @param[in] scanningParams Parameters of the scan procedure.
01893      *
01894      * @return BLE_ERROR_NONE if the scan procedure was successfully started.
01895      */
01896     virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams)
01897     {
01898         (void)scanningParams;
01899         /* Requesting action from porter(s): override this API if this capability
01900            is supported. */
01901         return BLE_ERROR_NOT_IMPLEMENTED;
01902     }
01903 
01904     /*
01905      * APIs with nonvirtual implementations.
01906      */
01907 public:
01908     /**
01909      * Get the current advertising and connection states of the device.
01910      *
01911      * @return The current GAP state of the device.
01912      */
01913     GapState_t getState(void) const
01914     {
01915         return state;
01916     }
01917 
01918     /**
01919      * Set the advertising type to use during the advertising procedure.
01920      *
01921      * @param[in] advType New type of advertising to use.
01922      */
01923     void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t advType)
01924     {
01925         _advParams.setAdvertisingType(advType);
01926     }
01927 
01928     /**
01929      * Set the advertising interval.
01930      *
01931      * @param[in] interval Advertising interval in units of milliseconds.
01932      * Advertising is disabled if interval is 0. If interval is smaller than
01933      * the minimum supported value, then the minimum supported value is used
01934      * instead. This minimum value can be discovered using
01935      * getMinAdvertisingInterval().
01936      *
01937      * This field must be set to 0 if connectionMode is equal
01938      * to ADV_CONNECTABLE_DIRECTED.
01939      *
01940      * @note  Decreasing this value allows central devices to detect a
01941      * peripheral faster, at the expense of the radio using more power
01942      * due to the higher data transmit rate.
01943      */
01944     void setAdvertisingInterval(uint16_t interval)
01945     {
01946         if (interval == 0) {
01947             stopAdvertising();
01948         } else if (interval < getMinAdvertisingInterval()) {
01949             interval = getMinAdvertisingInterval();
01950         }
01951         _advParams.setInterval(interval);
01952     }
01953 
01954     /**
01955      * Set the advertising duration.
01956      *
01957      * A timeout event is genenerated once the advertising period expired.
01958      *
01959      * @param[in] timeout Advertising timeout (in seconds) between 0x1 and 0x3FFF.
01960      * The special value 0 may be used to disable the advertising timeout.
01961      */
01962     void setAdvertisingTimeout(uint16_t timeout)
01963     {
01964         _advParams.setTimeout(timeout);
01965     }
01966 
01967     /**
01968      * Start the advertising procedure.
01969      *
01970      * @return BLE_ERROR_NONE if the device started advertising successfully.
01971      */
01972     ble_error_t startAdvertising(void)
01973     {
01974         ble_error_t rc;
01975         if ((rc = startAdvertising(_advParams)) == BLE_ERROR_NONE) {
01976             state.advertising = 1;
01977         }
01978         return rc;
01979     }
01980 
01981     /**
01982      * Reset the value of the advertising payload advertised.
01983      */
01984     void clearAdvertisingPayload(void)
01985     {
01986         _advPayload.clear();
01987         setAdvertisingData(_advPayload, _scanResponse);
01988     }
01989 
01990     /**
01991      * Set gap flags in the advertising payload.
01992      *
01993      * A call to this function is equivalent to:
01994      *
01995      * @code
01996      * Gap &gap;
01997      *
01998      * GapAdvertisingData payload = gap.getAdvertisingPayload();
01999      * payload.addFlags(flags);
02000      * gap.setAdvertisingPayload(payload);
02001      * @endcode
02002      *
02003      * @param[in] flags The flags to be added.
02004      *
02005      * @return BLE_ERROR_NONE if the data was successfully added to the
02006      * advertising payload.
02007      */
02008     ble_error_t accumulateAdvertisingPayload(uint8_t flags)
02009     {
02010         GapAdvertisingData advPayloadCopy = _advPayload;
02011         ble_error_t rc;
02012         if ((rc = advPayloadCopy.addFlags(flags)) != BLE_ERROR_NONE) {
02013             return rc;
02014         }
02015 
02016         rc = setAdvertisingData(advPayloadCopy, _scanResponse);
02017         if (rc == BLE_ERROR_NONE) {
02018             _advPayload = advPayloadCopy;
02019         }
02020 
02021         return rc;
02022     }
02023 
02024     /**
02025      * Set the appearance field in the advertising payload.
02026      *
02027      * A call to this function is equivalent to:
02028      *
02029      * @code
02030      * Gap &gap;
02031      *
02032      * GapAdvertisingData payload = gap.getAdvertisingPayload();
02033      * payload.addAppearance(app);
02034      * gap.setAdvertisingPayload(payload);
02035      * @endcode
02036      *
02037      * @param[in] app The appearance to advertise.
02038      *
02039      * @return BLE_ERROR_NONE if the data was successfully added to the
02040      * advertising payload.
02041      */
02042     ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app)
02043     {
02044         GapAdvertisingData advPayloadCopy = _advPayload;
02045         ble_error_t rc;
02046         if ((rc = advPayloadCopy.addAppearance(app)) != BLE_ERROR_NONE) {
02047             return rc;
02048         }
02049 
02050         rc = setAdvertisingData(advPayloadCopy, _scanResponse);
02051         if (rc == BLE_ERROR_NONE) {
02052             _advPayload = advPayloadCopy;
02053         }
02054 
02055         return rc;
02056     }
02057 
02058     /**
02059      * Set the Tx Power field in the advertising payload.
02060      *
02061      * A call to this function is equivalent to:
02062      *
02063      * @code
02064      * Gap &gap;
02065      *
02066      * GapAdvertisingData payload = gap.getAdvertisingPayload();
02067      * payload.addTxPower(power);
02068      * gap.setAdvertisingPayload(payload);
02069      * @endcode
02070      *
02071      * @param[in] power Transmit power in dBm used by the controller to advertise.
02072      *
02073      * @return BLE_ERROR_NONE if the data was successfully added to the
02074      * advertising payload.
02075      */
02076     ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power)
02077     {
02078         GapAdvertisingData advPayloadCopy = _advPayload;
02079         ble_error_t rc;
02080         if ((rc = advPayloadCopy.addTxPower(power)) != BLE_ERROR_NONE) {
02081             return rc;
02082         }
02083 
02084         rc = setAdvertisingData(advPayloadCopy, _scanResponse);
02085         if (rc == BLE_ERROR_NONE) {
02086             _advPayload = advPayloadCopy;
02087         }
02088 
02089         return rc;
02090     }
02091 
02092     /**
02093      * Add a new field in the advertising payload.
02094      *
02095      * A call to this function is equivalent to:
02096      *
02097      * @code
02098      * Gap &gap;
02099      *
02100      * GapAdvertisingData payload = gap.getAdvertisingPayload();
02101      * payload.addData(type, data, len);
02102      * gap.setAdvertisingPayload(payload);
02103      * @endcode
02104      *
02105      * @param[in] type Identity of the field being added.
02106      * @param[in] data Buffer containing the value of the field.
02107      * @param[in] len Length of the data buffer.
02108      *
02109      * @return BLE_ERROR_NONE if the advertisement payload was updated based on
02110      * matching AD type; otherwise, an appropriate error.
02111      *
02112      * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS,
02113      * COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS,
02114      * COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS,
02115      * COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the
02116      * supplied value is appended to the values previously added to the payload.
02117      */
02118     ble_error_t accumulateAdvertisingPayload(
02119         GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len
02120     ) {
02121         GapAdvertisingData advPayloadCopy = _advPayload;
02122         ble_error_t rc;
02123         if ((rc = advPayloadCopy.addData(type, data, len)) != BLE_ERROR_NONE) {
02124             return rc;
02125         }
02126 
02127         rc = setAdvertisingData(advPayloadCopy, _scanResponse);
02128         if (rc == BLE_ERROR_NONE) {
02129             _advPayload = advPayloadCopy;
02130         }
02131 
02132         return rc;
02133     }
02134 
02135     /**
02136      * Update a particular field in the advertising payload.
02137      *
02138      * A call to this function is equivalent to:
02139      *
02140      * @code
02141      * Gap &gap;
02142      *
02143      * GapAdvertisingData payload = gap.getAdvertisingPayload();
02144      * payload.updateData(type, data, len);
02145      * gap.setAdvertisingPayload(payload);
02146      * @endcode
02147      *
02148      *
02149      * @param[in] type Id of the field to update.
02150      * @param[in] data data buffer containing the new value of the field.
02151      * @param[in] len Length of the data buffer.
02152      *
02153      * @note If advertisements are enabled, then the update takes effect
02154      * immediately.
02155      *
02156      * @return BLE_ERROR_NONE if the advertisement payload was updated based on
02157      * matching AD type; otherwise, an appropriate error.
02158      */
02159     ble_error_t updateAdvertisingPayload(
02160         GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len
02161     ) {
02162         GapAdvertisingData advPayloadCopy = _advPayload;
02163         ble_error_t rc;
02164         if ((rc = advPayloadCopy.updateData(type, data, len)) != BLE_ERROR_NONE) {
02165             return rc;
02166         }
02167 
02168         rc = setAdvertisingData(advPayloadCopy, _scanResponse);
02169         if (rc == BLE_ERROR_NONE) {
02170             _advPayload = advPayloadCopy;
02171         }
02172 
02173         return rc;
02174     }
02175 
02176     /**
02177      * Set the value of the payload advertised.
02178      *
02179      * @param[in] payload A reference to a user constructed advertisement
02180      * payload to set.
02181      *
02182      * @return BLE_ERROR_NONE if the advertisement payload was successfully
02183      * set.
02184      */
02185     ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload)
02186     {
02187         ble_error_t rc = setAdvertisingData(payload, _scanResponse);
02188         if (rc == BLE_ERROR_NONE) {
02189             _advPayload = payload;
02190         }
02191 
02192         return rc;
02193     }
02194 
02195     /**
02196      * Get a reference to the current advertising payload.
02197      *
02198      * @return A reference to the current advertising payload.
02199      */
02200     const GapAdvertisingData &getAdvertisingPayload(void) const
02201     {
02202         return _advPayload;
02203     }
02204 
02205     /**
02206      * Add a new field in the advertising payload.
02207      *
02208      * @param[in] type AD type identifier.
02209      * @param[in] data buffer containing AD data.
02210      * @param[in] len Length of the data buffer.
02211      *
02212      * @return BLE_ERROR_NONE if the data was successfully added to the scan
02213      * response payload.
02214      */
02215     ble_error_t accumulateScanResponse(
02216         GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len
02217     ) {
02218         GapAdvertisingData scanResponseCopy = _scanResponse;
02219         ble_error_t rc;
02220         if ((rc = scanResponseCopy.addData(type, data, len)) != BLE_ERROR_NONE) {
02221             return rc;
02222         }
02223 
02224         rc = setAdvertisingData(_advPayload, scanResponseCopy);
02225         if (rc == BLE_ERROR_NONE) {
02226             _scanResponse = scanResponseCopy;
02227         }
02228 
02229         return rc;
02230     }
02231 
02232     /**
02233      * Reset the content of the scan response.
02234      *
02235      * @note This should be followed by a call to Gap::setAdvertisingPayload()
02236      * or Gap::startAdvertising() before the update takes effect.
02237      */
02238     void clearScanResponse(void) {
02239         _scanResponse.clear();
02240         setAdvertisingData(_advPayload, _scanResponse);
02241     }
02242 
02243     /**
02244      * Set the parameters used during a scan procedure.
02245      *
02246      * @param[in] interval in ms between the start of two consecutive scan windows.
02247      * That value is greater or equal to the scan window value. The
02248      * maximum allowed value is 10.24ms.
02249      *
02250      * @param[in] window Period in ms during which the scanner listens to
02251      * advertising channels. That value is in the range 2.5ms to 10.24s.
02252      *
02253      * @param[in] timeout Duration in seconds of the scan procedure if any. The
02254      * special value 0 disable specific duration of the scan procedure.
02255      *
02256      * @param[in] activeScanning If set to true, then the scanner sends scan
02257      * requests to a scannable or connectable advertiser. If set to false, then the
02258      * scanner does not send any request during the scan procedure.
02259      *
02260      * @return BLE_ERROR_NONE if the scan parameters were correctly set.
02261      *
02262      * @note The scanning window divided by the interval determines the duty
02263      * cycle for scanning. For example, if the interval is 100ms and the window
02264      * is 10ms, then the controller scans for 10 percent of the time.
02265      *
02266      * @note If the interval and the window are set to the same value, then the
02267      * device scans continuously during the scan procedure. The scanning
02268      * frequency changes at every interval.
02269      *
02270      * @note Once the scanning parameters have been configured, scanning can be
02271      * enabled by using startScan().
02272      *
02273      * @note The scan interval and window are recommendations to the BLE stack.
02274      */
02275     ble_error_t setScanParams(
02276         uint16_t interval = GapScanningParams::SCAN_INTERVAL_MAX,
02277         uint16_t window = GapScanningParams::SCAN_WINDOW_MAX,
02278         uint16_t timeout = 0,
02279         bool activeScanning = false
02280     ) {
02281         ble_error_t rc;
02282         if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) &&
02283             ((rc = _scanningParams.setWindow(window))     == BLE_ERROR_NONE) &&
02284             ((rc = _scanningParams.setTimeout(timeout))   == BLE_ERROR_NONE)) {
02285             _scanningParams.setActiveScanning(activeScanning);
02286             return BLE_ERROR_NONE;
02287         }
02288 
02289         return rc;
02290     }
02291 
02292     /**
02293      * Set the parameters used during a scan procedure.
02294      *
02295      * @param[in] scanningParams Parameter struct containing the interval, period,
02296      * timeout and active scanning toggle.
02297      *
02298      * @return BLE_ERROR_NONE if the scan parameters were correctly set.
02299      *
02300      * @note All restrictions from setScanParams(uint16_t, uint16_t, uint16_t, bool) apply.
02301      */
02302     ble_error_t setScanParams(const GapScanningParams& scanningParams) {
02303         return setScanParams(
02304             scanningParams.getInterval(),
02305             scanningParams.getWindow(),
02306             scanningParams.getTimeout(),
02307             scanningParams.getActiveScanning()
02308         );
02309     }
02310 
02311     /**
02312      * Set the interval parameter used during scanning procedures.
02313      *
02314      * @param[in] interval Interval in ms between the start of two consecutive
02315      * scan windows. That value is greater or equal to the scan window value.
02316      * The maximum allowed value is 10.24ms.
02317      *
02318      * @return BLE_ERROR_NONE if the scan interval was correctly set.
02319      */
02320     ble_error_t setScanInterval(uint16_t interval)
02321     {
02322         return _scanningParams.setInterval(interval);
02323     }
02324 
02325     /**
02326      * Set the window parameter used during scanning procedures.
02327      *
02328      * @param[in] window Period in ms during which the scanner listens to
02329      * advertising channels. That value is in the range 2.5ms to 10.24s.
02330      *
02331      * @return BLE_ERROR_NONE if the scan window was correctly set.
02332      *
02333      * @note If scanning is already active, the updated value of scanWindow
02334      * is propagated to the underlying BLE stack.
02335      */
02336     ble_error_t setScanWindow(uint16_t window)
02337     {
02338         ble_error_t rc;
02339         if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) {
02340             return rc;
02341         }
02342 
02343         /* If scanning is already active, propagate the new setting to the stack. */
02344         if (scanningActive) {
02345             return startRadioScan(_scanningParams);
02346         }
02347 
02348         return BLE_ERROR_NONE;
02349     }
02350 
02351     /**
02352      * Set the timeout parameter used during scanning procedures.
02353      *
02354      * @param[in] timeout Duration in seconds of the scan procedure if any. The
02355      * special value 0 disables specific duration of the scan procedure.
02356      *
02357      * @return BLE_ERROR_NONE if the scan timeout was correctly set.
02358      *
02359      * @note If scanning is already active, the updated value of scanTimeout
02360      * is propagated to the underlying BLE stack.
02361      */
02362     ble_error_t setScanTimeout(uint16_t timeout)
02363     {
02364         ble_error_t rc;
02365         if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) {
02366             return rc;
02367         }
02368 
02369         /* If scanning is already active, propagate the new settings to the stack. */
02370         if (scanningActive) {
02371             return startRadioScan(_scanningParams);
02372         }
02373 
02374         return BLE_ERROR_NONE;
02375     }
02376 
02377     /**
02378      * Enable or disable active scanning.
02379      *
02380      * @param[in] activeScanning If set to true, then the scanner sends scan
02381      * requests to a scannable or connectable advertiser. If set to false then the
02382      * scanner does not send any request during the scan procedure.
02383      *
02384      * @return BLE_ERROR_NONE if active scanning was successfully set.
02385      *
02386      * @note If scanning is already in progress, then active scanning is
02387      * enabled for the underlying BLE stack.
02388      */
02389     ble_error_t setActiveScanning(bool activeScanning)
02390     {
02391         _scanningParams.setActiveScanning(activeScanning);
02392 
02393         /* If scanning is already active, propagate the new settings to the stack. */
02394         if (scanningActive) {
02395             return startRadioScan(_scanningParams);
02396         }
02397 
02398         return BLE_ERROR_NONE;
02399     }
02400 
02401     /**
02402      * Start the scanning procedure.
02403      *
02404      * Packets received during the scan procedure are forwarded to the
02405      * scan packet handler passed as argument to this function.
02406      *
02407      * @param[in] callback Advertisement packet event handler. Upon reception
02408      * of an advertising packet, the packet is forwarded to @p callback.
02409      *
02410      * @return BLE_ERROR_NONE if the device successfully started the scan
02411      *         procedure.
02412      *
02413      * @note The parameters used by the procedure are defined by setScanParams().
02414      */
02415     ble_error_t startScan(
02416         void (*callback)(const AdvertisementCallbackParams_t *params)
02417     ) {
02418         ble_error_t err = BLE_ERROR_NONE;
02419         if (callback) {
02420             if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) {
02421                 scanningActive = true;
02422                 onAdvertisementReport.attach(callback);
02423             }
02424         }
02425 
02426         return err;
02427     }
02428 
02429     /**
02430      * Start the scanning procedure.
02431      *
02432      * Packets received during the scan procedure are forwarded to the
02433      * scan packet handler passed as argument to this function.
02434      *
02435      * @param[in] object Instance used to invoke @p callbackMember.
02436      *
02437      * @param[in] callbackMember Advertisement packet event handler. Upon
02438      * reception of an advertising packet, the packet is forwarded to @p
02439      * callback invoked from @p object.
02440      *
02441      * @return BLE_ERROR_NONE if the device successfully started the scan
02442      * procedure.
02443      *
02444      * @note The parameters used by the procedure are defined by setScanParams().
02445      */
02446     template<typename T>
02447     ble_error_t startScan(
02448         T *object,
02449         void (T::*callbackMember)(const AdvertisementCallbackParams_t *params)
02450     ) {
02451         ble_error_t err = BLE_ERROR_NONE;
02452         if (object && callbackMember) {
02453             if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) {
02454                 scanningActive = true;
02455                 onAdvertisementReport.attach(object, callbackMember);
02456             }
02457         }
02458 
02459         return err;
02460     }
02461 
02462     /**
02463      * Enable radio-notification events.
02464      *
02465      * Radio Notification is a feature that notifies the application when the
02466      * radio is in use.
02467      *
02468      * The ACTIVE signal is sent before the radio event starts. The nACTIVE
02469      * signal is sent at the end of the radio event. The application programmer can
02470      * use these signals to synchronize application logic with radio
02471      * activity. For example, the ACTIVE signal can be used to shut off external
02472      * devices, to manage peak current drawn during periods when the radio is on
02473      * or to trigger sensor data collection for transmission in the Radio Event.
02474      *
02475      * @return BLE_ERROR_NONE on successful initialization, otherwise an error code.
02476      */
02477     virtual ble_error_t initRadioNotification(void)
02478     {
02479         /* Requesting action from porter(s): override this API if this capability
02480            is supported. */
02481         return BLE_ERROR_NOT_IMPLEMENTED;
02482     }
02483 
02484     /**
02485      * Enable or disable privacy mode of the local device.
02486      *
02487      * When privacy is enabled, the system use private addresses while it scans,
02488      * advertises or initiate a connection. The device private address is
02489      * renewed every 15 minutes.
02490      *
02491      * @par Configuration
02492      *
02493      * The privacy feature can be configured with the help of the functions
02494      * setPeripheralPrivacyConfiguration and setCentralPrivacyConfiguration
02495      * which respectively set the privacy configuration of the peripheral and
02496      * central role.
02497      *
02498      * @par Default configuration of peripheral role
02499      *
02500      * By default private resolvable addresses are used for all procedures;
02501      * including advertisement of non connectable packets. Connection request
02502      * from an unknown initiator with a private resolvable address triggers the
02503      * pairing procedure.
02504      *
02505      * @par Default configuration of central role
02506      *
02507      * By default private resolvable addresses are used for all procedures;
02508      * including active scanning. Addresses present in advertisement packet are
02509      * resolved and advertisement packets are forwarded to the application
02510      * even if the advertiser private address is unknown.
02511      *
02512      * @param[in] enable Should be set to true to enable the privacy mode and
02513      * false to disable it.
02514      *
02515      * @return BLE_ERROR_NONE in case of success or an appropriate error code.
02516      */
02517     virtual ble_error_t enablePrivacy(bool enable) {
02518         return BLE_ERROR_NOT_IMPLEMENTED;
02519     }
02520 
02521     /**
02522      * Set the privacy configuration used by the peripheral role.
02523      *
02524      * @param[in] configuration The configuration to set.
02525      *
02526      * @return BLE_ERROR_NONE in case of success or an appropriate error code.
02527      */
02528     virtual ble_error_t setPeripheralPrivacyConfiguration(
02529         const PeripheralPrivacyConfiguration_t *configuration
02530     ) {
02531         return BLE_ERROR_NOT_IMPLEMENTED;
02532     }
02533 
02534     /**
02535      * Get the privacy configuration used by the peripheral role.
02536      *
02537      * @param[out] configuration The variable filled with the current
02538      * configuration.
02539      *
02540      * @return BLE_ERROR_NONE in case of success or an appropriate error code.
02541      */
02542     virtual ble_error_t getPeripheralPrivacyConfiguration(
02543         PeripheralPrivacyConfiguration_t *configuration
02544     ) {
02545         return BLE_ERROR_NOT_IMPLEMENTED;
02546     }
02547 
02548     /**
02549      * Set the privacy configuration used by the central role.
02550      *
02551      * @param[in] configuration The configuration to set.
02552      *
02553      * @return BLE_ERROR_NONE in case of success or an appropriate error code.
02554      */
02555     virtual ble_error_t setCentralPrivacyConfiguration(
02556         const CentralPrivacyConfiguration_t *configuration
02557     ) {
02558         return BLE_ERROR_NOT_IMPLEMENTED;
02559     }
02560 
02561     /**
02562      * Get the privacy configuration used by the central role.
02563      *
02564      * @param[out] configuration The variable filled with the current
02565      * configuration.
02566      *
02567      * @return BLE_ERROR_NONE in case of success or an appropriate error code.
02568      */
02569     virtual ble_error_t getCentralPrivacyConfiguration(
02570         CentralPrivacyConfiguration_t *configuration
02571     ) {
02572         return BLE_ERROR_NOT_IMPLEMENTED;
02573     }
02574 
02575 private:
02576     /**
02577      * Set the advertising data and scan response in the vendor subsytem.
02578      *
02579      * @param[in] advData Advertising data to set.
02580      * @param[in] scanResponse Scan response to set.
02581      *
02582      * @return BLE_ERROR_NONE if the advertising data was set successfully.
02583      *
02584      * @note Must be implemented in vendor port.
02585      */
02586     virtual ble_error_t setAdvertisingData(
02587         const GapAdvertisingData &advData,
02588         const GapAdvertisingData &scanResponse
02589     ) = 0;
02590 
02591     /**
02592      * Start the advertising procedure.
02593      *
02594      * @param[in] params Advertising parameters to use.
02595      *
02596      * @return BLE_ERROR_NONE if the advertising procedure successfully
02597      * started.
02598      *
02599      * @note Must be implemented in vendor port.
02600      */
02601     virtual ble_error_t startAdvertising(const GapAdvertisingParams &params) = 0;
02602 
02603 public:
02604     /**
02605      * Get the current advertising parameters.
02606      *
02607      * @return A reference to the current advertising parameters.
02608      */
02609     GapAdvertisingParams &getAdvertisingParams(void)
02610     {
02611         return _advParams;
02612     }
02613 
02614     /**
02615      * Const alternative to Gap::getAdvertisingParams().
02616      *
02617      * @return A const reference to the current advertising parameters.
02618      */
02619     const GapAdvertisingParams &getAdvertisingParams(void) const
02620     {
02621         return _advParams;
02622     }
02623 
02624     /**
02625      * Set the advertising parameters.
02626      *
02627      * @param[in] newParams The new advertising parameters.
02628      */
02629     void setAdvertisingParams(const GapAdvertisingParams &newParams)
02630     {
02631         _advParams = newParams;
02632     }
02633 
02634     /* Event handlers. */
02635 public:
02636 
02637     /**
02638      * Assign the event handler implementation that will be used by the gap
02639      * module to signal events back to the application.
02640      *
02641      * @param handler Application implementation of an Eventhandler.
02642      */
02643     void setEventHandler(EventHandler* handler) {
02644         _eventHandler = handler;
02645     }
02646 
02647     /**
02648      * Register a callback handling timeout events.
02649      *
02650      * @param[in] callback Event handler being registered.
02651      *
02652      * @note A callback may be unregistered using onTimeout().detach(callback).
02653      *
02654      * @see TimeoutSource_t
02655      */
02656     void onTimeout(TimeoutEventCallback_t callback)
02657     {
02658         timeoutCallbackChain.add(callback);
02659     }
02660 
02661     /**
02662      * Get the callchain of registered timeout event handlers.
02663      *
02664      * @note To register callbacks, use onTimeout().add(callback).
02665      *
02666      * @note To unregister callbacks, use onTimeout().detach(callback).
02667      *
02668      * @return A reference to the timeout event callbacks chain.
02669      */
02670     TimeoutEventCallbackChain_t & onTimeout()
02671     {
02672         return timeoutCallbackChain;
02673     }
02674 
02675     /**
02676      * Register a callback handling connection events.
02677      *
02678      * @param[in] callback Event handler being registered.
02679      *
02680      * @note A callback may be unregistered using onConnection().detach(callback).
02681      */
02682     void onConnection(ConnectionEventCallback_t  callback)
02683     {
02684         connectionCallChain.add(callback);
02685     }
02686 
02687     /**
02688      * Register a callback handling connection events.
02689      *
02690      * @param[in] tptr Instance used to invoke @p mptr.
02691      * @param[in] mptr Event handler being registered.
02692      *
02693      * @note A callback may be unregistered using onConnection().detach(callback).
02694      */
02695     template<typename T>
02696     void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*))
02697     {
02698         connectionCallChain.add(tptr, mptr);
02699     }
02700 
02701     /**
02702      * Get the callchain of registered connection event handlers.
02703      *
02704      * @note To register callbacks, use onConnection().add(callback).
02705      *
02706      * @note To unregister callbacks, use onConnection().detach(callback).
02707      *
02708      * @return A reference to the connection event callbacks chain.
02709      */
02710     ConnectionEventCallbackChain_t & onConnection()
02711     {
02712         return connectionCallChain;
02713     }
02714 
02715     /**
02716      * Register a callback handling disconnection events.
02717      *
02718      * @param[in] callback Event handler being registered.
02719      *
02720      * @note A callback may be unregistered using onDisconnection().detach(callback).
02721      */
02722     void onDisconnection(DisconnectionEventCallback_t  callback)
02723     {
02724         disconnectionCallChain.add(callback);
02725     }
02726 
02727     /**
02728      * Register a callback handling disconnection events.
02729      *
02730      * @param[in] tptr Instance used to invoke mptr.
02731      * @param[in] mptr Event handler being registered.
02732      *
02733      * @note A callback may be unregistered using onDisconnection().detach(callback).
02734      */
02735     template<typename T>
02736     void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*))
02737     {
02738         disconnectionCallChain.add(tptr, mptr);
02739     }
02740 
02741     /**
02742      * Get the callchain of registered disconnection event handlers.
02743      *
02744      * @note To register callbacks use onDisconnection().add(callback).
02745      *
02746      * @note To unregister callbacks use onDisconnection().detach(callback).
02747      *
02748      * @return A reference to the disconnection event callbacks chain.
02749      */
02750     DisconnectionEventCallbackChain_t & onDisconnection()
02751     {
02752         return disconnectionCallChain;
02753     }
02754 
02755     /**
02756      * Set the radio-notification events handler.
02757      *
02758      * Radio Notification is a feature that enables ACTIVE and INACTIVE
02759      * (nACTIVE) signals from the stack that notify the application when the
02760      * radio is in use.
02761      *
02762      * The ACTIVE signal is sent before the radio event starts. The nACTIVE
02763      * signal is sent at the end of the radio event. The application programmer can
02764      * use these signals to synchronize application logic with radio
02765      * activity. For example, the ACTIVE signal can be used to shut off external
02766      * devices, to manage peak current drawn during periods when the radio is on
02767      * or to trigger sensor data collection for transmission in the Radio Event.
02768      *
02769      * @param[in] callback Application handler to be invoked in response to a
02770      * radio ACTIVE/INACTIVE event.
02771      */
02772     void onRadioNotification(void (*callback)(bool param))
02773     {
02774         radioNotificationCallback.attach(callback);
02775     }
02776 
02777     /**
02778      * Set the radio-notification events handler.
02779      *
02780      * @param[in] tptr Instance to be used to invoke mptr.
02781      * @param[in] mptr Application handler to be invoked in response to a
02782      * radio ACTIVE/INACTIVE event.
02783      */
02784     template <typename T>
02785     void onRadioNotification(T *tptr, void (T::*mptr)(bool))
02786     {
02787         radioNotificationCallback.attach(tptr, mptr);
02788     }
02789 
02790     /**
02791      * Register a Gap shutdown event handler.
02792      *
02793      * The handler is called when the Gap instance is about to shut down.
02794      * It is usually issued after a call to BLE::shutdown().
02795      *
02796      * @param[in] callback Shutdown event handler to register.
02797      *
02798      * @note To unregister a shutdown event handler, use
02799      * onShutdown().detach(callback).
02800      */
02801     void onShutdown(const GapShutdownCallback_t& callback)
02802     {
02803         shutdownCallChain.add(callback);
02804     }
02805 
02806     /**
02807      * Register a Gap shutdown event handler.
02808      *
02809      * @param[in] objPtr Instance used to invoke @p memberPtr.
02810      * @param[in] memberPtr Shutdown event handler to register.
02811      */
02812     template <typename T>
02813     void onShutdown(T *objPtr, void (T::*memberPtr)(const Gap *))
02814     {
02815         shutdownCallChain.add(objPtr, memberPtr);
02816     }
02817 
02818     /**
02819      * Access the callchain of shutdown event handler.
02820      *
02821      * @note To register callbacks, use onShutdown().add(callback).
02822      *
02823      * @note To unregister callbacks, use onShutdown().detach(callback).
02824      *
02825      * @return A reference to the shutdown event callback chain.
02826      */
02827     GapShutdownCallbackChain_t & onShutdown()
02828     {
02829         return shutdownCallChain;
02830     }
02831 
02832 public:
02833     /**
02834      * Reset the Gap instance.
02835      *
02836      * Reset process starts by notifying all registered shutdown event handlers
02837      * that the Gap instance is about to be shut down. Then, it clears all Gap state
02838      * of the associated object and then cleans the state present in the vendor
02839      * implementation.
02840      *
02841      * This function is meant to be overridden in the platform-specific
02842      * subclass. Nevertheless, the subclass only resets its
02843      * state and not the data held in Gap members. This is achieved by a
02844      * call to Gap::reset() from the subclass' reset() implementation.
02845      *
02846      * @return BLE_ERROR_NONE on success.
02847      *
02848      * @note Currently, a call to reset() does not reset the advertising and
02849      * scan parameters to default values.
02850      */
02851     virtual ble_error_t reset(void)
02852     {
02853         /* Notify that the instance is about to shut down */
02854         shutdownCallChain.call(this);
02855         shutdownCallChain.clear();
02856 
02857         /* Clear Gap state */
02858         state.advertising = 0;
02859         state.connected   = 0;
02860         connectionCount   = 0;
02861 
02862         /* Clear scanning state */
02863         scanningActive = false;
02864 
02865         /* Clear advertising and scanning data */
02866         _advPayload.clear();
02867         _scanResponse.clear();
02868 
02869         /* Clear callbacks */
02870         timeoutCallbackChain.clear();
02871         connectionCallChain.clear();
02872         disconnectionCallChain.clear();
02873         radioNotificationCallback = NULL;
02874         onAdvertisementReport     = NULL;
02875         _eventHandler = NULL;
02876 
02877         return BLE_ERROR_NONE;
02878     }
02879 
02880 protected:
02881     /**
02882      * Construct a Gap instance.
02883      */
02884     Gap() :
02885         _advParams(),
02886         _advPayload(),
02887         _scanningParams(),
02888         _scanResponse(),
02889         connectionCount(0),
02890         state(),
02891         scanningActive(false),
02892         timeoutCallbackChain(),
02893         radioNotificationCallback(),
02894         onAdvertisementReport(),
02895         connectionCallChain(),
02896         disconnectionCallChain(),
02897         _eventHandler(NULL) {
02898         _advPayload.clear();
02899         _scanResponse.clear();
02900     }
02901 
02902     /* Entry points for the underlying stack to report events back to the user. */
02903 public:
02904     /**
02905      * Notify all registered connection event handlers of a connection event.
02906      *
02907      * @attention This function is meant to be called from the BLE stack specific
02908      * implementation when a connection event occurs.
02909      *
02910      * @param[in] handle Handle of the new connection.
02911      * @param[in] role Role of this BLE device in the connection.
02912      * @param[in] peerAddrType Address type of the connected peer.
02913      * @param[in] peerAddr Address of the connected peer.
02914      * @param[in] ownAddrType Address type this device uses for this
02915      * connection.
02916      * @param[in] ownAddr Address this device uses for this connection. This
02917      * parameter may be NULL if the local address is not available.
02918      * @param[in] connectionParams Parameters of the connection.
02919      * @param[in] peerResolvableAddr Resolvable address used by the peer.
02920      * @param[in] localResolvableAddr resolvable address used by the local device.
02921      */
02922     void processConnectionEvent(
02923         Handle_t handle,
02924         Role_t role,
02925         PeerAddressType_t peerAddrType,
02926         const BLEProtocol::AddressBytes_t peerAddr,
02927         BLEProtocol::AddressType_t ownAddrType,
02928         const BLEProtocol::AddressBytes_t ownAddr,
02929         const ConnectionParams_t *connectionParams,
02930         const uint8_t *peerResolvableAddr = NULL,
02931         const uint8_t *localResolvableAddr = NULL
02932     );
02933 
02934     /**
02935      * Notify all registered connection event handlers of a connection event.
02936      *
02937      * @attention This function is meant to be called from the BLE stack specific
02938      * implementation when a connection event occurs.
02939      *
02940      * @param[in] handle Handle of the new connection.
02941      * @param[in] role Role of this BLE device in the connection.
02942      * @param[in] peerAddrType Address type of the connected peer.
02943      * @param[in] peerAddr Address of the connected peer.
02944      * @param[in] ownAddrType Address type this device uses for this
02945      * connection.
02946      * @param[in] ownAddr Address this device uses for this connection.
02947      * @param[in] connectionParams Parameters of the connection.
02948      * @param[in] peerResolvableAddr Resolvable address used by the peer.
02949      * @param[in] localResolvableAddr resolvable address used by the local device.
02950      *
02951      * @deprecated The type BLEProtocol::AddressType_t is not suitable when
02952      * privacy is enabled. Use the overload that accepts a PeerAddressType_t
02953      * instead.
02954      */
02955     MBED_DEPRECATED_SINCE(
02956        "mbed-os-5.9.0",
02957        "The type BLEProtocol::AddressType_t is not suitable when privacy is "
02958        "enabled. Use the overload that accepts a PeerAddressType_t instead."
02959     )
02960     void processConnectionEvent(
02961         Handle_t handle,
02962         Role_t role,
02963         BLEProtocol::AddressType_t peerAddrType,
02964         const BLEProtocol::AddressBytes_t peerAddr,
02965         BLEProtocol::AddressType_t ownAddrType,
02966         const BLEProtocol::AddressBytes_t ownAddr,
02967         const ConnectionParams_t *connectionParams,
02968         const uint8_t *peerResolvableAddr = NULL,
02969         const uint8_t *localResolvableAddr = NULL
02970     );
02971 
02972     /**
02973      * Notify all registered disconnection event handlers of a disconnection event.
02974      *
02975      * @attention This function is meant to be called from the BLE stack specific
02976      * implementation when a disconnection event occurs.
02977      *
02978      * @param[in] handle Handle of the terminated connection.
02979      * @param[in] reason Reason of the disconnection.
02980      */
02981     void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason)
02982     {
02983         /* Update Gap state */
02984         --connectionCount;
02985         if (!connectionCount) {
02986             state.connected = 0;
02987         }
02988 
02989         DisconnectionCallbackParams_t callbackParams(handle, reason);
02990         disconnectionCallChain.call(&callbackParams);
02991     }
02992 
02993     /**
02994      * Forward a received advertising packet to all registered event handlers
02995      * listening for scanned packet events.
02996      *
02997      * @attention This function is meant to be called from the BLE stack specific
02998      * implementation when a disconnection event occurs.
02999      *
03000      * @param[in] peerAddr Address of the peer that has emitted the packet.
03001      * @param[in] rssi Value of the RSSI measured for the received packet.
03002      * @param[in] isScanResponse If true, then the packet is a response to a scan
03003      * request.
03004      * @param[in] type Advertising type of the packet.
03005      * @param[in] advertisingDataLen Length of the advertisement data received.
03006      * @param[in] advertisingData Pointer to the advertisement packet's data.
03007      * @param[in] addressType Type of the address of the peer that has emitted
03008      * the packet.
03009      */
03010     void processAdvertisementReport(
03011         const BLEProtocol::AddressBytes_t peerAddr,
03012         int8_t rssi,
03013         bool isScanResponse,
03014         GapAdvertisingParams::AdvertisingType_t type,
03015         uint8_t advertisingDataLen,
03016         const uint8_t *advertisingData,
03017         PeerAddressType_t addressType
03018     );
03019 
03020     /**
03021      * Forward a received advertising packet to all registered event handlers
03022      * listening for scanned packet events.
03023      *
03024      * @attention This function is meant to be called from the BLE stack specific
03025      * implementation when a disconnection event occurs.
03026      *
03027      * @param[in] peerAddr Address of the peer that has emitted the packet.
03028      * @param[in] rssi Value of the RSSI measured for the received packet.
03029      * @param[in] isScanResponse If true, then the packet is a response to a scan
03030      * request.
03031      * @param[in] type Advertising type of the packet.
03032      * @param[in] advertisingDataLen Length of the advertisement data received.
03033      * @param[in] advertisingData Pointer to the advertisement packet's data.
03034      * @param[in] addressType Type of the address of the peer that has emitted the packet.
03035      *
03036      * @deprecated The type BLEProtocol::AddressType_t is not suitable when
03037      * privacy is enabled. Use the overload that accepts a PeerAddressType_t
03038      * instead.
03039      */
03040     MBED_DEPRECATED_SINCE(
03041        "mbed-os-5.9.0",
03042        "The type BLEProtocol::AddressType_t is not suitable when privacy is "
03043        "enabled. Use the overload that accepts a PeerAddressType_t instead."
03044     )
03045     void processAdvertisementReport(
03046         const BLEProtocol::AddressBytes_t peerAddr,
03047         int8_t rssi,
03048         bool isScanResponse,
03049         GapAdvertisingParams::AdvertisingType_t type,
03050         uint8_t advertisingDataLen,
03051         const uint8_t *advertisingData,
03052         BLEProtocol::AddressType_t addressType = BLEProtocol::AddressType::RANDOM_STATIC
03053     );
03054 
03055     /**
03056      * Notify the occurrence of a timeout event to all registered timeout events
03057      * handler.
03058      *
03059      * @attention This function is meant to be called from the BLE stack specific
03060      * implementation when a disconnection event occurs.
03061      *
03062      * @param[in] source Source of the timout event.
03063      */
03064     void processTimeoutEvent(TimeoutSource_t source)
03065     {
03066         if (source == TIMEOUT_SRC_ADVERTISING) {
03067             /* Update gap state if the source is an advertising timeout */
03068             state.advertising = 0;
03069         }
03070         if (timeoutCallbackChain) {
03071             timeoutCallbackChain(source);
03072         }
03073     }
03074 
03075 protected:
03076     /**
03077      * Current advertising parameters.
03078      */
03079     GapAdvertisingParams _advParams;
03080 
03081     /**
03082      * Current advertising data.
03083      */
03084     GapAdvertisingData _advPayload;
03085 
03086     /**
03087      * Current scanning parameters.
03088      */
03089     GapScanningParams _scanningParams;
03090 
03091     /**
03092      * Current scan response.
03093      */
03094     GapAdvertisingData _scanResponse;
03095 
03096     /**
03097      * Number of open connections.
03098      */
03099     uint8_t connectionCount;
03100 
03101     /**
03102      * Current GAP state.
03103      */
03104     GapState_t state;
03105 
03106     /**
03107      * Active scanning flag.
03108      */
03109     bool scanningActive;
03110 
03111 protected:
03112     /**
03113      * Callchain containing all registered callback handlers for timeout
03114      * events.
03115      */
03116     TimeoutEventCallbackChain_t  timeoutCallbackChain;
03117 
03118     /**
03119      * The registered callback handler for radio notification events.
03120      */
03121     RadioNotificationEventCallback_t radioNotificationCallback;
03122 
03123     /**
03124      * The registered callback handler for scanned advertisement packet
03125      * notifications.
03126      */
03127     AdvertisementReportCallback_t  onAdvertisementReport;
03128 
03129     /**
03130      * Callchain containing all registered callback handlers for connection
03131      * events.
03132      */
03133     ConnectionEventCallbackChain_t  connectionCallChain;
03134 
03135     /**
03136      * Callchain containing all registered callback handlers for disconnection
03137      * events.
03138      */
03139     DisconnectionEventCallbackChain_t  disconnectionCallChain;
03140 
03141     /**
03142      * Event handler provided by the application.
03143      */
03144     EventHandler* _eventHandler;
03145 
03146 private:
03147     /**
03148      * Callchain containing all registered callback handlers for shutdown
03149      * events.
03150      */
03151     GapShutdownCallbackChain_t  shutdownCallChain;
03152 
03153 private:
03154     /* Disallow copy and assignment. */
03155     Gap(const Gap &);
03156     Gap& operator=(const Gap &);
03157 };
03158 
03159 /**
03160  * @}
03161  * @}
03162  */
03163 
03164 #endif // ifndef MBED_BLE_GAP_H__