Minor temporary patch to allow DFU packet callback

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 "GapAdvertisingData.h"
00021 #include "GapAdvertisingParams.h"
00022 #include "GapEvents.h"
00023 #include "CallChain.h"
00024 
00025 using namespace mbed;
00026 
00027 class GapScanningParams; /* forward declaration */
00028 
00029 class Gap {
00030 public:
00031     enum AddressType_t {
00032         ADDR_TYPE_PUBLIC = 0,
00033         ADDR_TYPE_RANDOM_STATIC,
00034         ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE,
00035         ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE
00036     };
00037     typedef enum AddressType_t addr_type_t; /* @Note: deprecated. Use AddressType_t instead. */
00038 
00039     static const unsigned ADDR_LEN = 6;
00040     typedef uint8_t Address_t[ADDR_LEN]; /* 48-bit address, LSB format. */
00041     typedef Address_t address_t;         /* @Note: deprecated. Use Address_t instead. */
00042 
00043     enum AdvertisementType_t {
00044         ADV_IND           = 0x00,   /**< Connectable undirected. */
00045         ADV_DIRECT_IND    = 0x01,   /**< Connectable directed. */
00046         ADV_SCAN_IND      = 0x02,   /**< Scannable undirected. */
00047         ADV_NONCONN_IND   = 0x03,   /**< Non connectable undirected. */
00048     };
00049 
00050     /**
00051      * Enumeration for disconnection reasons. The values for these reasons are
00052      * derived from Nordic's implementation; but the reasons are meant to be
00053      * independent of the transport. If you are returned a reason which is not
00054      * covered by this enumeration, then please refer to the underlying
00055      * transport library.
00056      */
00057     enum DisconnectionReason_t {
00058         REMOTE_USER_TERMINATED_CONNECTION = 0x13,
00059         LOCAL_HOST_TERMINATED_CONNECTION  = 0x16,
00060         CONN_INTERVAL_UNACCEPTABLE        = 0x3B,
00061     };
00062 
00063     /* Describes the current state of the device (more than one bit can be set) */
00064     typedef struct GapState_s {
00065         unsigned advertising : 1; /**< peripheral is currently advertising */
00066         unsigned connected   : 1; /**< peripheral is connected to a central */
00067     } GapState_t;
00068 
00069     typedef uint16_t Handle_t;
00070 
00071     typedef struct {
00072         uint16_t minConnectionInterval;      /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00073         uint16_t maxConnectionInterval;      /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00074         uint16_t slaveLatency;               /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/
00075         uint16_t connectionSupervisionTimeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/
00076     } ConnectionParams_t;
00077 
00078     enum SecurityMode_t {
00079         SECURITY_MODE_NO_ACCESS,
00080         SECURITY_MODE_ENCRYPTION_OPEN_LINK, /**< require no protection, open link. */
00081         SECURITY_MODE_ENCRYPTION_NO_MITM,   /**< require encryption, but no MITM protection. */
00082         SECURITY_MODE_ENCRYPTION_WITH_MITM, /**< require encryption and MITM protection. */
00083         SECURITY_MODE_SIGNED_NO_MITM,       /**< require signing or encryption, but no MITM protection. */
00084         SECURITY_MODE_SIGNED_WITH_MITM,     /**< require signing or encryption, and MITM protection. */
00085     };
00086 
00087     /**
00088      * @brief Defines possible security status/states.
00089      *
00090      * @details Defines possible security status/states of a link when requested by getLinkSecurity().
00091      */
00092     enum LinkSecurityStatus_t {
00093         NOT_ENCRYPTED,          /**< The link is not secured. */
00094         ENCRYPTION_IN_PROGRESS, /**< Link security is being established.*/
00095         ENCRYPTED               /**< The link is secure.*/
00096     };
00097 
00098     enum SecurityIOCapabilities_t {
00099       IO_CAPS_DISPLAY_ONLY     = 0x00,   /**< Display Only. */
00100       IO_CAPS_DISPLAY_YESNO    = 0x01,   /**< Display and Yes/No entry. */
00101       IO_CAPS_KEYBOARD_ONLY    = 0x02,   /**< Keyboard Only. */
00102       IO_CAPS_NONE             = 0x03,   /**< No I/O capabilities. */
00103       IO_CAPS_KEYBOARD_DISPLAY = 0x04,   /**< Keyboard and Display. */
00104     };
00105 
00106     enum SecurityCompletionStatus_t {
00107         SEC_STATUS_SUCCESS              = 0x00,  /**< Procedure completed with success. */
00108         SEC_STATUS_TIMEOUT              = 0x01,  /**< Procedure timed out. */
00109         SEC_STATUS_PDU_INVALID          = 0x02,  /**< Invalid PDU received. */
00110         SEC_STATUS_PASSKEY_ENTRY_FAILED = 0x81,  /**< Passkey entry failed (user canceled or other). */
00111         SEC_STATUS_OOB_NOT_AVAILABLE    = 0x82,  /**< Out of Band Key not available. */
00112         SEC_STATUS_AUTH_REQ             = 0x83,  /**< Authentication requirements not met. */
00113         SEC_STATUS_CONFIRM_VALUE        = 0x84,  /**< Confirm value failed. */
00114         SEC_STATUS_PAIRING_NOT_SUPP     = 0x85,  /**< Pairing not supported.  */
00115         SEC_STATUS_ENC_KEY_SIZE         = 0x86,  /**< Encryption key size. */
00116         SEC_STATUS_SMP_CMD_UNSUPPORTED  = 0x87,  /**< Unsupported SMP command. */
00117         SEC_STATUS_UNSPECIFIED          = 0x88,  /**< Unspecified reason. */
00118         SEC_STATUS_REPEATED_ATTEMPTS    = 0x89,  /**< Too little time elapsed since last attempt. */
00119         SEC_STATUS_INVALID_PARAMS       = 0x8A,  /**< Invalid parameters. */
00120     };
00121 
00122     /**
00123      * Declaration of type containing a passkey to be used during pairing. This
00124      * is passed into initializeSecurity() to specify a pre-programmed passkey
00125      * for authentication instead of generating a random one.
00126      */
00127     static const unsigned PASSKEY_LEN = 6;
00128     typedef uint8_t Passkey_t[PASSKEY_LEN];         /**< 6-digit passkey in ASCII ('0'-'9' digits only). */
00129 
00130     static const uint16_t UNIT_1_25_MS  = 1250; /**< Number of microseconds in 1.25 milliseconds. */
00131     static const uint16_t UNIT_0_625_MS = 625;  /**< Number of microseconds in 0.625 milliseconds. */
00132     static uint16_t MSEC_TO_GAP_DURATION_UNITS(uint32_t durationInMillis) {
00133         return (durationInMillis * 1000) / UNIT_1_25_MS;
00134     }
00135     static uint16_t MSEC_TO_ADVERTISEMENT_DURATION_UNITS(uint32_t durationInMillis) {
00136         return (durationInMillis * 1000) / UNIT_0_625_MS;
00137     }
00138     static uint16_t ADVERTISEMENT_DURATION_UNITS_TO_MS(uint16_t gapUnits) {
00139         return (gapUnits * UNIT_0_625_MS) / 1000;
00140     }
00141 
00142     typedef void (*EventCallback_t)(void);
00143     typedef void (*ConnectionEventCallback_t)(Handle_t,
00144                                               addr_type_t peerAddrType, const address_t peerAddr,
00145                                               addr_type_t ownAddrType,  const address_t ownAddr,
00146                                               const ConnectionParams_t *);
00147     typedef void (*HandleSpecificEvent_t)(Handle_t handle);
00148     typedef void (*DisconnectionEventCallback_t)(Handle_t, DisconnectionReason_t);
00149     typedef void (*RadioNotificationEventCallback_t) (bool radio_active); /* gets passed true for ACTIVE; false for INACTIVE. */
00150     typedef void (*SecuritySetupInitiatedCallback_t)(Handle_t, bool allowBonding, bool requireMITM, SecurityIOCapabilities_t iocaps);
00151     typedef void (*SecuritySetupCompletedCallback_t)(Handle_t, SecurityCompletionStatus_t status);
00152     typedef void (*LinkSecuredCallback_t)(Handle_t handle, SecurityMode_t securityMode);
00153     typedef void (*PasskeyDisplayCallback_t)(Handle_t handle, const Passkey_t passkey);
00154 
00155     typedef void (*AdvertisementReportCallback_t)(const address_t      peerAddr,
00156                                                   int8_t               rssi,
00157                                                   bool                 isScanResponse,
00158                                                   AdvertisementType_t  type,
00159                                                   uint8_t              advertisingDataLen,
00160                                                   const uint8_t       *advertisingData);
00161 
00162     friend class BLEDevice;
00163 
00164 private:
00165     /* These functions must be defined in the sub-class */
00166     virtual ble_error_t setAddress(addr_type_t type,   const address_t address)                    = 0;
00167     virtual ble_error_t getAddress(addr_type_t *typeP, address_t address)                          = 0;
00168     virtual ble_error_t setAdvertisingData(const GapAdvertisingData &, const GapAdvertisingData &) = 0;
00169     virtual ble_error_t startAdvertising(const GapAdvertisingParams &)                             = 0;
00170     virtual ble_error_t stopAdvertising(void)                                                      = 0;
00171     virtual ble_error_t startScan(const GapScanningParams &scanningParams, AdvertisementReportCallback_t callback) = 0;
00172     virtual ble_error_t stopScan()                                                                 = 0;
00173     virtual uint16_t    getMinAdvertisingInterval (void) const                                      = 0;
00174     virtual uint16_t    getMinNonConnectableAdvertisingInterval (void) const                        = 0;
00175     virtual uint16_t    getMaxAdvertisingInterval (void) const                                      = 0;
00176     virtual ble_error_t disconnect(DisconnectionReason_t reason)                                   = 0;
00177     virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params)                   = 0;
00178     virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params)             = 0;
00179     virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params)  = 0;
00180 
00181     virtual ble_error_t purgeAllBondingState(void)                                                        = 0;
00182     virtual ble_error_t getLinkSecurity(Handle_t connectionHandle, LinkSecurityStatus_t *securityStatusP) = 0;
00183 
00184     virtual ble_error_t setDeviceName(const uint8_t *deviceName)              = 0;
00185     virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP) = 0;
00186     virtual ble_error_t setAppearance(uint16_t appearance)                    = 0;
00187     virtual ble_error_t getAppearance(uint16_t *appearanceP)                  = 0;
00188 
00189 protected:
00190     /* Event callback handlers */
00191     void setOnTimeout(EventCallback_t callback) {onTimeout = callback;}
00192     void setOnConnection(ConnectionEventCallback_t callback) {onConnection = callback;}
00193 
00194     /**
00195      * Set the application callback for disconnection events.
00196      * @param callback
00197      *        Pointer to the unique callback.
00198      */
00199     void setOnDisconnection(DisconnectionEventCallback_t callback) {onDisconnection = callback;}
00200 
00201     /**
00202      * Set the application callback for radio-notification events.
00203      * @param callback
00204      *          Handler to be executed in response to a radio notification event.
00205      */
00206     virtual void setOnRadioNotification(RadioNotificationEventCallback_t callback) {onRadioNotification = callback;}
00207 
00208     /**
00209      * To indicate that security procedure for link has started.
00210      */
00211     virtual void setOnSecuritySetupInitiated(SecuritySetupInitiatedCallback_t callback) {onSecuritySetupInitiated = callback;}
00212 
00213     /**
00214      * To indicate that security procedure for link has completed.
00215      */
00216     virtual void setOnSecuritySetupCompleted(SecuritySetupCompletedCallback_t callback) {onSecuritySetupCompleted = callback;}
00217 
00218     /**
00219      * To indicate that link with the peer is secured. For bonded devices,
00220      * subsequent re-connections with bonded peer will result only in this callback
00221      * when the link is secured and setup procedures will not occur unless the
00222      * bonding information is either lost or deleted on either or both sides.
00223      */
00224     virtual void setOnLinkSecured(LinkSecuredCallback_t callback) {onLinkSecured = callback;}
00225 
00226     /**
00227      * To indicate that device context is stored persistently.
00228      */
00229     virtual void setOnSecurityContextStored(HandleSpecificEvent_t callback) {onSecurityContextStored = callback;}
00230 
00231     /**
00232      * To set the callback for when the passkey needs to be displayed on a peripheral with DISPLAY capability.
00233      */
00234     virtual void setOnPasskeyDisplay(PasskeyDisplayCallback_t callback) {onPasskeyDisplay = callback;}
00235 
00236     /**
00237      * Append to a chain of callbacks to be invoked upon disconnection; these
00238      * callbacks receive no context and are therefore different from the
00239      * onDisconnection callback.
00240      * @param callback
00241      *        function pointer to be invoked upon disconnection; receives no context.
00242      *
00243      * @note the disconnection CallChain should have been merged with
00244      *     onDisconnctionCallback; but this was not possible because
00245      *     FunctionPointer (which is a building block for CallChain) doesn't
00246      *     accept variadic templates.
00247      */
00248     template<typename T>
00249     void addToDisconnectionCallChain(T *tptr, void (T::*mptr)(void)) {disconnectionCallChain.add(tptr, mptr);}
00250 
00251 private:
00252     GapState_t getState(void) const {
00253         return state;
00254     }
00255 
00256 protected:
00257     Gap() :
00258         state(),
00259         onTimeout(NULL),
00260         onConnection(NULL),
00261         onDisconnection(NULL),
00262         onRadioNotification(),
00263         onSecuritySetupInitiated(),
00264         onSecuritySetupCompleted(),
00265         onLinkSecured(),
00266         onSecurityContextStored(),
00267         onPasskeyDisplay(),
00268         onAdvertisementReport(),
00269         disconnectionCallChain() {
00270         /* empty */
00271     }
00272 
00273 public:
00274     void processConnectionEvent(Handle_t handle, addr_type_t peerAddrType, const address_t peerAddr, addr_type_t ownAddrType, const address_t ownAddr, const ConnectionParams_t *params) {
00275         state.connected = 1;
00276         if (onConnection) {
00277             onConnection(handle, peerAddrType, peerAddr, ownAddrType, ownAddr, params);
00278         }
00279     }
00280 
00281     void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) {
00282         state.connected = 0;
00283         if (onDisconnection) {
00284             onDisconnection(handle, reason);
00285         }
00286         disconnectionCallChain.call();
00287     }
00288 
00289     void processSecuritySetupInitiatedEvent(Handle_t handle, bool allowBonding, bool requireMITM, SecurityIOCapabilities_t iocaps) {
00290         if (onSecuritySetupInitiated) {
00291             onSecuritySetupInitiated(handle, allowBonding, requireMITM, iocaps);
00292         }
00293     }
00294 
00295     void processSecuritySetupCompletedEvent(Handle_t handle, SecurityCompletionStatus_t status) {
00296         if (onSecuritySetupCompleted) {
00297             onSecuritySetupCompleted(handle, status);
00298         }
00299     }
00300 
00301     void processLinkSecuredEvent(Handle_t handle, SecurityMode_t securityMode) {
00302         if (onLinkSecured) {
00303             onLinkSecured(handle, securityMode);
00304         }
00305     }
00306 
00307     void processSecurityContextStoredEvent(Handle_t handle) {
00308         if (onSecurityContextStored) {
00309             onSecurityContextStored(handle);
00310         }
00311     }
00312 
00313     void processPasskeyDisplayEvent(Handle_t handle, const Passkey_t passkey) {
00314         if (onPasskeyDisplay) {
00315             onPasskeyDisplay(handle, passkey);
00316         }
00317     }
00318 
00319     void processAdvertisementReport(const address_t      peerAddr,
00320                                     int8_t               rssi,
00321                                     bool                 isScanResponse,
00322                                     AdvertisementType_t  type,
00323                                     uint8_t              advertisingDataLen,
00324                                     const uint8_t       *advertisingData) {
00325         if (onAdvertisementReport) {
00326             onAdvertisementReport(peerAddr, rssi, isScanResponse, type, advertisingDataLen, advertisingData);
00327         }
00328     }
00329 
00330     void processEvent(GapEvents::gapEvent_e type) {
00331         switch (type) {
00332             case GapEvents::GAP_EVENT_TIMEOUT:
00333                 state.advertising = 0;
00334                 if (onTimeout) {
00335                     onTimeout();
00336                 }
00337                 break;
00338             default:
00339                 break;
00340         }
00341     }
00342 
00343 protected:
00344     GapState_t                       state;
00345 
00346 protected:
00347     EventCallback_t                  onTimeout;
00348     ConnectionEventCallback_t        onConnection;
00349     DisconnectionEventCallback_t     onDisconnection;
00350     RadioNotificationEventCallback_t onRadioNotification;
00351     SecuritySetupInitiatedCallback_t onSecuritySetupInitiated;
00352     SecuritySetupCompletedCallback_t onSecuritySetupCompleted;
00353     LinkSecuredCallback_t            onLinkSecured;
00354     HandleSpecificEvent_t            onSecurityContextStored;
00355     PasskeyDisplayCallback_t         onPasskeyDisplay;
00356     AdvertisementReportCallback_t    onAdvertisementReport;
00357     CallChain                        disconnectionCallChain;
00358 
00359 private:
00360     /* disallow copy and assignment */
00361     Gap(const Gap &);
00362     Gap& operator=(const Gap &);
00363 };
00364 
00365 #endif // ifndef __GAP_H__