Microbug / BLE_API

Fork of BLE_API by Bluetooth Low Energy

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers BLEDevice.h Source File

BLEDevice.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 __BLE_DEVICE__
00018 #define __BLE_DEVICE__
00019 
00020 #include "blecommon.h"
00021 #include "Gap.h"
00022 #include "GattServer.h"
00023 #include "GapScanningParams.h"
00024 #include "BLEDeviceInstanceBase.h"
00025 
00026 /**
00027  * The base class used to abstract away BLE capable radio transceivers or SOCs,
00028  * to enable this BLE API to work with any radio transparently.
00029  */
00030 class BLEDevice
00031 {
00032 public:
00033     /**
00034      * Initialize the BLE controller. This should be called before using
00035      * anything else in the BLE_API.
00036      */
00037     ble_error_t init();
00038     ble_error_t reset(void);
00039 
00040     /**
00041      * Purge the BLE stack of GATT and GAP state. init() must be called afterwards to re-instate services and GAP state.
00042      */
00043     ble_error_t shutdown(void);
00044 
00045     /* GAP specific APIs */
00046 public:
00047     /**
00048      * Set the BTLE MAC address and type.
00049      * @return BLE_ERROR_NONE on success.
00050      */
00051     ble_error_t setAddress(Gap::addr_type_t type, const Gap::address_t address);
00052 
00053     /**
00054      * Fetch the BTLE MAC address and type.
00055      * @return BLE_ERROR_NONE on success.
00056      */
00057     ble_error_t getAddress(Gap::addr_type_t *typeP, Gap::address_t address);
00058 
00059     /**
00060      * @param[in] advType
00061      *              The GAP advertising mode to use for this device. Valid
00062      *              values are defined in AdvertisingType:
00063      *
00064      *              \par ADV_NON_CONNECTABLE_UNDIRECTED
00065      *              All connections to the peripheral device will be refused.
00066      *
00067      *              \par ADV_CONNECTABLE_DIRECTED
00068      *              Only connections from a pre-defined central device will be
00069      *              accepted.
00070      *
00071      *              \par ADV_CONNECTABLE_UNDIRECTED
00072      *              Any central device can connect to this peripheral.
00073      *
00074      *              \par ADV_SCANNABLE_UNDIRECTED
00075      *              Include support for Scan Response payloads.
00076      *
00077      *              \par
00078      *              See Bluetooth Core Specification 4.0 (Vol. 3), Part C,
00079      *              Section 9.3 and Core Specification 4.0 (Vol. 6), Part B,
00080      *              Section 2.3.1 for further information on GAP connection
00081      *              modes
00082      */
00083     void        setAdvertisingType (GapAdvertisingParams::AdvertisingType);
00084 
00085     /**
00086      * @param[in] interval
00087      *              Advertising interval in units of milliseconds. Advertising
00088      *              is disabled if interval is 0. If interval is smaller than
00089      *              the minimum supported value, then the minimum supported
00090      *              value is used instead.
00091      *
00092      *              \par
00093      *              Decreasing this value will allow central devices to detect
00094      *              your peripheral faster at the expense of more power being
00095      *              used by the radio due to the higher data transmit rate.
00096      *
00097      *              \par
00098      *              This field must be set to 0 if connectionMode is equal
00099      *              to ADV_CONNECTABLE_DIRECTED
00100      *
00101      *              \par
00102      *              See Bluetooth Core Specification, Vol 3., Part C,
00103      *              Appendix A for suggested advertising intervals.
00104      *
00105      * @Note: [WARNING] This API previously used 0.625ms as the unit for its
00106      * 'interval' argument. That required an explicit conversion from
00107      * milliseconds using Gap::MSEC_TO_GAP_DURATION_UNITS(). This conversion is
00108      * no longer required as the new units are milliseconds. Any application
00109      * code depending on the old semantics would need to be updated accordingly.
00110      */
00111     void        setAdvertisingInterval (uint16_t interval);
00112 
00113     /**
00114      * @return Minimum Advertising interval in milliseconds.
00115      */
00116     uint16_t    getMinAdvertisingInterval (void) const;
00117     /**
00118      * @return Minimum Advertising interval in milliseconds for non connectible mode.
00119      */
00120     uint16_t    getMinNonConnectableAdvertisingInterval (void) const;
00121     /**
00122      * @return Maximum Advertising interval in milliseconds.
00123      */
00124     uint16_t    getMaxAdvertisingInterval (void) const;
00125 
00126     /**
00127      * @param[in] timeout
00128      *              Advertising timeout between 0x1 and 0x3FFF (1 and 16383)
00129      *              in seconds.  Enter 0 to disable the advertising timeout.
00130      */
00131     void        setAdvertisingTimeout (uint16_t timeout);
00132 
00133     /**
00134      * Please refer to the APIs above.
00135      */
00136     void        setAdvertisingParams(const GapAdvertisingParams &advParams);
00137 
00138     /**
00139      * This API is typically used as an internal helper to udpate the transport
00140      * backend with advertising data before starting to advertise. It may also
00141      * be explicity used to dynamically reset the accumulated advertising
00142      * payload and scanResponse; to do this, the application can clear and re-
00143      * accumulate a new advertising payload (and scanResponse) before using this
00144      * API.
00145      */
00146     ble_error_t setAdvertisingPayload(void);
00147 
00148     /**
00149      * Reset any advertising payload prepared from prior calls to
00150      * accumulateAdvertisingPayload().
00151      *
00152      * Note: This should be followed by a call to setAdvertisingPayload() or
00153      * startAdvertising() before the update takes effect.
00154      */
00155     void        clearAdvertisingPayload(void);
00156 
00157     /**
00158      * Accumulate an AD structure in the advertising payload. Please note that
00159      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00160      * as an additional 31 bytes if the advertising payload proves to be too
00161      * small.
00162      *
00163      * @param  flags
00164      *         The flags to be added. Multiple flags may be specified in
00165      *         combination.
00166      */
00167     ble_error_t accumulateAdvertisingPayload(uint8_t flags);
00168 
00169     /**
00170      * Accumulate an AD structure in the advertising payload. Please note that
00171      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00172      * as an additional 31 bytes if the advertising payload proves to be too
00173      * small.
00174      *
00175      * @param  app
00176      *         The appearance of the peripheral.
00177      */
00178     ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::Appearance app);
00179 
00180     /**
00181      * Accumulate an AD structure in the advertising payload. Please note that
00182      * the payload is limited to 31 bytes. The SCAN_RESPONSE message may be used
00183      * as an additional 31 bytes if the advertising payload proves to be too
00184      * small.
00185      *
00186      * @param  app
00187      *         The max transmit power to be used by the controller. This is
00188      *         only a hint.
00189      */
00190     ble_error_t accumulateAdvertisingPayloadTxPower(int8_t power);
00191 
00192     /**
00193      * Accumulate a variable length byte-stream as an AD structure in the
00194      * advertising payload. Please note that the payload is limited to 31 bytes.
00195      * The SCAN_RESPONSE message may be used as an additional 31 bytes if the
00196      * advertising payload proves to be too small.
00197      *
00198      * @param  type The type which describes the variable length data.
00199      * @param  data data bytes.
00200      * @param  len  length of data.
00201      */
00202     ble_error_t accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len);
00203 
00204     /**
00205      * Accumulate a variable length byte-stream as an AD structure in the
00206      * scanResponse payload.
00207      *
00208      * @param  type The type which describes the variable length data.
00209      * @param  data data bytes.
00210      * @param  len  length of data.
00211      */
00212     ble_error_t accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len);
00213 
00214     /**
00215      * Reset any scan response prepared from prior calls to
00216      * accumulateScanResponse().
00217      *
00218      * Note: This should be followed by a call to setAdvertisingPayload() or
00219      * startAdvertising() before the update takes effect.
00220      */
00221     void        clearScanResponse(void);
00222 
00223     /**
00224      * Start advertising (GAP Discoverable, Connectable modes, Broadcast
00225      * Procedure).
00226      */
00227     ble_error_t startAdvertising(void);
00228 
00229     /**
00230      * Stop advertising (GAP Discoverable, Connectable modes, Broadcast
00231      * Procedure).
00232      */
00233     ble_error_t stopAdvertising(void);
00234 
00235     /**
00236      * Setup parameters for GAP scanning--i.e. observer mode.
00237      * @param  interval Scan interval (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00238      * @param  window   Scan Window (in milliseconds) [valid values lie between 2.5ms and 10.24s].
00239      * @param  timeout  Scan timeout (in seconds) between 0x0001 and 0xFFFF, 0x0000 disables timeout.
00240      * @param  activeScanning Set to True if active-scanning is required. This is used to fetch the
00241      *                        scan response from a peer if possible.
00242      *
00243      * The scanning window divided by the interval determines the duty cycle for
00244      * scanning. For example, if the interval is 100ms and the window is 10ms,
00245      * then the controller will scan for 10 percent of the time. It is possible
00246      * to have the interval and window set to the same value. In this case,
00247      * scanning is continuous, with a change of scanning frequency once every
00248      * interval.
00249      *
00250      * Once the scanning parameters have been configured, scanning can be
00251      * enabled by using startScan().
00252      *
00253      * @Note: The scan interval and window are recommendations to the BLE stack.
00254      */
00255     ble_error_t setScanParams(uint16_t interval       = GapScanningParams::SCAN_INTERVAL_MAX,
00256                               uint16_t window         = GapScanningParams::SCAN_WINDOW_MAX,
00257                               uint16_t timeout        = 0,
00258                               bool     activeScanning = false);
00259     ble_error_t setScanInterval(uint16_t interval);
00260     ble_error_t setScanWindow  (uint16_t window);
00261     ble_error_t setScanTimeout (uint16_t timeout);
00262     void        setActiveScan  (bool     activeScanning);
00263 
00264     /**
00265      * Start scanning (Observer Procedure) based on the scan-params currently
00266      * in effect.
00267      *
00268      * @param  callback The application callback to be invoked upon receiving
00269      *     every advertisement report. Can be passed in as NULL, in which case
00270      *     scanning may not be enabled at all.
00271      */
00272     ble_error_t startScan(Gap::AdvertisementReportCallback_t callback);
00273 
00274     /**
00275      * Stop scanning. The current scanning parameters remain in effect.
00276      *
00277      * @retval BLE_ERROR_NONE if successfully stopped scanning procedure.
00278      */
00279     ble_error_t stopScan(void);
00280 
00281     /**
00282      * This call initiates the disconnection procedure, and its completion will
00283      * be communicated to the application with an invocation of the
00284      * onDisconnection callback.
00285      *
00286      * @param  reason
00287      *           The reason for disconnection to be sent back to the peer.
00288      */
00289     ble_error_t disconnect(Gap::DisconnectionReason_t reason);
00290 
00291     /* APIs to set GAP callbacks. */
00292     void onTimeout(Gap::EventCallback_t timeoutCallback);
00293 
00294     void onConnection(Gap::ConnectionEventCallback_t connectionCallback);
00295     /**
00296      * Used to setup a callback for GAP disconnection.
00297      */
00298     void onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback);
00299 
00300     /**
00301      * Append to a chain of callbacks to be invoked upon disconnection; these
00302      * callbacks receive no context and are therefore different from the
00303      * onDisconnection callback.
00304      */
00305     template<typename T>
00306     void addToDisconnectionCallChain(T *tptr, void (T::*mptr)(void));
00307 
00308     /**
00309      * Add a callback for the GATT event DATA_SENT (which is triggered when
00310      * updates are sent out by GATT in the form of notifications).
00311      *
00312      * @Note: it is possible to chain together multiple onDataSent callbacks
00313      * (potentially from different modules of an application) to receive updates
00314      * to characteristics.
00315      *
00316      * @Note: it is also possible to setup a callback into a member function of
00317      * some object.
00318      */
00319     void onDataSent(void (*callback)(unsigned count));
00320     template <typename T> void onDataSent(T * objPtr, void (T::*memberPtr)(unsigned count));
00321 
00322     /**
00323      * Setup a callback for when a characteristic has its value updated by a
00324      * client.
00325      *
00326      * @Note: it is possible to chain together multiple onDataWritten callbacks
00327      * (potentially from different modules of an application) to receive updates
00328      * to characteristics. Many services, such as DFU and UART add their own
00329      * onDataWritten callbacks behind the scenes to trap interesting events.
00330      *
00331      * @Note: it is also possible to setup a callback into a member function of
00332      * some object.
00333      */
00334     void onDataWritten(void (*callback)(const GattCharacteristicWriteCBParams *eventDataP));
00335     template <typename T> void onDataWritten(T * objPtr, void (T::*memberPtr)(const GattCharacteristicWriteCBParams *context));
00336 
00337     /**
00338      * Setup a callback for when a characteristic is being read by a client.
00339      *
00340      * @Note: this functionality may not be available on all underlying stacks.
00341      * You could use GattCharacteristic::setReadAuthorizationCallback() as an
00342      * alternative.
00343      *
00344      * @Note: it is possible to chain together multiple onDataRead callbacks
00345      * (potentially from different modules of an application) to receive updates
00346      * to characteristics. Services may add their own onDataRead callbacks
00347      * behind the scenes to trap interesting events.
00348      *
00349      * @Note: it is also possible to setup a callback into a member function of
00350      * some object.
00351      *
00352      * @return BLE_ERROR_NOT_IMPLEMENTED if this functionality isn't available;
00353      *         else BLE_ERROR_NONE.
00354      */
00355     ble_error_t onDataRead(void (*callback)(const GattCharacteristicReadCBParams *eventDataP));
00356     template <typename T> ble_error_t onDataRead(T * objPtr, void (T::*memberPtr)(const GattCharacteristicReadCBParams *context));
00357 
00358     void onUpdatesEnabled(GattServer::EventCallback_t callback);
00359     void onUpdatesDisabled(GattServer::EventCallback_t callback);
00360     void onConfirmationReceived(GattServer::EventCallback_t callback);
00361 
00362     /**
00363      * Radio Notification is a feature that enables ACTIVE and INACTIVE
00364      * (nACTIVE) signals from the stack that notify the application when the
00365      * radio is in use. The signal is sent using software interrupt.
00366      *
00367      * The ACTIVE signal is sent before the Radio Event starts. The nACTIVE
00368      * signal is sent at the end of the Radio Event. These signals can be used
00369      * by the application programmer to synchronize application logic with radio
00370      * activity. For example, the ACTIVE signal can be used to shut off external
00371      * devices to manage peak current drawn during periods when the radio is on,
00372      * or to trigger sensor data collection for transmission in the Radio Event.
00373      *
00374      * @param callback
00375      *          The application handler to be invoked in response to a radio
00376      *          ACTIVE/INACTIVE event.
00377      */
00378     void onRadioNotification(Gap::RadioNotificationEventCallback_t callback);
00379 
00380     /**
00381      * Add a service declaration to the local server ATT table. Also add the
00382      * characteristics contained within.
00383      */
00384     ble_error_t addService(GattService &service);
00385 
00386     /**
00387      * Returns the current GAP state of the device using a bitmask which
00388      * describes whether the device is advertising and/or connected.
00389      */
00390     Gap::GapState_t getGapState(void) const;
00391 
00392     /**
00393      * @param[in/out]  lengthP
00394      *     input:  Length in bytes to be read,
00395      *     output: Total length of attribute value upon successful return.
00396      */
00397     ble_error_t readCharacteristicValue (GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP);
00398     /**
00399      * A version of the same as above with connection handle parameter to allow fetches for connection-specific multivalued attribtues (such as the CCCDs).
00400      */
00401     ble_error_t readCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP);
00402 
00403     /**
00404      * @param  localOnly
00405      *         Only update the characteristic locally regardless of notify/indicate flags in the CCCD.
00406      */
00407     ble_error_t updateCharacteristicValue (GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly = false);
00408     /**
00409      * A version of the same as above with connection handle parameter to allow updates for connection-specific multivalued attribtues (such as the CCCDs).
00410      */
00411     ble_error_t updateCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly = false);
00412 
00413     /**
00414      * Yield control to the BLE stack or to other tasks waiting for events. This
00415      * is a sleep function which will return when there is an application
00416      * specific interrupt, but the MCU might wake up several times before
00417      * returning (to service the stack). This is not always interchangeable with
00418      * WFE().
00419      */
00420     void waitForEvent(void);
00421 
00422     ble_error_t getPreferredConnectionParams(Gap::ConnectionParams_t *params);
00423     ble_error_t setPreferredConnectionParams(const Gap::ConnectionParams_t *params);
00424     ble_error_t updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params);
00425 
00426     /**
00427      * This call allows the application to get the BLE stack version information.
00428      *
00429      * @return  A pointer to a const string representing the version.
00430      *          Note: The string is owned by the BLE_API.
00431      */
00432     const char *getVersion(void);
00433 
00434     /**
00435      * Set the device name characteristic in the GAP service.
00436      * @param  deviceName The new value for the device-name. This is a UTF-8 encoded, <b>NULL-terminated</b> string.
00437      */
00438     ble_error_t setDeviceName(const uint8_t *deviceName);
00439 
00440     /**
00441      * Get the value of the device name characteristic in the GAP service.
00442      * @param[out]    deviceName Pointer to an empty buffer where the UTF-8 *non NULL-
00443      *                           terminated* string will be placed. Set this
00444      *                           value to NULL in order to obtain the deviceName-length
00445      *                           from the 'length' parameter.
00446      *
00447      * @param[in/out] lengthP    (on input) Length of the buffer pointed to by deviceName;
00448      *                           (on output) the complete device name length (without the
00449      *                           null terminator).
00450      *
00451      * @note          If the device name is longer than the size of the supplied buffer,
00452      *                length will return the complete device name length,
00453      *                and not the number of bytes actually returned in deviceName.
00454      *                The application may use this information to retry with a suitable buffer size.
00455      *
00456      * Sample use:
00457      *     uint8_t deviceName[20];
00458      *     unsigned length = sizeof(deviceName);
00459      *     ble.getDeviceName(deviceName, &length);
00460      *     if (length < sizeof(deviceName)) {
00461      *         deviceName[length] = 0;
00462      *     }
00463      *     DEBUG("length: %u, deviceName: %s\r\n", length, deviceName);
00464      */
00465     ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP);
00466 
00467     /**
00468      * Set the appearance characteristic in the GAP service.
00469      * @param[in]  appearance The new value for the device-appearance.
00470      */
00471     ble_error_t setAppearance(uint16_t appearance);
00472 
00473     /**
00474      * Set the appearance characteristic in the GAP service.
00475      * @param[out]  appearance The new value for the device-appearance.
00476      */
00477     ble_error_t getAppearance(uint16_t *appearanceP);
00478 
00479     /**
00480      * Set the radio's transmit power.
00481      * @param[in] txPower Radio transmit power in dBm.
00482      */
00483     ble_error_t setTxPower(int8_t txPower);
00484 
00485     /**
00486      * Query the underlying stack for permitted arguments for setTxPower().
00487      *
00488      * @param[out] valueArrayPP
00489      *                 Out parameter to receive the immutable array of Tx values.
00490      * @param[out] countP
00491      *                 Out parameter to receive the array's size.
00492      */
00493     void getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP);
00494 
00495     /**
00496      * Enable the BLE stack's Security Manager. The Security Manager implements
00497      * the actual cryptographic algorithms and protocol exchanges that allow two
00498      * devices to securely exchange data and privately detect each other.
00499      * Calling this API is a prerequisite for encryption and pairing (bonding).
00500      *
00501      * @param[in]  enableBonding Allow for bonding.
00502      * @param[in]  requireMITM   Require protection for man-in-the-middle attacks.
00503      * @param[in]  iocaps        To specify IO capabilities of this peripheral,
00504      *                           such as availability of a display or keyboard to
00505      *                           support out-of-band exchanges of security data.
00506      * @param[in]  passkey       To specify a static passkey.
00507      *
00508      * @return BLE_ERROR_NONE on success.
00509      */
00510     ble_error_t initializeSecurity(bool                          enableBonding = true,
00511                                    bool                          requireMITM   = true,
00512                                    Gap::SecurityIOCapabilities_t iocaps        = Gap::IO_CAPS_NONE,
00513                                    const Gap::Passkey_t          passkey       = NULL);
00514 
00515     /**
00516      * Setup a callback for when the security setup procedure (key generation
00517      * and exchange) for a link has started. This will be skipped for bonded
00518      * devices. The callback is passed in parameters received from the peer's
00519      * security request: bool allowBonding, bool requireMITM, and
00520      * SecurityIOCapabilities_t.
00521      */
00522     void onSecuritySetupInitiated(Gap::SecuritySetupInitiatedCallback_t callback);
00523 
00524     /**
00525      * Setup a callback for when the security setup procedure (key generation
00526      * and exchange) for a link has completed. This will be skipped for bonded
00527      * devices. The callback is passed in the success/failure status of the
00528      * security setup procedure.
00529      */
00530     void onSecuritySetupCompleted(Gap::SecuritySetupCompletedCallback_t callback);
00531 
00532     /**
00533      * Setup a callback for when a link with the peer is secured. For bonded
00534      * devices, subsequent reconnections with bonded peer will result only in
00535      * this callback when the link is secured and setup procedures will not
00536      * occur unless the bonding information is either lost or deleted on either
00537      * or both sides. The callback is passed in a Gap::SecurityMode_t according
00538      * to the level of security in effect for the secured link.
00539      */
00540     void onLinkSecured(Gap::LinkSecuredCallback_t callback);
00541 
00542     /**
00543      * Setup a callback for successful bonding; i.e. that link-specific security
00544      * context is stored persistently for a peer device.
00545      */
00546     void onSecurityContextStored(Gap::HandleSpecificEvent_t callback);
00547 
00548     /**
00549      * Setup a callback for when the passkey needs to be displayed on a
00550      * peripheral with DISPLAY capability. This happens when security is
00551      * configured to prevent Man-In-The-Middle attacks, and a PIN (or passkey)
00552      * needs to be exchanged between the peers to authenticate the connection
00553      * attempt.
00554      */
00555     void onPasskeyDisplay(Gap::PasskeyDisplayCallback_t callback);
00556 
00557     /**
00558      * Get the security status of a connection.
00559      *
00560      * @param[in]  connectionHandle   Handle to identify the connection.
00561      * @param[out] securityStatusP    security status.
00562      *
00563      * @return BLE_SUCCESS Or appropriate error code indicating reason for failure.
00564      */
00565     ble_error_t getLinkSecurity(Gap::Handle_t connectionHandle, Gap::LinkSecurityStatus_t *securityStatusP);
00566 
00567     /**
00568      * Delete all peer device context and all related bonding information from
00569      * the database within the security manager.
00570      *
00571      * @retval BLE_ERROR_NONE             On success, else an error code indicating reason for failure.
00572      * @retval BLE_ERROR_INVALID_STATE    If the API is called without module initialization and/or
00573      *                                    application registration.
00574      */
00575     ble_error_t purgeAllBondingState(void);
00576 
00577 public:
00578     BLEDevice() : transport(createBLEDeviceInstance()), advParams(), advPayload(), scanResponse(), needToSetAdvPayload(true), scanningParams() {
00579         advPayload.clear();
00580         scanResponse.clear();
00581     }
00582 
00583 private:
00584     BLEDeviceInstanceBase *const transport; /* the device specific backend */
00585 
00586     GapAdvertisingParams advParams;
00587     GapAdvertisingData   advPayload;
00588     GapAdvertisingData   scanResponse;
00589 
00590     /* Accumulation of AD structures in the advertisement payload should
00591      * eventually result in a call to the target's setAdvertisingData() before
00592      * the server begins advertising. This flag marks the status of the pending update.*/
00593     bool                 needToSetAdvPayload;
00594 
00595     GapScanningParams    scanningParams;
00596 };
00597 
00598 /* BLEDevice methods. Most of these simply forward the calls to the underlying
00599  * transport.*/
00600 
00601 inline ble_error_t
00602 BLEDevice::reset(void)
00603 {
00604     return transport->reset();
00605 }
00606 
00607 inline ble_error_t
00608 BLEDevice::shutdown(void)
00609 {
00610     clearAdvertisingPayload();
00611     return transport->shutdown();
00612 }
00613 
00614 inline ble_error_t
00615 BLEDevice::setAddress(Gap::addr_type_t type, const Gap::address_t address)
00616 {
00617     return transport->getGap().setAddress(type, address);
00618 }
00619 
00620 inline ble_error_t
00621 BLEDevice::getAddress(Gap::addr_type_t *typeP, Gap::address_t address)
00622 {
00623     return transport->getGap().getAddress(typeP, address);
00624 }
00625 
00626 inline void
00627 BLEDevice::setAdvertisingType (GapAdvertisingParams::AdvertisingType advType)
00628 {
00629     advParams.setAdvertisingType(advType);
00630 }
00631 
00632 inline void
00633 BLEDevice::setAdvertisingInterval (uint16_t interval)
00634 {
00635     if (interval == 0) {
00636         stopAdvertising();
00637     } else if (interval < getMinAdvertisingInterval ()) {
00638         interval = getMinAdvertisingInterval ();
00639     }
00640     advParams.setInterval(Gap::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(interval));
00641 }
00642 
00643 inline uint16_t
00644 BLEDevice::getMinAdvertisingInterval (void) const {
00645     return transport->getGap().getMinAdvertisingInterval();
00646 }
00647 
00648 inline uint16_t
00649 BLEDevice::getMinNonConnectableAdvertisingInterval (void) const {
00650     return transport->getGap().getMinNonConnectableAdvertisingInterval();
00651 }
00652 
00653 inline uint16_t
00654 BLEDevice::getMaxAdvertisingInterval (void) const {
00655     return transport->getGap().getMaxAdvertisingInterval();
00656 }
00657 
00658 inline void
00659 BLEDevice::setAdvertisingTimeout (uint16_t timeout)
00660 {
00661     advParams.setTimeout(timeout);
00662 }
00663 
00664 inline void
00665 BLEDevice::setAdvertisingParams(const GapAdvertisingParams &newAdvParams)
00666 {
00667     advParams = newAdvParams;
00668 }
00669 
00670 inline void
00671 BLEDevice::clearAdvertisingPayload(void)
00672 {
00673     needToSetAdvPayload = true;
00674     advPayload.clear();
00675 }
00676 
00677 inline ble_error_t
00678 BLEDevice::accumulateAdvertisingPayload(uint8_t flags)
00679 {
00680     needToSetAdvPayload = true;
00681     return advPayload.addFlags(flags);
00682 }
00683 
00684 inline ble_error_t
00685 BLEDevice::accumulateAdvertisingPayload(GapAdvertisingData::Appearance app)
00686 {
00687     needToSetAdvPayload = true;
00688     transport->getGap().setAppearance(app);
00689     return advPayload.addAppearance(app);
00690 }
00691 
00692 inline ble_error_t
00693 BLEDevice::accumulateAdvertisingPayloadTxPower(int8_t txPower)
00694 {
00695     needToSetAdvPayload = true;
00696     return advPayload.addTxPower(txPower);
00697 }
00698 
00699 inline ble_error_t
00700 BLEDevice::accumulateAdvertisingPayload(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len)
00701 {
00702     needToSetAdvPayload = true;
00703     if (type == GapAdvertisingData::COMPLETE_LOCAL_NAME) {
00704         transport->getGap().setDeviceName(data);
00705     }
00706     return advPayload.addData(type, data, len);
00707 }
00708 
00709 inline ble_error_t
00710 BLEDevice::accumulateScanResponse(GapAdvertisingData::DataType type, const uint8_t *data, uint8_t len)
00711 {
00712     needToSetAdvPayload = true;
00713     return scanResponse.addData(type, data, len);
00714 }
00715 
00716 inline void
00717 BLEDevice::clearScanResponse(void)
00718 {
00719     needToSetAdvPayload = true;
00720     scanResponse.clear();
00721 }
00722 
00723 inline ble_error_t
00724 BLEDevice::setAdvertisingPayload(void) {
00725     needToSetAdvPayload = false;
00726     return transport->getGap().setAdvertisingData(advPayload, scanResponse);
00727 }
00728 
00729 inline ble_error_t
00730 BLEDevice::startAdvertising(void)
00731 {
00732     ble_error_t rc;
00733     if ((rc = transport->getGattServer().initializeGATTDatabase()) != BLE_ERROR_NONE) {
00734         return rc;
00735     }
00736     if (needToSetAdvPayload) {
00737         if ((rc = setAdvertisingPayload()) != BLE_ERROR_NONE) {
00738             return rc;
00739         }
00740     }
00741 
00742     return transport->getGap().startAdvertising(advParams);
00743 }
00744 
00745 inline ble_error_t
00746 BLEDevice::stopAdvertising(void)
00747 {
00748     return transport->getGap().stopAdvertising();
00749 }
00750 
00751 inline ble_error_t
00752 BLEDevice::setScanParams(uint16_t interval, uint16_t window, uint16_t timeout, bool activeScanning) {
00753     ble_error_t rc;
00754     if (((rc = scanningParams.setInterval(interval)) == BLE_ERROR_NONE) &&
00755         ((rc = scanningParams.setWindow(window))     == BLE_ERROR_NONE) &&
00756         ((rc = scanningParams.setTimeout(timeout))   == BLE_ERROR_NONE)) {
00757         scanningParams.setActiveScanning(activeScanning);
00758         return BLE_ERROR_NONE;
00759     }
00760 
00761     return rc;
00762 }
00763 
00764 inline ble_error_t
00765 BLEDevice::setScanInterval(uint16_t interval) {
00766     return scanningParams.setInterval(interval);
00767 }
00768 
00769 inline ble_error_t
00770 BLEDevice::setScanWindow(uint16_t window) {
00771 
00772     return scanningParams.setWindow(window);
00773 }
00774 
00775 inline ble_error_t
00776 BLEDevice::setScanTimeout(uint16_t timeout) {
00777     return scanningParams.setTimeout(timeout);
00778 }
00779 
00780 inline void
00781 BLEDevice::setActiveScan(bool activeScanning) {
00782     return scanningParams.setActiveScanning(activeScanning);
00783 }
00784 
00785 inline ble_error_t
00786 BLEDevice::startScan(Gap::AdvertisementReportCallback_t callback) {
00787     return transport->getGap().startScan(scanningParams, callback);
00788 }
00789 
00790 inline ble_error_t
00791 BLEDevice::stopScan(void) {
00792     return transport->getGap().stopScan();
00793 }
00794 
00795 
00796 inline ble_error_t
00797 BLEDevice::disconnect(Gap::DisconnectionReason_t reason)
00798 {
00799     return transport->getGap().disconnect(reason);
00800 }
00801 
00802 inline void
00803 BLEDevice::onTimeout(Gap::EventCallback_t timeoutCallback)
00804 {
00805     transport->getGap().setOnTimeout(timeoutCallback);
00806 }
00807 
00808 inline void
00809 BLEDevice::onConnection(Gap::ConnectionEventCallback_t connectionCallback)
00810 {
00811     transport->getGap().setOnConnection(connectionCallback);
00812 }
00813 
00814 inline void
00815 BLEDevice::onDisconnection(Gap::DisconnectionEventCallback_t disconnectionCallback)
00816 {
00817     transport->getGap().setOnDisconnection(disconnectionCallback);
00818 }
00819 
00820 template<typename T>
00821 inline void
00822 BLEDevice::addToDisconnectionCallChain(T *tptr, void (T::*mptr)(void)) {
00823     transport->getGap().addToDisconnectionCallChain(tptr, mptr);
00824 }
00825 
00826 inline void
00827 BLEDevice::onDataSent(void (*callback)(unsigned count)) {
00828     transport->getGattServer().setOnDataSent(callback);
00829 }
00830 
00831 template <typename T> inline void
00832 BLEDevice::onDataSent(T *objPtr, void (T::*memberPtr)(unsigned count)) {
00833     transport->getGattServer().setOnDataSent(objPtr, memberPtr);
00834 }
00835 
00836 inline void
00837 BLEDevice::onDataWritten(void (*callback)(const GattCharacteristicWriteCBParams *eventDataP)) {
00838     transport->getGattServer().setOnDataWritten(callback);
00839 }
00840 
00841 template <typename T> inline void
00842 BLEDevice::onDataWritten(T *objPtr, void (T::*memberPtr)(const GattCharacteristicWriteCBParams *context)) {
00843     transport->getGattServer().setOnDataWritten(objPtr, memberPtr);
00844 }
00845 
00846 inline ble_error_t
00847 BLEDevice::onDataRead(void (*callback)(const GattCharacteristicReadCBParams *eventDataP)) {
00848     return transport->getGattServer().setOnDataRead(callback);
00849 }
00850 
00851 template <typename T> inline ble_error_t
00852 BLEDevice::onDataRead(T *objPtr, void (T::*memberPtr)(const GattCharacteristicReadCBParams *context)) {
00853     return transport->getGattServer().setOnDataRead(objPtr, memberPtr);
00854 }
00855 
00856 inline void
00857 BLEDevice::onUpdatesEnabled(GattServer::EventCallback_t callback)
00858 {
00859     transport->getGattServer().setOnUpdatesEnabled(callback);
00860 }
00861 
00862 inline void
00863 BLEDevice::onUpdatesDisabled(GattServer::EventCallback_t callback)
00864 {
00865     transport->getGattServer().setOnUpdatesDisabled(callback);
00866 }
00867 
00868 inline void
00869 BLEDevice::onConfirmationReceived(GattServer::EventCallback_t callback)
00870 {
00871     transport->getGattServer().setOnConfirmationReceived(callback);
00872 }
00873 
00874 inline void
00875 BLEDevice::onRadioNotification(Gap::RadioNotificationEventCallback_t callback)
00876 {
00877     transport->getGap().setOnRadioNotification(callback);
00878 }
00879 
00880 inline ble_error_t
00881 BLEDevice::addService(GattService &service)
00882 {
00883     return transport->getGattServer().addService(service);
00884 }
00885 
00886 inline Gap::GapState_t
00887 BLEDevice::getGapState(void) const
00888 {
00889     return transport->getGap().getState();
00890 }
00891 
00892 inline ble_error_t BLEDevice::readCharacteristicValue (GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP)
00893 {
00894     return transport->getGattServer().readValue(attributeHandle, buffer, lengthP);
00895 }
00896 
00897 inline ble_error_t BLEDevice::readCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, uint8_t *buffer, uint16_t *lengthP)
00898 {
00899     return transport->getGattServer().readValue(connectionHandle, attributeHandle, buffer, lengthP);
00900 }
00901 
00902 inline ble_error_t
00903 BLEDevice::updateCharacteristicValue (GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly)
00904 {
00905     return transport->getGattServer().updateValue(attributeHandle, const_cast<uint8_t *>(value), size, localOnly);
00906 }
00907 
00908 inline ble_error_t
00909 BLEDevice::updateCharacteristicValue (Gap::Handle_t connectionHandle, GattAttribute::Handle_t attributeHandle, const uint8_t *value, uint16_t size, bool localOnly)
00910 {
00911     return transport->getGattServer().updateValue(connectionHandle, attributeHandle, const_cast<uint8_t *>(value), size, localOnly);
00912 }
00913 
00914 inline void
00915 BLEDevice::waitForEvent(void)
00916 {
00917     transport->waitForEvent();
00918 }
00919 
00920 inline ble_error_t
00921 BLEDevice::getPreferredConnectionParams(Gap::ConnectionParams_t *params)
00922 {
00923     return transport->getGap().getPreferredConnectionParams(params);
00924 }
00925 
00926 inline ble_error_t
00927 BLEDevice::setPreferredConnectionParams(const Gap::ConnectionParams_t *params)
00928 {
00929     return transport->getGap().setPreferredConnectionParams(params);
00930 }
00931 
00932 inline ble_error_t
00933 BLEDevice::updateConnectionParams(Gap::Handle_t handle, const Gap::ConnectionParams_t *params) {
00934     return transport->getGap().updateConnectionParams(handle, params);
00935 }
00936 
00937 inline const char *
00938 BLEDevice::getVersion(void)
00939 {
00940     return transport->getVersion();
00941 }
00942 
00943 inline ble_error_t
00944 BLEDevice::setDeviceName(const uint8_t *deviceName)
00945 {
00946     return transport->getGap().setDeviceName(deviceName);
00947 }
00948 
00949 inline ble_error_t
00950 BLEDevice::getDeviceName(uint8_t *deviceName, unsigned *lengthP)
00951 {
00952     return transport->getGap().getDeviceName(deviceName, lengthP);
00953 }
00954 
00955 inline ble_error_t
00956 BLEDevice::setAppearance(uint16_t appearance)
00957 {
00958     return transport->getGap().setAppearance(appearance);
00959 }
00960 
00961 inline ble_error_t
00962 BLEDevice::getAppearance(uint16_t *appearanceP)
00963 {
00964     return transport->getGap().getAppearance(appearanceP);
00965 }
00966 
00967 inline ble_error_t
00968 BLEDevice::setTxPower(int8_t txPower)
00969 {
00970     return transport->setTxPower(txPower);
00971 }
00972 
00973 inline void
00974 BLEDevice::getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP)
00975 {
00976     transport->getPermittedTxPowerValues(valueArrayPP, countP);
00977 }
00978 
00979 inline ble_error_t
00980 BLEDevice::initializeSecurity(bool                          enableBonding,
00981                               bool                          requireMITM,
00982                               Gap::SecurityIOCapabilities_t iocaps,
00983                               const Gap::Passkey_t          passkey)
00984 {
00985     return transport->initializeSecurity(enableBonding, requireMITM, iocaps, passkey);
00986 }
00987 
00988 inline void
00989 BLEDevice::onSecuritySetupInitiated(Gap::SecuritySetupInitiatedCallback_t callback)
00990 {
00991     transport->getGap().setOnSecuritySetupInitiated(callback);
00992 }
00993 
00994 inline void
00995 BLEDevice::onSecuritySetupCompleted(Gap::SecuritySetupCompletedCallback_t callback)
00996 {
00997     transport->getGap().setOnSecuritySetupCompleted(callback);
00998 }
00999 
01000 inline void
01001 BLEDevice::onLinkSecured(Gap::LinkSecuredCallback_t callback)
01002 {
01003     transport->getGap().setOnLinkSecured(callback);
01004 }
01005 
01006 inline void
01007 BLEDevice::onSecurityContextStored(Gap::HandleSpecificEvent_t callback)
01008 {
01009     transport->getGap().setOnSecurityContextStored(callback);
01010 }
01011 
01012 inline void
01013 BLEDevice::onPasskeyDisplay(Gap::PasskeyDisplayCallback_t callback)
01014 {
01015     return transport->getGap().setOnPasskeyDisplay(callback);
01016 }
01017 
01018 inline ble_error_t
01019 BLEDevice::getLinkSecurity(Gap::Handle_t connectionHandle, Gap::LinkSecurityStatus_t *securityStatusP)
01020 {
01021     return transport->getGap().getLinkSecurity(connectionHandle, securityStatusP);
01022 }
01023 
01024 inline ble_error_t
01025 BLEDevice::purgeAllBondingState(void)
01026 {
01027     return transport->getGap().purgeAllBondingState();
01028 }
01029 
01030 #endif // ifndef __BLE_DEVICE__