Mistake on this page?
Report an issue in GitHub or email us
BLE.h
1 /* mbed Microcontroller Library
2  * Copyright (c) 2006-2020 ARM Limited
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #ifndef MBED_BLE_H__
20 #define MBED_BLE_H__
21 
22 #include "platform/mbed_error.h"
23 #include "platform/mbed_assert.h"
24 #include "platform/mbed_toolchain.h"
25 
26 #include "ble/Gap.h"
27 #include "ble/GattClient.h"
28 #include "ble/GattServer.h"
29 #include "ble/SecurityManager.h"
30 
31 #include "ble/common/BLERoles.h"
32 #include "ble/common/BLETypes.h"
33 #include "ble/common/blecommon.h"
35 
36 /* Forward declaration for the implementation class */
37 
38 namespace ble {
39 class BLEInstanceBase;
40 
41 /**
42  * @addtogroup ble
43  * @{
44  */
45 
46 /**
47  * Abstract away BLE-capable radio transceivers or SOCs.
48  *
49  * Instances of this class have three responsibilities:
50  * - Initialize the inner BLE subsystem.
51  * - Signal user code that BLE events are available and an API to process them.
52  * - Manage access to the instances abstracting each BLE layer:
53  * + GAP: Handle advertising and scan, as well as connection and
54  * disconnection.
55  * + GATTServer: API to construct and manage a GATT server, which connected peers can
56  * access.
57  * + GATTClient: API to interact with a peer GATT server.
58  * + SecurityManager: API to manage security.
59  *
60  * The user should not create BLE instances directly but rather access to the
61  * singleton(s) holding the BLE interfaces present in the system by using the
62  * static function Instance().
63  *
64  * @code
65  * #include "ble/BLE.h"
66  *
67  * BLE& ble_interface = BLE::Instance();
68  * @endcode
69  *
70  * Next, the signal handling/process mechanism should be set up. By design,
71  * Mbed BLE does not impose to the user an event handling/processing mechanism;
72  * however, it exposes APIs, which allows an application to compose its own:
73  * - onEventsToProcess(), which registers a callback that
74  * the BLE subsystem will call when there is an event ready to be processed.
75  * - processEvents(), which processes all the events present in the BLE subsystem.
76  *
77  * It is common to bind BLE event mechanism with Mbed EventQueue:
78  *
79  * @code
80  * #include <events/mbed_events.h>
81  * #include "ble/BLE.h"
82  *
83  * // declare the event queue, which the whole application will share.
84  * static EventQueue event_queue(4 * EVENTS_EVENT_SIZE);
85  *
86  * // Function invoked when there is a BLE event available.
87  * // Event processing is put into the event queue.
88  * void schedule_ble_processing(BLE::OnEventsToProcessCallbackContext* context) {
89  * event_queue.call(callback(&(context->ble), &BLE::processEvents));
90  * }
91  *
92  * int main()
93  * {
94  * BLE &ble_interface = BLE::Instance();
95  *
96  * // Bind event signaling to schedule_ble_processing
97  * ble_interface.onEventsToProcess(schedule_ble_processing);
98  *
99  * // Launch BLE initialisation
100  *
101  * // Dispatch events in the event queue
102  * event_queue.dispatch_forever();
103  * return 0;
104  * }
105  * @endcode
106  *
107  * Once the event processing mechanism is in place, the Bluetooth subsystem can
108  * be initialized with the init() function. That function accepts in input a
109  * callback, which will be invoked once the initialization process has finished.
110  *
111  * @code
112  * void on_ble_init_complete(BLE::InitializationCompleteCallbackContext *context)
113  * {
114  * BLE& ble_interface = context->ble;
115  * ble_error_t initialization_error = context->error;
116  *
117  * if (initialization_error) {
118  * // handle error
119  * return;
120  * }
121  *
122  * // The BLE interface can be accessed now.
123  * }
124  *
125  * int main() {
126  * BLE &ble_interface = BLE::Instance();
127  * ble_interface.onEventsToProcess(schedule_ble_processing);
128  *
129  * // Initialize the BLE interface
130  * ble_interface.init(on_ble_init_complete);
131  *
132  * event_queue.dispatch_forever();
133  * return 0;
134  * }
135  * @endcode
136  */
137 class BLE {
138 public:
139  /**
140  * Opaque type used to store the ID of a BLE instance.
141  * @deprecated BLE singleton supports one instance. You may create multiple instances by using the constructor.
142  */
143  typedef unsigned InstanceID_t;
144 
145  /**
146  * The value of the BLE::InstanceID_t for the default BLE instance.
147  * @deprecated BLE singleton supports one instance. You may create multiple instances by using the constructor.
148  */
149  static const InstanceID_t DEFAULT_INSTANCE = 0;
150 
151  /**
152  * The number of permitted BLE instances for the application.
153  * @deprecated BLE singleton supports one instance. You may create multiple instances by using the constructor.
154  */
155  static const InstanceID_t NUM_INSTANCES = 1;
156 
157  // Prevent copy construction and copy assignment of BLE.
158  BLE(const BLE &) = delete;
159  BLE &operator=(const BLE &) = delete;
160 
161  /**
162  * Get a reference to the BLE singleton.
163  *
164  * @note Calling Instance() is preferred over constructing a BLE object
165  * directly because it returns a reference to singleton.
166  *
167  * @return A reference to a single object.
168  */
169  static BLE &Instance();
170 
171  /**
172  * Get a reference to the BLE singleton corresponding to a given interface.
173  *
174  * There is a static array of BLE singletons.
175  *
176  * @note Calling Instance() is preferred over constructing a BLE object
177  * directly because it returns references to singletons.
178  *
179  * @param[in] id BLE Instance ID to get.
180  *
181  * @return A reference to a single object.
182  *
183  * @pre id shall be less than NUM_INSTANCES.
184  *
185  */
186  MBED_DEPRECATED_SINCE("mbed-os-6.3.0", "BLE singleton supports one instance. You may create multiple"
187  "instances by using the constructor. Please use BLE::Instance().")
188  static BLE &Instance(InstanceID_t id)
189  {
190  return Instance();
191  }
192 
193  /**
194  * Fetch the ID of a BLE instance.
195  *
196  * @return Instance id of this BLE instance.
197  */
198  MBED_DEPRECATED_SINCE("mbed-os-6.3.0", "BLE singleton supports one instance. You may create multiple"
199  "instances by using the constructor.")
200  InstanceID_t getInstanceID() const
201  {
202  return DEFAULT_INSTANCE;
203  }
204 
205  /**
206  * Events to process event.
207  *
208  * Instances of OnEventsToProcessCallbackContext are passed to the event
209  * handler registered with onEventsToProcess().
210  */
212  /**
213  * The ble instance which have events to process.
214  */
216  };
217 
218  /**
219  * Events to process event handler
220  */
223 
224  /**
225  * Register a callback called when the BLE stack has pending work.
226  *
227  * By registering a callback, application code can know when event processing
228  * has to be scheduled.
229  *
230  * @param on_event_cb Callback invoked when there are new events to process.
231  */
232  void onEventsToProcess(const OnEventsToProcessCallback_t &on_event_cb);
233 
234  /**
235  * Process ALL pending events living in the BLE stack and return once all
236  * events have been consumed.
237  *
238  * @see onEventsToProcess()
239  */
240  void processEvents();
241 
242  /**
243  * Initialization complete event.
244  *
245  * This event is generated at the end of the init() procedure and is passed
246  * to the completion callback passed to init().
247  */
249  /**
250  * Reference to the BLE object that has been initialized
251  */
253 
254  /**
255  * Error status of the initialization.
256  *
257  * That value is set to BLE_ERROR_NONE if initialization completed
258  * successfully or the appropriate error code otherwise.
259  * */
261  };
262 
263  /**
264  * Initialization complete event handler.
265  *
266  * @note There are two versions of init(). In addition to the
267  * function-pointer, init() can also take an <Object, member> tuple as its
268  * callback target. In case of the latter, the following declaration doesn't
269  * apply.
270  */
273  );
274 
275  /**
276  * Initialize the BLE controller/stack.
277  *
278  * init() hands control to the underlying BLE module to accomplish
279  * initialization. This initialization may tacitly depend on other hardware
280  * setup (such as clocks or power-modes) that happens early on during system
281  * startup. It may not be safe to call init() from a global static context
282  * where ordering is compiler-specific and can't be guaranteed - it is safe
283  * to call BLE::init() from within main().
284  *
285  * @param[in] completion_cb A callback for when initialization completes for
286  * a BLE instance. This is an optional parameter; if no callback is set up,
287  * the application can still determine the status of initialization using
288  * BLE::hasInitialized() (see below).
289  *
290  * @return BLE_ERROR_NONE if the initialization procedure started
291  * successfully.
292  *
293  * @note If init() returns BLE_ERROR_NONE, the underlying stack must invoke
294  * the initialization completion callback at some point.
295  *
296  * @note Nearly all BLE APIs would return BLE_ERROR_INITIALIZATION_INCOMPLETE
297  * if used on an instance before the corresponding transport is initialized.
298  *
299  * @note There are two versions of init(). In addition to the
300  * function-pointer, init() can also take an <Object, member> pair as its
301  * callback target.
302  *
303  * @attention This should be called before using anything else in the BLE
304  * API.
305  */
307  {
309  return initImplementation(callback);
310  }
311 
312  /**
313  * Initialize the BLE controller/stack.
314  *
315  * This is an alternate declaration for init(). This one takes an
316  * <Object, member> pair as its callback target.
317  *
318  * @param[in] object Object, which will be used to invoke the completion callback.
319  * @param[in] completion_cb Member function pointer, which will be invoked when
320  * initialization is complete.
321  */
322  template<typename T>
323  ble_error_t init(T *object, void (T::*completion_cb)(InitializationCompleteCallbackContext *context))
324  {
326  return initImplementation(callback);
327  }
328 
329  /**
330  * Indicate if the BLE instance has been initialized.
331  *
332  * @return true if initialization has completed for the underlying BLE
333  * transport.
334  *
335  * @note The application should set up a callback to signal completion of
336  * initialization when using init().
337  */
338  bool hasInitialized() const;
339 
340  /**
341  * Shut down the underlying stack, and reset state of this BLE instance.
342  *
343  * @return BLE_ERROR_NONE if the instance was shut down without error or the
344  * appropriate error code.
345  *
346  * @attention init() must be called afterward to reinstate services and
347  * GAP state. This API offers a way to repopulate the GATT database with new
348  * services and characteristics.
349  */
351 
352  /**
353  * This call allows the application to get the BLE stack version information.
354  *
355  * @return A pointer to a const string representing the version.
356  *
357  * @note The BLE API owns the string returned.
358  */
359  const char *getVersion();
360 
361  /**
362  * Accessor to Gap. All Gap-related functionality requires going through
363  * this accessor.
364  *
365  * @return A reference to a Gap object associated to this BLE instance.
366  */
367  ble::Gap &gap();
368 
369  /**
370  * A const alternative to gap().
371  *
372  * @return A const reference to a Gap object associated to this BLE instance.
373  */
374  const ble::Gap &gap() const;
375 
376 #if BLE_FEATURE_GATT_SERVER
377  /**
378  * Accessor to GattServer. All GattServer related functionality requires
379  * going through this accessor.
380  *
381  * @return A reference to a GattServer object associated to this BLE instance.
382  */
384 
385  /**
386  * A const alternative to gattServer().
387  *
388  * @return A const reference to a GattServer object associated to this BLE
389  * instance.
390  */
391  const ble::GattServer &gattServer() const;
392 #endif // BLE_FEATURE_GATT_SERVER
393 
394 #if BLE_FEATURE_GATT_CLIENT
395  /**
396  * Accessors to GattClient. All GattClient related functionality requires
397  * going through this accessor.
398  *
399  * @return A reference to a GattClient object associated to this BLE instance.
400  */
402 
403  /**
404  * A const alternative to gattClient().
405  *
406  * @return A const reference to a GattClient object associated to this BLE
407  * instance.
408  */
409  const ble::GattClient &gattClient() const;
410 #endif // BLE_FEATURE_GATT_CLIENT
411 
412 #if BLE_FEATURE_SECURITY
413  /**
414  * Accessors to SecurityManager. All SecurityManager-related functionality
415  * requires going through this accessor.
416  *
417  * @return A reference to a SecurityManager object associated to this BLE
418  * instance.
419  */
421 
422  /**
423  * A const alternative to securityManager().
424  *
425  * @return A const reference to a SecurityManager object associated to this
426  * BLE instance.
427  */
428  const ble::SecurityManager &securityManager() const;
429 #endif // BLE_FEATURE_SECURITY
430 
431  /**
432  * Translate error code into a printable string.
433  *
434  * @param[in] error Error code returned by BLE functions.
435  *
436  * @return A pointer to a const string describing the error.
437  */
438  static const char *errorToString(ble_error_t error);
439 
440  /**
441  * This function allows the BLE stack to signal that there is work to do and
442  * event processing should be done (BLE::processEvent()).
443  *
444  * @note This function should be called by the port of BLE_API. It is not
445  * meant to be used by end users.
446  */
447  void signalEventsToProcess();
448 
449 private:
450  friend class ble::BLEInstanceBase;
451 
452  /**
453  * Constructor for a handle to a BLE instance (the BLE stack). BLE handles
454  * are thin wrappers around a transport object (that is, ptr. to
455  * ble::BLEInstanceBase).
456  *
457  * @param[in] transport Ble transport used for the BLE instance.
458  * @note Cordio supports only one instance.
459  */
460  BLE(ble::BLEInstanceBase &transport);
461 
462  /**
463  * Implementation of init() [internal to BLE_API].
464  *
465  * The implementation is separated into a private method because it isn't
466  * suitable to be included in the header.
467  */
468  ble_error_t initImplementation(
470  );
471 
472 private:
473  ble::BLEInstanceBase &transport; /* The device-specific backend */
474  OnEventsToProcessCallback_t whenEventsToProcess;
475  bool event_signaled;
476 };
477 
478 }
479 
480 using ble::BLE;
481 /**
482  * @namespace ble Entry namespace for all BLE API definitions.
483  */
484 
485 /**
486  * @}
487  */
488 
489 #endif /* ifndef MBED_BLE_H__ */
const char * getVersion()
This call allows the application to get the BLE stack version information.
Define device discovery, connection and link management procedures.
Definition: Gap.h:282
MBED_NORETURN void error(const char *format,...) MBED_PRINTF(1
To generate a fatal compile-time error, you can use the pre-processor error directive.
Construct and operates a GATT server.
Definition: GattServer.h:102
void(* InitializationCompleteCallback_t)(InitializationCompleteCallbackContext *context)
Initialization complete event handler.
Definition: BLE.h:271
static BLE & Instance()
Get a reference to the BLE singleton.
static const InstanceID_t NUM_INSTANCES
The number of permitted BLE instances for the application.
Definition: BLE.h:155
FunctionPointerWithContext< OnEventsToProcessCallbackContext * > OnEventsToProcessCallback_t
Events to process event handler.
Definition: BLE.h:222
void processEvents()
Process ALL pending events living in the BLE stack and return once all events have been consumed...
ble_error_t shutdown()
Shut down the underlying stack, and reset state of this BLE instance.
static const InstanceID_t DEFAULT_INSTANCE
The value of the BLE::InstanceID_t for the default BLE instance.
Definition: BLE.h:149
Callback< R(ArgTs...)> callback(R(*func)(ArgTs...)=nullptr) noexcept
Create a callback class with type inferred from the arguments.
Definition: Callback.h:678
bool hasInitialized() const
Indicate if the BLE instance has been initialized.
Initialization complete event.
Definition: BLE.h:248
ble::SecurityManager & securityManager()
Accessors to SecurityManager.
void onEventsToProcess(const OnEventsToProcessCallback_t &on_event_cb)
Register a callback called when the BLE stack has pending work.
ble_error_t init(T *object, void(T::*completion_cb)(InitializationCompleteCallbackContext *context))
Initialize the BLE controller/stack.
Definition: BLE.h:323
InstanceID_t getInstanceID() const
Fetch the ID of a BLE instance.
Definition: BLE.h:200
ble::GattClient & gattClient()
Accessors to GattClient.
ble_error_t init(InitializationCompleteCallback_t completion_cb=nullptr)
Initialize the BLE controller/stack.
Definition: BLE.h:306
Define procedures required for interacting with a distant GATT server.
Definition: GattClient.h:97
static const char * errorToString(ble_error_t error)
Translate error code into a printable string.
void signalEventsToProcess()
This function allows the BLE stack to signal that there is work to do and event processing should be ...
ble::GattServer & gattServer()
Accessor to GattServer.
unsigned InstanceID_t
Opaque type used to store the ID of a BLE instance.
Definition: BLE.h:143
ble_error_t error
Error status of the initialization.
Definition: BLE.h:260
ble::Gap & gap()
Accessor to Gap.
Entry namespace for all BLE API definitions.
BLE & ble
The ble instance which have events to process.
Definition: BLE.h:215
Abstract away BLE-capable radio transceivers or SOCs.
Definition: BLE.h:137
Events to process event.
Definition: BLE.h:211
#define MBED_DEPRECATED_SINCE(D, M)
MBED_DEPRECATED("message string") Mark a function declaration as deprecated, if it used then a warnin...
ble_error_t
Error codes for the BLE API.
Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.