Lancaster University's fork of the mbed BLE API. Lives on github, https://github.com/lancaster-university/BLE_API

Dependents:   microbit-dal microbit-dal microbit-ble-open microbit-dal ... more

Fork of BLE_API by Bluetooth Low Energy

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 __GAP_H__
00018 #define __GAP_H__
00019 
00020 #include "ble/BLEProtocol.h"
00021 #include "GapAdvertisingData.h"
00022 #include "GapAdvertisingParams.h"
00023 #include "GapScanningParams.h"
00024 #include "GapEvents.h"
00025 #include "CallChainOfFunctionPointersWithContext.h"
00026 #include "FunctionPointerWithContext.h"
00027 #include "deprecate.h"
00028 
00029 /* Forward declarations for classes that will only be used for pointers or references in the following. */
00030 class GapAdvertisingParams;
00031 class GapScanningParams;
00032 class GapAdvertisingData;
00033 
00034 class Gap {
00035     /*
00036      * DEPRECATION ALERT: all of the APIs in this `public` block are deprecated.
00037      * They have been relocated to the class BLEProtocol.
00038      */
00039 public:
00040     /**
00041      * Address-type for BLEProtocol addresses.
00042      *
00043      * @note: deprecated. Use BLEProtocol::AddressType_t instead.
00044      */
00045     typedef BLEProtocol::AddressType_t AddressType_t;
00046 
00047     /**
00048      * Address-type for BLEProtocol addresses.
00049      * @note: deprecated. Use BLEProtocol::AddressType_t instead.
00050      */
00051     typedef BLEProtocol::AddressType_t addr_type_t;
00052 
00053     /**
00054      * Address-type for BLEProtocol addresses.
00055      * \deprecated: Use BLEProtocol::AddressType_t instead.
00056      *
00057      * DEPRECATION ALERT: The following constants have been left in their
00058      * deprecated state to transparenly support existing applications which may
00059      * have used Gap::ADDR_TYPE_*.
00060      */
00061     enum DeprecatedAddressType_t {
00062         ADDR_TYPE_PUBLIC                        = BLEProtocol::AddressType::PUBLIC,
00063         ADDR_TYPE_RANDOM_STATIC                 = BLEProtocol::AddressType::RANDOM_STATIC,
00064         ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE     = BLEProtocol::AddressType::RANDOM_PRIVATE_RESOLVABLE,
00065         ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE = BLEProtocol::AddressType::RANDOM_PRIVATE_NON_RESOLVABLE
00066     };
00067 
00068     static const unsigned ADDR_LEN = BLEProtocol::ADDR_LEN; /**< Length (in octets) of the BLE MAC address. */
00069     typedef BLEProtocol::AddressBytes_t Address_t; /**< 48-bit address, LSB format. @Note: Deprecated. Use BLEProtocol::AddressBytes_t instead. */
00070     typedef BLEProtocol::AddressBytes_t address_t; /**< 48-bit address, LSB format. @Note: Deprecated. Use BLEProtocol::AddressBytes_t instead. */
00071 
00072 public:
00073     enum TimeoutSource_t {
00074         TIMEOUT_SRC_ADVERTISING      = 0x00, /**< Advertising timeout. */
00075         TIMEOUT_SRC_SECURITY_REQUEST = 0x01, /**< Security request timeout. */
00076         TIMEOUT_SRC_SCAN             = 0x02, /**< Scanning timeout. */
00077         TIMEOUT_SRC_CONN             = 0x03, /**< Connection timeout. */
00078     };
00079 
00080     /**
00081      * Enumeration for disconnection reasons. The values for these reasons are
00082      * derived from Nordic's implementation, but the reasons are meant to be
00083      * independent of the transport. If you are returned a reason that is not
00084      * covered by this enumeration, please refer to the underlying
00085      * transport library.
00086      */
00087     enum DisconnectionReason_t {
00088         CONNECTION_TIMEOUT                          = 0x08,
00089         REMOTE_USER_TERMINATED_CONNECTION           = 0x13,
00090         REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES = 0x14,  /**< Remote device terminated connection due to low resources.*/
00091         REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF     = 0x15,  /**< Remote device terminated connection due to power off. */
00092         LOCAL_HOST_TERMINATED_CONNECTION            = 0x16,
00093         CONN_INTERVAL_UNACCEPTABLE                  = 0x3B,
00094     };
00095 
00096     /**
00097      * Enumeration for whitelist advertising policy filter modes. The possible
00098      * filter modes were obtained from the Bluetooth Core Specification
00099      * 4.2 (Vol. 6), Part B, Section 4.3.2.
00100      *
00101      * @experimental
00102      */
00103     enum AdvertisingPolicyMode_t {
00104         ADV_POLICY_IGNORE_WHITELIST = 0,
00105         ADV_POLICY_FILTER_SCAN_REQS = 1,
00106         ADV_POLICY_FILTER_CONN_REQS = 2,
00107         ADV_POLICY_FILTER_ALL_REQS  = 3,
00108     };
00109 
00110     /**
00111      * Enumeration for whitelist scanning policy filter modes. The possible
00112      * filter modes were obtained from the Bluetooth Core Specification
00113      * 4.2 (Vol. 6), Part B, Section 4.3.3.
00114      *
00115      * @experimental
00116      */
00117     enum ScanningPolicyMode_t {
00118         SCAN_POLICY_IGNORE_WHITELIST = 0,
00119         SCAN_POLICY_FILTER_ALL_ADV   = 1,
00120     };
00121 
00122     /**
00123      * Enumeration for the whitelist initiator policy fiter modes. The possible
00124      * filter modes were obtained from the Bluetooth Core Specification
00125      * 4.2 (vol. 6), Part B, Section 4.4.4.
00126      *
00127      * @experimental
00128      */
00129     enum InitiatorPolicyMode_t {
00130         INIT_POLICY_IGNORE_WHITELIST = 0,
00131         INIT_POLICY_FILTER_ALL_ADV   = 1,
00132     };
00133 
00134     /**
00135      * Representation of a Bluetooth Low Enery Whitelist containing addresses.
00136      *
00137      * @experimental
00138      */
00139     struct Whitelist_t {
00140         BLEProtocol::Address_t *addresses;
00141         uint8_t                 size;
00142         uint8_t                 capacity;
00143         uint8_t                 bonds;
00144     };
00145 
00146 
00147     /* Describes the current state of the device (more than one bit can be set). */
00148     struct GapState_t {
00149         unsigned advertising : 1; /**< Peripheral is currently advertising. */
00150         unsigned connected   : 1; /**< Peripheral is connected to a central. */
00151     };
00152 
00153     typedef uint16_t Handle_t; /* Type for connection handle. */
00154 
00155     typedef struct {
00156         uint16_t minConnectionInterval;        /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00157         uint16_t maxConnectionInterval;        /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00158         uint16_t slaveLatency;                 /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/
00159         uint16_t connectionSupervisionTimeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00160     } ConnectionParams_t;
00161 
00162     enum Role_t {
00163         PERIPHERAL  = 0x1, /**< Peripheral Role. */
00164         CENTRAL     = 0x2, /**< Central Role.    */
00165     };
00166 
00167     struct AdvertisementCallbackParams_t {
00168         BLEProtocol::AddressBytes_t              peerAddr;
00169         int8_t                                   rssi;
00170         bool                                     isScanResponse;
00171         GapAdvertisingParams::AdvertisingType_t   type;
00172         uint8_t                                  advertisingDataLen;
00173         const uint8_t                           *advertisingData;
00174     };
00175     typedef FunctionPointerWithContext<const AdvertisementCallbackParams_t *> AdvertisementReportCallback_t;
00176 
00177     struct ConnectionCallbackParams_t {
00178         Handle_t                    handle;
00179         Role_t                      role;
00180         BLEProtocol::AddressType_t  peerAddrType;
00181         BLEProtocol::AddressBytes_t peerAddr;
00182         BLEProtocol::AddressType_t  ownAddrType;
00183         BLEProtocol::AddressBytes_t ownAddr;
00184         const ConnectionParams_t   *connectionParams;
00185 
00186         ConnectionCallbackParams_t(Handle_t                    handleIn,
00187                                    Role_t                      roleIn,
00188                                    BLEProtocol::AddressType_t  peerAddrTypeIn,
00189                                    const uint8_t              *peerAddrIn,
00190                                    BLEProtocol::AddressType_t  ownAddrTypeIn,
00191                                    const uint8_t              *ownAddrIn,
00192                                    const ConnectionParams_t   *connectionParamsIn) :
00193             handle(handleIn),
00194             role(roleIn),
00195             peerAddrType(peerAddrTypeIn),
00196             peerAddr(),
00197             ownAddrType(ownAddrTypeIn),
00198             ownAddr(),
00199             connectionParams(connectionParamsIn) {
00200             memcpy(peerAddr, peerAddrIn, ADDR_LEN);
00201             memcpy(ownAddr, ownAddrIn, ADDR_LEN);
00202         }
00203     };
00204 
00205     struct DisconnectionCallbackParams_t {
00206         Handle_t              handle;
00207         DisconnectionReason_t reason;
00208 
00209         DisconnectionCallbackParams_t(Handle_t              handleIn,
00210                                       DisconnectionReason_t reasonIn) :
00211             handle(handleIn),
00212             reason(reasonIn)
00213         {}
00214     };
00215 
00216     static const uint16_t UNIT_1_25_MS  = 1250; /**< Number of microseconds in 1.25 milliseconds. */
00217     static uint16_t MSEC_TO_GAP_DURATION_UNITS(uint32_t durationInMillis) {
00218         return (durationInMillis * 1000) / UNIT_1_25_MS;
00219     }
00220 
00221     typedef FunctionPointerWithContext<TimeoutSource_t> TimeoutEventCallback_t;
00222     typedef CallChainOfFunctionPointersWithContext<TimeoutSource_t> TimeoutEventCallbackChain_t;
00223 
00224     typedef FunctionPointerWithContext<const ConnectionCallbackParams_t *> ConnectionEventCallback_t;
00225     typedef CallChainOfFunctionPointersWithContext<const ConnectionCallbackParams_t *> ConnectionEventCallbackChain_t;
00226 
00227     typedef FunctionPointerWithContext<const DisconnectionCallbackParams_t*> DisconnectionEventCallback_t;
00228     typedef CallChainOfFunctionPointersWithContext<const DisconnectionCallbackParams_t*> DisconnectionEventCallbackChain_t;
00229 
00230     typedef FunctionPointerWithContext<bool> RadioNotificationEventCallback_t;
00231 
00232     typedef FunctionPointerWithContext<const Gap *> GapShutdownCallback_t;
00233     typedef CallChainOfFunctionPointersWithContext<const Gap *> GapShutdownCallbackChain_t;
00234 
00235     /*
00236      * The following functions are meant to be overridden in the platform-specific sub-class.
00237      */
00238 public:
00239     /**
00240      * Set the BTLE MAC address and type. Please note that the address format is
00241      * least significant byte first (LSB). Please refer to BLEProtocol::AddressBytes_t.
00242      *
00243      * @return BLE_ERROR_NONE on success.
00244      */
00245     virtual ble_error_t setAddress(BLEProtocol::AddressType_t type, const BLEProtocol::AddressBytes_t address) {
00246         /* avoid compiler warnings about unused variables */
00247         (void)type;
00248         (void)address;
00249 
00250         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00251     }
00252 
00253     /**
00254      * Fetch the BTLE MAC address and type.
00255      *
00256      * @return BLE_ERROR_NONE on success.
00257      */
00258     virtual ble_error_t getAddress(BLEProtocol::AddressType_t *typeP, BLEProtocol::AddressBytes_t address) {
00259         /* Avoid compiler warnings about unused variables. */
00260         (void)typeP;
00261         (void)address;
00262 
00263         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00264     }
00265 
00266     /**
00267      * @return Minimum Advertising interval in milliseconds for connectable
00268      *      undirected and connectable directed event types.
00269      */
00270     virtual uint16_t getMinAdvertisingInterval(void) const {
00271         return 0; /* Requesting action from porter(s): override this API if this capability is supported. */
00272     }
00273 
00274     /**
00275      * @return Minimum Advertising interval in milliseconds for scannable
00276      *      undirected and non-connectable undirected event types.
00277      */
00278     virtual uint16_t getMinNonConnectableAdvertisingInterval(void) const {
00279         return 0; /* Requesting action from porter(s): override this API if this capability is supported. */
00280     }
00281 
00282     /**
00283      * @return Maximum Advertising interval in milliseconds.
00284      */
00285     virtual uint16_t getMaxAdvertisingInterval(void) const {
00286         return 0xFFFF; /* Requesting action from porter(s): override this API if this capability is supported. */
00287     }
00288 
00289     virtual ble_error_t stopAdvertising(void) {
00290         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00291     }
00292 
00293     /**
00294      * Stop scanning. The current scanning parameters remain in effect.
00295      *
00296      * @retval BLE_ERROR_NONE if successfully stopped scanning procedure.
00297      */
00298     virtual ble_error_t stopScan() {
00299         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00300     }
00301 
00302     /**
00303      * Create a connection (GAP Link Establishment).
00304      *
00305      * @param peerAddr
00306      *          48-bit address, LSB format.
00307      * @param peerAddrType
00308      *          Address type of the peer.
00309      * @param connectionParams
00310      *         Connection parameters.
00311      * @param scanParams
00312      *          Paramters to be used while scanning for the peer.
00313      * @return  BLE_ERROR_NONE if connection establishment procedure is started
00314      *     successfully. The connectionCallChain (if set) will be invoked upon
00315      *     a connection event.
00316      */
00317     virtual ble_error_t connect(const BLEProtocol::AddressBytes_t  peerAddr,
00318                                 BLEProtocol::AddressType_t         peerAddrType,
00319                                 const ConnectionParams_t          *connectionParams,
00320                                 const GapScanningParams           *scanParams) {
00321         /* Avoid compiler warnings about unused variables. */
00322         (void)peerAddr;
00323         (void)peerAddrType;
00324         (void)connectionParams;
00325         (void)scanParams;
00326 
00327         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00328     }
00329 
00330     /**
00331      * Create a connection (GAP Link Establishment).
00332      *
00333      * \deprecated: This funtion overloads Gap::connect(const BLEProtocol::Address_t  peerAddr,
00334                                                         BLEProtocol::AddressType_t    peerAddrType,
00335                                                         const ConnectionParams_t     *connectionParams,
00336                                                         const GapScanningParams      *scanParams)
00337      *      to maintain backward compatibility for change from Gap::AddressType_t to BLEProtocol::AddressType_t
00338      */
00339     ble_error_t connect(const BLEProtocol::AddressBytes_t  peerAddr,
00340                         DeprecatedAddressType_t            peerAddrType,
00341                         const ConnectionParams_t          *connectionParams,
00342                         const GapScanningParams           *scanParams)
00343     __deprecated_message("Gap::DeprecatedAddressType_t is deprecated, use BLEProtocol::AddressType_t instead") {
00344         return connect(peerAddr, (BLEProtocol::AddressType_t) peerAddrType, connectionParams, scanParams);
00345     }
00346 
00347     /**
00348      * This call initiates the disconnection procedure, and its completion will
00349      * be communicated to the application with an invocation of the
00350      * disconnectionCallback.
00351      *
00352      * @param  reason
00353      *           The reason for disconnection; to be sent back to the peer.
00354      */
00355     virtual ble_error_t disconnect(Handle_t connectionHandle, DisconnectionReason_t reason) {
00356         /* avoid compiler warnings about unused variables */
00357         (void)connectionHandle;
00358         (void)reason;
00359 
00360         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00361     }
00362 
00363     /**
00364      * This call initiates the disconnection procedure, and its completion will
00365      * be communicated to the application with an invocation of the
00366      * disconnectionCallback.
00367      *
00368      * @param  reason
00369      *           The reason for disconnection; to be sent back to the peer.
00370      *
00371      * @note: This version of disconnect() doesn't take a connection handle. It
00372      * works reliably only for stacks that are limited to a single
00373      * connection. This API should be considered *deprecated* in favour of the
00374      * alternative, which takes a connection handle. It will be dropped in the future.
00375      */
00376     virtual ble_error_t disconnect(DisconnectionReason_t reason) {
00377         /* Avoid compiler warnings about unused variables. */
00378         (void)reason;
00379 
00380         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00381     }
00382 
00383     /**
00384      * Get the GAP peripheral preferred connection parameters. These are the
00385      * defaults that the peripheral would like to have in a connection. The
00386      * choice of the connection parameters is eventually up to the central.
00387      *
00388      * @param[out] params
00389      *               The structure where the parameters will be stored. Memory
00390      *               for this is owned by the caller.
00391      *
00392      * @return BLE_ERROR_NONE if the parameters were successfully filled into
00393      * the given structure pointed to by params.
00394      */
00395     virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params) {
00396         /* Avoid compiler warnings about unused variables. */
00397         (void)params;
00398 
00399         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00400     }
00401 
00402     /**
00403      * Set the GAP peripheral preferred connection parameters. These are the
00404      * defaults that the peripheral would like to have in a connection. The
00405      * choice of the connection parameters is eventually up to the central.
00406      *
00407      * @param[in] params
00408      *               The structure containing the desired parameters.
00409      */
00410     virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params) {
00411         /* Avoid compiler warnings about unused variables. */
00412         (void)params;
00413 
00414         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00415     }
00416 
00417     /**
00418      * Update connection parameters.
00419      * In the central role this will initiate a Link Layer connection parameter update procedure.
00420      * In the peripheral role, this will send the corresponding L2CAP request and wait for
00421      * the central to perform the procedure.
00422      *
00423      * @param[in] handle
00424      *              Connection Handle.
00425      * @param[in] params
00426      *              Pointer to desired connection parameters. If NULL is provided on a peripheral role,
00427      *              the parameters in the PPCP characteristic of the GAP service will be used instead.
00428      */
00429     virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params) {
00430         /* avoid compiler warnings about unused variables */
00431         (void)handle;
00432         (void)params;
00433 
00434         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00435     }
00436 
00437     /**
00438      * Set the device name characteristic in the GAP service.
00439      * @param[in] deviceName
00440      *              The new value for the device-name. This is a UTF-8 encoded, <b>NULL-terminated</b> string.
00441      */
00442     virtual ble_error_t setDeviceName(const uint8_t *deviceName) {
00443         /* Avoid compiler warnings about unused variables. */
00444         (void)deviceName;
00445 
00446         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00447     }
00448 
00449     /**
00450      * Get the value of the device name characteristic in the GAP service.
00451      * @param[out]    deviceName
00452      *                  Pointer to an empty buffer where the UTF-8 *non NULL-
00453      *                  terminated* string will be placed. Set this
00454      *                  value to NULL in order to obtain the deviceName-length
00455      *                  from the 'length' parameter.
00456      *
00457      * @param[in/out] lengthP
00458      *                  (on input) Length of the buffer pointed to by deviceName;
00459      *                  (on output) the complete device name length (without the
00460      *                     null terminator).
00461      *
00462      * @note If the device name is longer than the size of the supplied buffer,
00463      *     length will return the complete device name length, and not the
00464      *     number of bytes actually returned in deviceName. The application may
00465      *     use this information to retry with a suitable buffer size.
00466      */
00467     virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) {
00468         /* avoid compiler warnings about unused variables */
00469         (void)deviceName;
00470         (void)lengthP;
00471 
00472         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00473     }
00474 
00475     /**
00476      * Set the appearance characteristic in the GAP service.
00477      * @param[in] appearance
00478      *              The new value for the device-appearance.
00479      */
00480     virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance) {
00481         /* Avoid compiler warnings about unused variables. */
00482         (void)appearance;
00483 
00484         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00485     }
00486 
00487     /**
00488      * Get the appearance characteristic in the GAP service.
00489      * @param[out] appearance
00490      *               The new value for the device-appearance.
00491      */
00492     virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP) {
00493         /* Avoid compiler warnings about unused variables. */
00494         (void)appearanceP;
00495 
00496         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00497     }
00498 
00499     /**
00500      * Set the radio's transmit power.
00501      * @param[in] txPower Radio transmit power in dBm.
00502      */
00503     virtual ble_error_t setTxPower(int8_t txPower) {
00504         /* Avoid compiler warnings about unused variables. */
00505         (void)txPower;
00506 
00507         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00508     }
00509 
00510     /**
00511      * Query the underlying stack for permitted arguments for setTxPower().
00512      *
00513      * @param[out] valueArrayPP
00514      *                 Out parameter to receive the immutable array of Tx values.
00515      * @param[out] countP
00516      *                 Out parameter to receive the array's size.
00517      */
00518     virtual void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP) {
00519         /* Avoid compiler warnings about unused variables. */
00520         (void)valueArrayPP;
00521         (void)countP;
00522 
00523         *countP = 0; /* Requesting action from porter(s): override this API if this capability is supported. */
00524     }
00525 
00526     /**
00527      * @return Maximum size of the whitelist.
00528      *
00529      * @experimental
00530      */
00531     virtual uint8_t getMaxWhitelistSize(void) const
00532     {
00533         return 0;
00534     }
00535 
00536     /**
00537      * Get the internal whitelist to be used by the Link Layer when scanning,
00538      * advertising or initiating a connection depending on the filter policies.
00539      *
00540      * @param[in/out]   whitelist
00541      *                  (on input) whitelist.capacity contains the maximum number
00542      *                  of addresses to be returned.
00543      *                  (on output) The populated whitelist with copies of the
00544      *                  addresses in the implementation's whitelist.
00545      *
00546      * @return BLE_ERROR_NONE if the implementation's whitelist was successfully
00547      *         copied into the supplied reference.
00548      *
00549      * @experimental
00550      */
00551     virtual ble_error_t getWhitelist(Whitelist_t &whitelist) const
00552     {
00553         (void) whitelist;
00554         return BLE_ERROR_NOT_IMPLEMENTED;
00555     }
00556 
00557     /**
00558      * Set the internal whitelist to be used by the Link Layer when scanning,
00559      * advertising or initiating a connection depending on the filter policies.
00560      *
00561      * @param[in]     whitelist
00562      *                  A reference to a whitelist containing the addresses to
00563      *                  be added to the internal whitelist.
00564      *
00565      * @return BLE_ERROR_NONE if the implementation's whitelist was successfully
00566      *         populated with the addresses in the given whitelist.
00567      *
00568      * @note The whitelist must not contain addresses of type @ref
00569      *       BLEProtocol::AddressType_t::RANDOM_PRIVATE_NON_RESOLVABLE, this
00570      *       this will result in a @ref BLE_ERROR_INVALID_PARAM since the
00571      *       remote peer might change its private address at any time and it
00572      *       is not possible to resolve it.
00573      * @note If the input whitelist is larger than @ref getMaxWhitelistSize()
00574      *       the @ref BLE_ERROR_PARAM_OUT_OF_RANGE is returned.
00575      *
00576      * @experimental
00577      */
00578     virtual ble_error_t setWhitelist(const Whitelist_t &whitelist)
00579     {
00580         (void) whitelist;
00581         return BLE_ERROR_NOT_IMPLEMENTED;
00582     }
00583 
00584     /**
00585      * Set the advertising policy filter mode to be used in the next call
00586      * to startAdvertising().
00587      *
00588      * @param[in] mode
00589      *              The new advertising policy filter mode.
00590      *
00591      * @return BLE_ERROR_NONE if the specified policy filter mode was set
00592      *         successfully.
00593      *
00594      * @experimental
00595      */
00596     virtual ble_error_t setAdvertisingPolicyMode(AdvertisingPolicyMode_t mode)
00597     {
00598         (void) mode;
00599         return BLE_ERROR_NOT_IMPLEMENTED;
00600     }
00601 
00602     /**
00603      * Set the scan policy filter mode to be used in the next call
00604      * to startScan().
00605      *
00606      * @param[in] mode
00607      *              The new scan policy filter mode.
00608      *
00609      * @return BLE_ERROR_NONE if the specified policy filter mode was set
00610      *         successfully.
00611      *
00612      * @experimental
00613      */
00614     virtual ble_error_t setScanningPolicyMode(ScanningPolicyMode_t mode)
00615     {
00616         (void) mode;
00617         return BLE_ERROR_NOT_IMPLEMENTED;
00618     }
00619 
00620     /**
00621      * Set the initiator policy filter mode to be used.
00622      *
00623      * @param[in] mode
00624      *              The new initiator policy filter mode.
00625      *
00626      * @return BLE_ERROR_NONE if the specified policy filter mode was set
00627      *         successfully.
00628      *
00629      * @experimental
00630      */
00631     virtual ble_error_t setInitiatorPolicyMode(InitiatorPolicyMode_t mode)
00632     {
00633         (void) mode;
00634         return BLE_ERROR_NOT_IMPLEMENTED;
00635     }
00636 
00637     /**
00638      * Get the advertising policy filter mode that will be used in the next
00639      * call to startAdvertising().
00640      *
00641      * @return The set advertising policy filter mode.
00642      *
00643      * @experimental
00644      */
00645     virtual AdvertisingPolicyMode_t getAdvertisingPolicyMode(void) const
00646     {
00647         return ADV_POLICY_IGNORE_WHITELIST;
00648     }
00649 
00650     /**
00651      * Get the scan policy filter mode that will be used in the next
00652      * call to startScan().
00653      *
00654      * @return The set scan policy filter mode.
00655      *
00656      * @experimental
00657      */
00658     virtual ScanningPolicyMode_t getScanningPolicyMode(void) const
00659     {
00660         return SCAN_POLICY_IGNORE_WHITELIST;
00661     }
00662 
00663     /**
00664      * Get the initiator policy filter mode that will be used.
00665      *
00666      * @return The set scan policy filter mode.
00667      *
00668      * @experimental
00669      */
00670     virtual InitiatorPolicyMode_t getInitiatorPolicyMode(void) const
00671     {
00672         return INIT_POLICY_IGNORE_WHITELIST;
00673     }
00674 
00675 
00676 protected:
00677     /* Override the following in the underlying adaptation layer to provide the functionality of scanning. */
00678     virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams) {
00679         (void)scanningParams;
00680         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
00681     }
00682 
00683     /*
00684      * APIs with non-virtual implementations.
00685      */
00686 public:
00687     /**
00688      * Returns the current GAP state of the device using a bitmask that
00689      * describes whether the device is advertising or connected.
00690      */
00691     GapState_t getState(void) const {
00692         return state;
00693     }
00694 
00695     /**
00696      * Set the GAP advertising mode to use for this device.
00697      */
00698     void setAdvertisingType(GapAdvertisingParams::AdvertisingType_t  advType) {
00699         _advParams.setAdvertisingType(advType);
00700     }
00701 
00702     /**
00703      * @param[in] interval
00704      *              Advertising interval in units of milliseconds. Advertising
00705      *              is disabled if interval is 0. If interval is smaller than
00706      *              the minimum supported value, then the minimum supported
00707      *              value is used instead. This minimum value can be discovered
00708      *              using getMinAdvertisingInterval().
00709      *
00710      *              This field must be set to 0 if connectionMode is equal
00711      *              to ADV_CONNECTABLE_DIRECTED.
00712      *
00713      * @note: Decreasing this value will allow central devices to detect a
00714      * peripheral faster, at the expense of more power being used by the radio
00715      * due to the higher data transmit rate.
00716      *
00717      * @Note: [WARNING] This API previously used 0.625ms as the unit for its
00718      * 'interval' argument. That required an explicit conversion from
00719      * milliseconds using Gap::MSEC_TO_GAP_DURATION_UNITS(). This conversion is
00720      * no longer required as the new units are milliseconds. Any application
00721      * code depending on the old semantics needs to be updated accordingly.
00722      */
00723     void setAdvertisingInterval(uint16_t interval) {
00724         if (interval == 0) {
00725             stopAdvertising();
00726         } else if (interval < getMinAdvertisingInterval()) {
00727             interval = getMinAdvertisingInterval();
00728         }
00729         _advParams.setInterval(interval);
00730     }
00731 
00732     /**
00733      * @param[in] timeout
00734      *              Advertising timeout (in seconds) between 0x1 and 0x3FFF (1
00735      *              and 16383). Use 0 to disable the advertising timeout.
00736      */
00737     void setAdvertisingTimeout(uint16_t timeout) {
00738         _advParams.setTimeout(timeout);
00739     }
00740 
00741     /**
00742      * Start advertising.
00743      */
00744     ble_error_t startAdvertising(void) {
00745         setAdvertisingData(); /* Update the underlying stack. */
00746         return startAdvertising(_advParams);
00747     }
00748 
00749     /**
00750      * Reset any advertising payload prepared from prior calls to
00751      * accumulateAdvertisingPayload(). This automatically propagates the re-
00752      * initialized advertising payload to the underlying stack.
00753      */
00754     void clearAdvertisingPayload(void) {
00755         _advPayload.clear();
00756         setAdvertisingData();
00757     }
00758 
00759     /**
00760      * Accumulate an AD structure in the advertising payload. Please note that
00761      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00762      * as an additional 31 bytes if the advertising payload is too
00763      * small.
00764      *
00765      * @param[in] flags
00766      *              The flags to be added. Please refer to
00767      *              GapAdvertisingData::Flags for valid flags. Multiple
00768      *              flags may be specified in combination.
00769      */
00770     ble_error_t accumulateAdvertisingPayload(uint8_t flags) {
00771         ble_error_t rc;
00772         if ((rc = _advPayload.addFlags(flags)) != BLE_ERROR_NONE) {
00773             return rc;
00774         }
00775 
00776         return setAdvertisingData();
00777     }
00778 
00779     /**
00780      * Accumulate an AD structure in the advertising payload. Please note that
00781      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00782      * as an additional 31 bytes if the advertising payload is too
00783      * small.
00784      *
00785      * @param  app
00786      *         The appearance of the peripheral.
00787      */
00788     ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app) {
00789         setAppearance(app);
00790 
00791         ble_error_t rc;
00792         if ((rc = _advPayload.addAppearance(app)) != BLE_ERROR_NONE) {
00793             return rc;
00794         }
00795 
00796         return setAdvertisingData();
00797     }
00798 
00799     /**
00800      * Accumulate an AD structure in the advertising payload. Please note that
00801      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00802      * as an additional 31 bytes if the advertising payload is too
00803      * small.
00804      *
00805      * @param  power
00806      *         The max transmit power to be used by the controller (in dBm).
00807      */
00808     ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power) {
00809         ble_error_t rc;
00810         if ((rc = _advPayload.addTxPower(power)) != BLE_ERROR_NONE) {
00811             return rc;
00812         }
00813 
00814         return setAdvertisingData();
00815     }
00816 
00817     /**
00818      * Accumulate a variable length byte-stream as an AD structure in the
00819      * advertising payload. Please note that the payload is limited to 31 bytes.
00820      * The SCAN_RESPONSE message may be used as an additional 31 bytes if the
00821      * advertising payload is too small.
00822      *
00823      * @param  type The type describing the variable length data.
00824      * @param  data Data bytes.
00825      * @param  len  Length of data.
00826      *
00827      * @return BLE_ERROR_NONE if the advertisement payload was updated based on
00828      *         matching AD type; otherwise, an appropriate error.
00829      *
00830      * @note When the specified AD type is INCOMPLETE_LIST_16BIT_SERVICE_IDS,
00831      *       COMPLETE_LIST_16BIT_SERVICE_IDS, INCOMPLETE_LIST_32BIT_SERVICE_IDS,
00832      *       COMPLETE_LIST_32BIT_SERVICE_IDS, INCOMPLETE_LIST_128BIT_SERVICE_IDS,
00833      *       COMPLETE_LIST_128BIT_SERVICE_IDS or LIST_128BIT_SOLICITATION_IDS the
00834      *       supplied value is appended to the values previously added to the
00835      *       payload.
00836      */
00837     ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) {
00838         if (type == GapAdvertisingData::COMPLETE_LOCAL_NAME) {
00839             setDeviceName(data);
00840         }
00841 
00842         ble_error_t rc;
00843         if ((rc = _advPayload.addData(type, data, len)) != BLE_ERROR_NONE) {
00844             return rc;
00845         }
00846 
00847         return setAdvertisingData();
00848     }
00849 
00850     /**
00851      * Update a particular ADV field in the advertising payload (based on
00852      * matching type).
00853      *
00854      * @param[in] type  The ADV type field describing the variable length data.
00855      * @param[in] data  Data bytes.
00856      * @param[in] len   Length of data.
00857      *
00858      * @note: If advertisements are enabled, then the update will take effect immediately.
00859      *
00860      * @return BLE_ERROR_NONE if the advertisement payload was updated based on
00861      *         matching AD type; otherwise, an appropriate error.
00862      */
00863     ble_error_t updateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) {
00864         if (type == GapAdvertisingData::COMPLETE_LOCAL_NAME) {
00865             setDeviceName(data);
00866         }
00867 
00868         ble_error_t rc;
00869         if ((rc = _advPayload.updateData(type, data, len)) != BLE_ERROR_NONE) {
00870             return rc;
00871         }
00872 
00873         return setAdvertisingData();
00874     }
00875 
00876     /**
00877      * Set up a particular, user-constructed advertisement payload for the
00878      * underlying stack. It would be uncommon for this API to be used directly;
00879      * there are other APIs to build an advertisement payload (see above).
00880      */
00881     ble_error_t setAdvertisingPayload(const GapAdvertisingData &payload) {
00882         _advPayload = payload;
00883         return setAdvertisingData();
00884     }
00885 
00886     /**
00887      * @return  Read back advertising data. Useful for storing and
00888      *          restoring payload.
00889      */
00890     const GapAdvertisingData &getAdvertisingPayload(void) const {
00891         return _advPayload;
00892     }
00893 
00894     /**
00895      * Accumulate a variable length byte-stream as an AD structure in the
00896      * scanResponse payload.
00897      *
00898      * @param[in] type The type describing the variable length data.
00899      * @param[in] data Data bytes.
00900      * @param[in] len  Length of data.
00901      */
00902     ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len) {
00903         ble_error_t rc;
00904         if ((rc = _scanResponse.addData(type, data, len)) != BLE_ERROR_NONE) {
00905             return rc;
00906         }
00907 
00908         return setAdvertisingData();
00909     }
00910 
00911     /**
00912      * Reset any scan response prepared from prior calls to
00913      * accumulateScanResponse().
00914      *
00915      * Note: This should be followed by a call to setAdvertisingPayload() or
00916      * startAdvertising() before the update takes effect.
00917      */
00918     void clearScanResponse(void) {
00919         _scanResponse.clear();
00920         setAdvertisingData();
00921     }
00922 
00923     /**
00924      * Set up parameters for GAP scanning (observer mode).
00925      * @param[in] interval
00926      *              Scan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00927      * @param[in] window
00928      *              Scan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00929      * @param[in] timeout
00930      *              Scan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables the timeout.
00931      * @param[in] activeScanning
00932      *              Set to True if active-scanning is required. This is used to fetch the
00933      *              scan response from a peer if possible.
00934      *
00935      * The scanning window divided by the interval determines the duty cycle for
00936      * scanning. For example, if the interval is 100ms and the window is 10ms,
00937      * then the controller will scan for 10 percent of the time. It is possible
00938      * to have the interval and window set to the same value. In this case,
00939      * scanning is continuous, with a change of scanning frequency once every
00940      * interval.
00941      *
00942      * Once the scanning parameters have been configured, scanning can be
00943      * enabled by using startScan().
00944      *
00945      * @Note: The scan interval and window are recommendations to the BLE stack.
00946      */
00947     ble_error_t setScanParams(uint16_t interval       = GapScanningParams::SCAN_INTERVAL_MAX,
00948                               uint16_t window         = GapScanningParams::SCAN_WINDOW_MAX,
00949                               uint16_t timeout        = 0,
00950                               bool     activeScanning = false) {
00951         ble_error_t rc;
00952         if (((rc = _scanningParams.setInterval(interval)) == BLE_ERROR_NONE) &&
00953             ((rc = _scanningParams.setWindow(window))     == BLE_ERROR_NONE) &&
00954             ((rc = _scanningParams.setTimeout(timeout))   == BLE_ERROR_NONE)) {
00955             _scanningParams.setActiveScanning(activeScanning);
00956             return BLE_ERROR_NONE;
00957         }
00958 
00959         return rc;
00960     }
00961 
00962     /**
00963      * Set up the scanInterval parameter for GAP scanning (observer mode).
00964      * @param[in] interval
00965      *              Scan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00966      *
00967      * The scanning window divided by the interval determines the duty cycle for
00968      * scanning. For example, if the interval is 100ms and the window is 10ms,
00969      * then the controller will scan for 10 percent of the time. It is possible
00970      * to have the interval and window set to the same value. In this case,
00971      * scanning is continuous, with a change of scanning frequency once every
00972      * interval.
00973      *
00974      * Once the scanning parameters have been configured, scanning can be
00975      * enabled by using startScan().
00976      */
00977     ble_error_t setScanInterval(uint16_t interval) {
00978         return _scanningParams.setInterval(interval);
00979     }
00980 
00981     /**
00982      * Set up the scanWindow parameter for GAP scanning (observer mode).
00983      * @param[in] window
00984      *              Scan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00985      *
00986      * The scanning window divided by the interval determines the duty cycle for
00987      * scanning. For example, if the interval is 100ms and the window is 10ms,
00988      * then the controller will scan for 10 percent of the time. It is possible
00989      * to have the interval and window set to the same value. In this case,
00990      * scanning is continuous, with a change of scanning frequency once every
00991      * interval.
00992      *
00993      * Once the scanning parameters have been configured, scanning can be
00994      * enabled by using startScan().
00995      *
00996      * If scanning is already active, the updated value of scanWindow will be
00997      * propagated to the underlying BLE stack.
00998      */
00999     ble_error_t setScanWindow(uint16_t window) {
01000         ble_error_t rc;
01001         if ((rc = _scanningParams.setWindow(window)) != BLE_ERROR_NONE) {
01002             return rc;
01003         }
01004 
01005         /* If scanning is already active, propagate the new setting to the stack. */
01006         if (scanningActive) {
01007             return startRadioScan(_scanningParams);
01008         }
01009 
01010         return BLE_ERROR_NONE;
01011     }
01012 
01013     /**
01014      * Set up parameters for GAP scanning (observer mode).
01015      * @param[in] timeout
01016      *              Scan timeout (in seconds) between 0x0001 and 0xFFFF; 0x0000 disables the timeout.
01017      *
01018      * Once the scanning parameters have been configured, scanning can be
01019      * enabled by using startScan().
01020      *
01021      * If scanning is already active, the updated value of scanTimeout will be
01022      * propagated to the underlying BLE stack.
01023      */
01024     ble_error_t setScanTimeout(uint16_t timeout) {
01025         ble_error_t rc;
01026         if ((rc = _scanningParams.setTimeout(timeout)) != BLE_ERROR_NONE) {
01027             return rc;
01028         }
01029 
01030         /* If scanning is already active, propagate the new settings to the stack. */
01031         if (scanningActive) {
01032             return startRadioScan(_scanningParams);
01033         }
01034 
01035         return BLE_ERROR_NONE;
01036     }
01037 
01038     /**
01039      * Set up parameters for GAP scanning (observer mode).
01040      * @param[in] activeScanning
01041      *              Set to True if active-scanning is required. This is used to fetch the
01042      *              scan response from a peer if possible.
01043      *
01044      * Once the scanning parameters have been configured, scanning can be
01045      * enabled by using startScan().
01046      *
01047      * If scanning is already in progress, then active-scanning will be enabled
01048      * for the underlying BLE stack.
01049      */
01050     ble_error_t setActiveScanning(bool activeScanning) {
01051         _scanningParams.setActiveScanning(activeScanning);
01052 
01053         /* If scanning is already active, propagate the new settings to the stack. */
01054         if (scanningActive) {
01055             return startRadioScan(_scanningParams);
01056         }
01057 
01058         return BLE_ERROR_NONE;
01059     }
01060 
01061     /**
01062      * Start scanning (Observer Procedure) based on the parameters currently in
01063      * effect.
01064      *
01065      * @param[in] callback
01066      *              The application-specific callback to be invoked upon
01067      *              receiving every advertisement report. This can be passed in
01068      *              as NULL, in which case scanning may not be enabled at all.
01069      */
01070     ble_error_t startScan(void (*callback)(const AdvertisementCallbackParams_t *params)) {
01071         ble_error_t err = BLE_ERROR_NONE;
01072         if (callback) {
01073             if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) {
01074                 scanningActive = true;
01075                 onAdvertisementReport.attach(callback);
01076             }
01077         }
01078 
01079         return err;
01080     }
01081 
01082     /**
01083      * Same as above, but this takes an (object, method) pair for a callback.
01084      */
01085     template<typename T>
01086     ble_error_t startScan(T *object, void (T::*callbackMember)(const AdvertisementCallbackParams_t *params)) {
01087         ble_error_t err = BLE_ERROR_NONE;
01088         if (object && callbackMember) {
01089             if ((err = startRadioScan(_scanningParams)) == BLE_ERROR_NONE) {
01090                 scanningActive = true;
01091                 onAdvertisementReport.attach(object, callbackMember);
01092             }
01093         }
01094 
01095         return err;
01096     }
01097 
01098     /**
01099      * Initialize radio-notification events to be generated from the stack.
01100      * This API doesn't need to be called directly.
01101      *
01102      * Radio Notification is a feature that enables ACTIVE and INACTIVE
01103      * (nACTIVE) signals from the stack that notify the application when the
01104      * radio is in use.
01105      *
01106      * The ACTIVE signal is sent before the radio event starts. The nACTIVE
01107      * signal is sent at the end of the radio event. These signals can be used
01108      * by the application programmer to synchronize application logic with radio
01109      * activity. For example, the ACTIVE signal can be used to shut off external
01110      * devices, to manage peak current drawn during periods when the radio is on,
01111      * or to trigger sensor data collection for transmission in the Radio Event.
01112      *
01113      * @return BLE_ERROR_NONE on successful initialization, otherwise an error code.
01114      */
01115     virtual ble_error_t initRadioNotification(void) {
01116         return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */
01117     }
01118 
01119 private:
01120     ble_error_t setAdvertisingData(void) {
01121         return setAdvertisingData(_advPayload, _scanResponse);
01122     }
01123 
01124 private:
01125     virtual ble_error_t setAdvertisingData(const GapAdvertisingData &advData, const GapAdvertisingData &scanResponse) = 0;
01126     virtual ble_error_t startAdvertising(const GapAdvertisingParams &) = 0;
01127 
01128 public:
01129     /**
01130      * Accessors to read back currently active advertising params.
01131      */
01132     GapAdvertisingParams &getAdvertisingParams(void) {
01133         return _advParams;
01134     }
01135     const GapAdvertisingParams &getAdvertisingParams(void) const {
01136         return _advParams;
01137     }
01138 
01139     /**
01140      * Set up a particular, user-constructed set of advertisement parameters for
01141      * the underlying stack. It would be uncommon for this API to be used
01142      * directly; there are other APIs to tweak advertisement parameters
01143      * individually.
01144      */
01145     void setAdvertisingParams(const GapAdvertisingParams &newParams) {
01146         _advParams = newParams;
01147     }
01148 
01149     /* Event callback handlers. */
01150 public:
01151     /**
01152      * Set up a callback for timeout events. Refer to TimeoutSource_t for
01153      * possible event types.
01154      * @note It is possible to unregister callbacks using onTimeout().detach(callback)
01155      */
01156     void onTimeout(TimeoutEventCallback_t callback) {
01157         timeoutCallbackChain.add(callback);
01158     }
01159 
01160     /**
01161      * @brief provide access to the callchain of timeout event callbacks
01162      * It is possible to register callbacks using onTimeout().add(callback);
01163      * It is possible to unregister callbacks using onTimeout().detach(callback)
01164      * @return The timeout event callbacks chain
01165      */
01166     TimeoutEventCallbackChain_t& onTimeout() {
01167         return timeoutCallbackChain;
01168     }
01169 
01170     /**
01171      * Append to a chain of callbacks to be invoked upon GAP connection.
01172      * @note It is possible to unregister callbacks using onConnection().detach(callback)
01173      */
01174     void onConnection(ConnectionEventCallback_t callback) {connectionCallChain.add(callback);}
01175 
01176     template<typename T>
01177     void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) {connectionCallChain.add(tptr, mptr);}
01178 
01179     /**
01180      * @brief provide access to the callchain of connection event callbacks
01181      * It is possible to register callbacks using onConnection().add(callback);
01182      * It is possible to unregister callbacks using onConnection().detach(callback)
01183      * @return The connection event callbacks chain
01184      */
01185     ConnectionEventCallbackChain_t& onConnection() {
01186         return connectionCallChain;
01187     }
01188 
01189     /**
01190      * Append to a chain of callbacks to be invoked upon GAP disconnection.
01191      * @note It is possible to unregister callbacks using onDisconnection().detach(callback)
01192      */
01193     void onDisconnection(DisconnectionEventCallback_t callback) {disconnectionCallChain.add(callback);}
01194 
01195     template<typename T>
01196     void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) {disconnectionCallChain.add(tptr, mptr);}
01197 
01198     /**
01199      * @brief provide access to the callchain of disconnection event callbacks
01200      * It is possible to register callbacks using onDisconnection().add(callback);
01201      * It is possible to unregister callbacks using onDisconnection().detach(callback)
01202      * @return The disconnection event callbacks chain
01203      */
01204     DisconnectionEventCallbackChain_t& onDisconnection() {
01205         return disconnectionCallChain;
01206     }
01207 
01208     /**
01209      * Set the application callback for radio-notification events.
01210      *
01211      * Radio Notification is a feature that enables ACTIVE and INACTIVE
01212      * (nACTIVE) signals from the stack that notify the application when the
01213      * radio is in use.
01214      *
01215      * The ACTIVE signal is sent before the radio event starts. The nACTIVE
01216      * signal is sent at the end of the radio event. These signals can be used
01217      * by the application programmer to synchronize application logic with radio
01218      * activity. For example, the ACTIVE signal can be used to shut off external
01219      * devices, to manage peak current drawn during periods when the radio is on,
01220      * or to trigger sensor data collection for transmission in the Radio Event.
01221      *
01222      * @param callback
01223      *          The application handler to be invoked in response to a radio
01224      *          ACTIVE/INACTIVE event.
01225      *
01226      * Or in the other version:
01227      *
01228      * @param tptr
01229      *          Pointer to the object of a class defining the member callback
01230      *          function (mptr).
01231      * @param mptr
01232      *          The member callback (within the context of an object) to be
01233      *          invoked in response to a radio ACTIVE/INACTIVE event.
01234      */
01235     void onRadioNotification(void (*callback)(bool param)) {
01236         radioNotificationCallback.attach(callback);
01237     }
01238     template <typename T>
01239     void onRadioNotification(T *tptr, void (T::*mptr)(bool)) {
01240         radioNotificationCallback.attach(tptr, mptr);
01241     }
01242 
01243     /**
01244      * Setup a callback to be invoked to notify the user application that the
01245      * Gap instance is about to shutdown (possibly as a result of a call
01246      * to BLE::shutdown()).
01247      *
01248      * @Note: It is possible to chain together multiple onShutdown callbacks
01249      * (potentially from different modules of an application) to be notified
01250      * before the Gap instance is shutdown.
01251      *
01252      * @Note: It is also possible to set up a callback into a member function of
01253      * some object.
01254      *
01255      * @Note It is possible to unregister a callback using onShutdown().detach(callback)
01256      */
01257     void onShutdown(const GapShutdownCallback_t& callback) {
01258         shutdownCallChain.add(callback);
01259     }
01260     template <typename T>
01261     void onShutdown(T *objPtr, void (T::*memberPtr)(void)) {
01262         shutdownCallChain.add(objPtr, memberPtr);
01263     }
01264 
01265     /**
01266      * @brief provide access to the callchain of shutdown event callbacks
01267      * It is possible to register callbacks using onShutdown().add(callback);
01268      * It is possible to unregister callbacks using onShutdown().detach(callback)
01269      * @return The shutdown event callbacks chain
01270      */
01271     GapShutdownCallbackChain_t& onShutdown() {
01272         return shutdownCallChain;
01273     }
01274 
01275 public:
01276     /**
01277      * Notify all registered onShutdown callbacks that the Gap instance is
01278      * about to be shutdown and clear all Gap state of the
01279      * associated object.
01280      *
01281      * This function is meant to be overridden in the platform-specific
01282      * sub-class. Nevertheless, the sub-class is only expected to reset its
01283      * state and not the data held in Gap members. This shall be achieved by a
01284      * call to Gap::reset() from the sub-class' reset() implementation.
01285      *
01286      * @return BLE_ERROR_NONE on success.
01287      *
01288      * @note: Currently a call to reset() does not reset the advertising and
01289      * scan parameters to default values.
01290      */
01291     virtual ble_error_t reset(void) {
01292         /* Notify that the instance is about to shutdown */
01293         shutdownCallChain.call(this);
01294         shutdownCallChain.clear();
01295 
01296         /* Clear Gap state */
01297         state.advertising = 0;
01298         state.connected   = 0;
01299 
01300         /* Clear scanning state */
01301         scanningActive = false;
01302 
01303         /* Clear advertising and scanning data */
01304         _advPayload.clear();
01305         _scanResponse.clear();
01306 
01307         /* Clear callbacks */
01308         timeoutCallbackChain.clear();
01309         connectionCallChain.clear();
01310         disconnectionCallChain.clear();
01311         radioNotificationCallback = NULL;
01312         onAdvertisementReport     = NULL;
01313 
01314         return BLE_ERROR_NONE;
01315     }
01316 
01317 protected:
01318     Gap() :
01319         _advParams(),
01320         _advPayload(),
01321         _scanningParams(),
01322         _scanResponse(),
01323         state(),
01324         scanningActive(false),
01325         timeoutCallbackChain(),
01326         radioNotificationCallback(),
01327         onAdvertisementReport(),
01328         connectionCallChain(),
01329         disconnectionCallChain() {
01330         _advPayload.clear();
01331         _scanResponse.clear();
01332     }
01333 
01334     /* Entry points for the underlying stack to report events back to the user. */
01335 public:
01336     void processConnectionEvent(Handle_t                           handle,
01337                                 Role_t                             role,
01338                                 BLEProtocol::AddressType_t         peerAddrType,
01339                                 const BLEProtocol::AddressBytes_t  peerAddr,
01340                                 BLEProtocol::AddressType_t         ownAddrType,
01341                                 const BLEProtocol::AddressBytes_t  ownAddr,
01342                                 const ConnectionParams_t          *connectionParams) {
01343         state.connected = 1;
01344         ConnectionCallbackParams_t callbackParams(handle, role, peerAddrType, peerAddr, ownAddrType, ownAddr, connectionParams);
01345         connectionCallChain.call(&callbackParams);
01346     }
01347 
01348     void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) {
01349         state.connected = 0;
01350         DisconnectionCallbackParams_t callbackParams(handle, reason);
01351         disconnectionCallChain.call(&callbackParams);
01352     }
01353 
01354     void processAdvertisementReport(const BLEProtocol::AddressBytes_t        peerAddr,
01355                                     int8_t                                   rssi,
01356                                     bool                                     isScanResponse,
01357                                     GapAdvertisingParams::AdvertisingType_t   type,
01358                                     uint8_t                                  advertisingDataLen,
01359                                     const uint8_t                           *advertisingData) {
01360         AdvertisementCallbackParams_t params;
01361         memcpy(params.peerAddr, peerAddr, ADDR_LEN);
01362         params.rssi               = rssi;
01363         params.isScanResponse     = isScanResponse;
01364         params.type               = type;
01365         params.advertisingDataLen = advertisingDataLen;
01366         params.advertisingData    = advertisingData;
01367         onAdvertisementReport.call(&params);
01368     }
01369 
01370     void processTimeoutEvent(TimeoutSource_t source) {
01371         if (timeoutCallbackChain) {
01372             timeoutCallbackChain(source);
01373         }
01374     }
01375 
01376 protected:
01377     GapAdvertisingParams             _advParams;
01378     GapAdvertisingData               _advPayload;
01379     GapScanningParams                _scanningParams;
01380     GapAdvertisingData               _scanResponse;
01381 
01382     GapState_t                       state;
01383     bool                             scanningActive;
01384 
01385 protected:
01386     TimeoutEventCallbackChain_t       timeoutCallbackChain;
01387     RadioNotificationEventCallback_t  radioNotificationCallback;
01388     AdvertisementReportCallback_t     onAdvertisementReport;
01389     ConnectionEventCallbackChain_t    connectionCallChain;
01390     DisconnectionEventCallbackChain_t disconnectionCallChain;
01391 
01392 private:
01393     GapShutdownCallbackChain_t shutdownCallChain;
01394 
01395 private:
01396     /* Disallow copy and assignment. */
01397     Gap(const Gap &);
01398     Gap& operator=(const Gap &);
01399 };
01400 
01401 #endif // ifndef __GAP_H__