From 6f960cbecd95205b2f0dcea4763180608a6d359a Mon Sep 17 00:00:00 2001 From: Marcus Chang Date: Sun, 30 Aug 2015 18:00:19 +0100 Subject: [PATCH 01/16] Gap.h - Added onConnection callback chain simarly to the currently present onDisconnection callback chain. --- ble/Gap.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/ble/Gap.h b/ble/Gap.h index 9540680..6bf5a1b 100644 --- a/ble/Gap.h +++ b/ble/Gap.h @@ -900,6 +900,16 @@ public: */ void onDisconnection(DisconnectionEventCallback_t callback) {disconnectionCallback = callback;} + /** + * Append to a chain of callbacks to be invoked upon connection; these + * callbacks receive no context and are therefore different from the + * connectionCallback callback. + * @param callback + * function pointer to be invoked upon connection; receives no context. + */ + template + void addToConnectionCallChain(T *tptr, void (T::*mptr)(void)) {connectionCallChain.add(tptr, mptr);} + /** * Append to a chain of callbacks to be invoked upon disconnection; these * callbacks receive no context and are therefore different from the @@ -960,6 +970,7 @@ protected: disconnectionCallback(NULL), radioNotificationCallback(), onAdvertisementReport(), + connectionCallChain(), disconnectionCallChain() { _advPayload.clear(); _scanResponse.clear(); @@ -979,6 +990,7 @@ public: ConnectionCallbackParams_t callbackParams(handle, role, peerAddrType, peerAddr, ownAddrType, ownAddr, connectionParams); connectionCallback(&callbackParams); } + connectionCallChain.call(); } void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) { @@ -1026,6 +1038,7 @@ protected: DisconnectionEventCallback_t disconnectionCallback; RadioNotificationEventCallback_t radioNotificationCallback; AdvertisementReportCallback_t onAdvertisementReport; + CallChain connectionCallChain; CallChain disconnectionCallChain; private: From 626c551477602a7d6e982234123ed77000580550 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Mon, 24 Aug 2015 10:03:58 +0100 Subject: [PATCH 02/16] minor improvement to comments for AuthCallbackParams. --- ble/GattCallbackParamTypes.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ble/GattCallbackParamTypes.h b/ble/GattCallbackParamTypes.h index 18784c8..50a1788 100644 --- a/ble/GattCallbackParamTypes.h +++ b/ble/GattCallbackParamTypes.h @@ -65,8 +65,9 @@ struct GattWriteAuthCallbackParams { uint16_t offset; /**< Offset for the write operation. */ uint16_t len; /**< Length of the incoming data. */ const uint8_t *data; /**< Incoming data, variable length. */ - GattAuthCallbackReply_t authorizationReply; /* This is the out parameter which needs to be set to true by the callback if the - * request is to proceed; false otherwise. */ + GattAuthCallbackReply_t authorizationReply; /* This is the out parameter which needs to be set to + * AUTH_CALLBACK_REPLY_SUCCESS by the callback if the + * request is to proceed. */ }; struct GattReadAuthCallbackParams { @@ -75,8 +76,9 @@ struct GattReadAuthCallbackParams { uint16_t offset; /**< Offset for the read operation. */ uint16_t len; /**< Optional: new length of the outgoing data. */ uint8_t *data; /**< Optional: new outgoing data. Leave at NULL if data is unchanged. */ - GattAuthCallbackReply_t authorizationReply; /* This is the out parameter which needs to be set to true by the callback if the - * request is to proceed; false otherwise. */ + GattAuthCallbackReply_t authorizationReply; /* This is the out parameter which needs to be set to + * AUTH_CALLBACK_REPLY_SUCCESS by the callback if the + * request is to proceed. */ }; /* For encapsulating handle-value update events (notifications or indications) generated at the remote server. */ From 3f2f94ec1b88b0c13a1e408659b02500343c2235 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Wed, 26 Aug 2015 13:09:18 +0100 Subject: [PATCH 03/16] update comment header for Gap::updateConnectionParams() --- ble/Gap.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ble/Gap.h b/ble/Gap.h index 6bf5a1b..692bd25 100644 --- a/ble/Gap.h +++ b/ble/Gap.h @@ -301,9 +301,11 @@ public: } /** - * Update connection parameters while in the peripheral role. - * @details In the peripheral role, this will send the corresponding L2CAP request to the connected peer and wait for - * the central to perform the procedure. + * Update connection parameters. + * In the central role this will initiate a Link Layer connection parameter update procedure, + * otherwise in the peripheral role, this will send the corresponding L2CAP request and wait for + * the central to perform the procedure. + * * @param[in] handle * Connection Handle * @param[in] params From 7198945fb54ccb1744c537974498671fe3bb72da Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Wed, 2 Sep 2015 11:04:21 +0100 Subject: [PATCH 04/16] Adding LICENSE at the top level. --- LICENSE | 2 ++ apache-2.0.txt | 13 +++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 LICENSE create mode 100644 apache-2.0.txt diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..546a8e6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,2 @@ +Unless specifically indicated otherwise in a file, files are licensed +under the Apache 2.0 license, as can be found in: apache-2.0.txt diff --git a/apache-2.0.txt b/apache-2.0.txt new file mode 100644 index 0000000..9327527 --- /dev/null +++ b/apache-2.0.txt @@ -0,0 +1,13 @@ +Copyright (c) 2015 ARM Limited + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. From a462757a6ccc6a5f0e2d7b8b44be522b57a844dc Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Mon, 7 Sep 2015 14:10:35 +0100 Subject: [PATCH 05/16] disallow copy constructor and assignment operators for BLE. --- ble/BLE.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ble/BLE.h b/ble/BLE.h index 5484c40..dc1fc37 100644 --- a/ble/BLE.h +++ b/ble/BLE.h @@ -1332,6 +1332,10 @@ public: /* empty */ } +private: + BLE(const BLE&); + BLE &operator=(const BLE &); + private: BLEInstanceBase *const transport; /* the device specific backend */ }; From ad8e92acd540ed95b737fffea1ae249b2be4a326 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Mon, 7 Sep 2015 14:53:28 +0100 Subject: [PATCH 06/16] adding an initial prototype for a yotta-config based initialization for BLE transports --- ble/BLE.h | 44 +++++++++++++++++++++++++----- source/BLE.cpp | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/ble/BLE.h b/ble/BLE.h index c7ca4c3..109bc0f 100644 --- a/ble/BLE.h +++ b/ble/BLE.h @@ -154,6 +154,43 @@ public: transport->waitForEvent(); } +public: + typedef unsigned InstanceID_t; + static const InstanceID_t DEFAULT_INSTANCE = 0; +#ifndef YOTTA_CFG_BLE_INSTANCES_COUNT + static const InstanceID_t NUM_INSTANCES = 1; +#else + static const InstanceID_t NUM_INSTANCES = YOTTA_CFG_BLE_INSTANCES_COUNT; +#endif + + /** + * Get a reference to the BLE singleton corresponding to a given interface. + * There is a static array of BLE singletons. + * + * @Note: Calling Instance() is preferred over constructing a BLE object + * directly, as it returns references to singletons. + * + * @param[in] id + * Instance-ID. This should be less than NUM_INSTANCES in order + * for the returned BLE singleton to be useful. + * + * @return a reference to a single object + */ + static BLE &Instance(InstanceID_t id = DEFAULT_INSTANCE); + + /** + * Constructor for a handle to a BLE instance (i.e. BLE stack). BLE handles + * are thin wrappers around a transport object (i.e. ptr. to + * BLEInstanceBase). + * + * BLE objects are are better created as singletons accessed through the + * Instance() method. If multiple BLE handles are constructed for the same + * interface (using this constructor), they will share the same underlying + * transport object. + */ + BLE(InstanceID_t instanceID = DEFAULT_INSTANCE); + + /* * Deprecation alert! * All of the following are deprecated and may be dropped in a future @@ -1362,17 +1399,12 @@ public: return securityManager().onPasskeyDisplay(callback); } -public: - BLE() : transport(createBLEInstance()) { - /* empty */ - } - private: BLE(const BLE&); BLE &operator=(const BLE &); private: - BLEInstanceBase *const transport; /* the device specific backend */ + BLEInstanceBase *transport; /* the device specific backend */ }; typedef BLE BLEDevice; /* DEPRECATED. This type alias is retained for the sake of compatibility with older diff --git a/source/BLE.cpp b/source/BLE.cpp index 26d9dc7..5ca827d 100644 --- a/source/BLE.cpp +++ b/source/BLE.cpp @@ -36,3 +36,76 @@ BLE::init() return BLE_ERROR_NONE; } + +/** + * BLE::Instance() and BLE constructor rely upon a static array of initializers + * to create actual BLE transport instances. A description of these instances + * and initializers is supposed to be put in some .json file contributing to + * yotta's configuration (typically the target.json). Here's a sample: + * + * "config": { + * ... + * "ble_instances": { + * "count": 1, + * "0" : { + * "initializer" : "createBLEInstance" + * } + * } + * } + * + * The following macros result in translating the above config into a static + * array: instanceConstructors. + */ +#ifdef YOTTA_CFG_BLE_INSTANCES_COUNT +#define CONCATENATE(A, B) A ## B +#define EXPAND(X) X /* this adds a level of indirection needed to allow macro-expansion following a token-paste operation (see use of CONCATENATE() below). */ + +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_1 YOTTA_CFG_BLE_INSTANCES_0_INITIALIZER +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_2 INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_1, YOTTA_CFG_BLE_INSTANCES_1_INITIALIZER +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_3 INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_2, YOTTA_CFG_BLE_INSTANCES_2_INITIALIZER +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_4 INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_3, YOTTA_CFG_BLE_INSTANCES_3_INITIALIZER +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_5 INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_4, YOTTA_CFG_BLE_INSTANCES_4_INITIALIZER +/* ... add more of the above if ever needed */ + +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS(N) EXPAND(CONCATENATE(INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_, N)) +#endif /* YOTTA_CFG_BLE_INSTANCES_COUNT */ + +typedef BLEInstanceBase *(*InstanceConstructor_t)(void); +static const InstanceConstructor_t instanceConstructors[BLE::NUM_INSTANCES] = { +#ifndef YOTTA_CFG_BLE_INSTANCES_COUNT + createBLEInstance +#else + INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS(YOTTA_CFG_BLE_INSTANCES_COUNT) +#endif +}; + +BLE::BLE & +BLE::Instance(InstanceID_t id) +{ + static BLE *singletons[NUM_INSTANCES]; + if (id < NUM_INSTANCES) { + if (singletons[id] == NULL) { + singletons[id] = new BLE(id); /* This object will never be freed. */ + } + + return *singletons[id]; + } + + /* we come here only in the case of a bad interfaceID. */ + static BLE badSingleton(NUM_INSTANCES /* this is a bad index; and will result in a NULL transport. */); + return badSingleton; +} + +BLE::BLE(InstanceID_t instanceID) : transport() +{ + static BLEInstanceBase *transportInstances[NUM_INSTANCES]; + + if (instanceID < NUM_INSTANCES) { + if (!transportInstances[instanceID]) { + transportInstances[instanceID] = instanceConstructors[instanceID](); /* Call the stack's initializer for the transport object. */ + } + transport = transportInstances[instanceID]; + } else { + transport = NULL; + } +} From ce4821076fd9900eaedd84a62860bb99c3d90c77 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Mon, 7 Sep 2015 14:13:09 +0100 Subject: [PATCH 07/16] handle the case of a NULL transport pointer for BLE. --- ble/BLE.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/ble/BLE.h b/ble/BLE.h index dc1fc37..c7ca4c3 100644 --- a/ble/BLE.h +++ b/ble/BLE.h @@ -23,6 +23,8 @@ #include "GattClient.h" #include "BLEInstanceBase.h" +#include "mbed_error.h" + /** * The base class used to abstract away BLE capable radio transceivers or SOCs, * to enable this BLE API to work with any radio transparently. @@ -50,6 +52,9 @@ public: */ ble_error_t shutdown(void) { clearAdvertisingPayload(); + if (!transport) { + error("bad handle to underlying transport"); + } return transport->shutdown(); } @@ -60,6 +65,9 @@ public: * Note: The string is owned by the BLE_API. */ const char *getVersion(void) { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getVersion(); } @@ -68,9 +76,15 @@ public: * going through this accessor. */ const Gap &gap() const { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGap(); } Gap &gap() { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGap(); } @@ -79,9 +93,15 @@ public: * functionality requires going through this accessor. */ const GattServer& gattServer() const { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGattServer(); } GattServer& gattServer() { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGattServer(); } @@ -90,9 +110,15 @@ public: * functionality requires going through this accessor. */ const GattClient& gattClient() const { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGattClient(); } GattClient& gattClient() { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getGattClient(); } @@ -102,9 +128,15 @@ public: * accessor. */ const SecurityManager& securityManager() const { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getSecurityManager(); } SecurityManager& securityManager() { + if (!transport) { + error("bad handle to underlying transport"); + } return transport->getSecurityManager(); } @@ -116,6 +148,9 @@ public: * WFE(). */ void waitForEvent(void) { + if (!transport) { + error("bad handle to underlying transport"); + } transport->waitForEvent(); } From 984266ee8a9d056d4ca10134e007828f10266f04 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Mon, 7 Sep 2015 15:24:28 +0100 Subject: [PATCH 08/16] oops. typo. --- source/BLE.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/BLE.cpp b/source/BLE.cpp index 5ca827d..7f6c5f0 100644 --- a/source/BLE.cpp +++ b/source/BLE.cpp @@ -79,7 +79,7 @@ static const InstanceConstructor_t instanceConstructors[BLE::NUM_INSTANCES] = { #endif }; -BLE::BLE & +BLE & BLE::Instance(InstanceID_t id) { static BLE *singletons[NUM_INSTANCES]; From cc3db8500cb84a0aa9bdf9074d6b59c4880ac4bb Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Tue, 8 Sep 2015 10:11:39 +0100 Subject: [PATCH 09/16] minor improvement to comment header for GattServer::onDataRead() --- ble/GattServer.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ble/GattServer.h b/ble/GattServer.h index 0f36718..7821798 100644 --- a/ble/GattServer.h +++ b/ble/GattServer.h @@ -271,7 +271,7 @@ public: * * @Note: this functionality may not be available on all underlying stacks. * You could use GattCharacteristic::setReadAuthorizationCallback() as an - * alternative. + * alternative. Refer to isOnDataReadAvailable(). * * @Note: it is possible to chain together multiple onDataRead callbacks * (potentially from different modules of an application) to receive updates From c6dcbfc670ee8c1f781ef7e61bd153dde5d91222 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Tue, 8 Sep 2015 10:33:57 +0100 Subject: [PATCH 10/16] allow createBLEInstance to be overridable. --- source/BLE.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/source/BLE.cpp b/source/BLE.cpp index 7f6c5f0..22bba15 100644 --- a/source/BLE.cpp +++ b/source/BLE.cpp @@ -68,12 +68,19 @@ BLE::init() /* ... add more of the above if ever needed */ #define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS(N) EXPAND(CONCATENATE(INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS_, N)) +#elif !defined(INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS) +/* + * The following applies when building without yotta. By default BLE_API provides + * a trivial initializer list containing a single constructor: createBLEInstance. + * This may be overridden. + */ +#define INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS createBLEInstance #endif /* YOTTA_CFG_BLE_INSTANCES_COUNT */ typedef BLEInstanceBase *(*InstanceConstructor_t)(void); static const InstanceConstructor_t instanceConstructors[BLE::NUM_INSTANCES] = { #ifndef YOTTA_CFG_BLE_INSTANCES_COUNT - createBLEInstance + INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS #else INITIALIZER_LIST_FOR_INSTANCE_CONSTRUCTORS(YOTTA_CFG_BLE_INSTANCES_COUNT) #endif From 2c421951cbe30fff08b597f0319ea69673eb1506 Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Tue, 8 Sep 2015 10:35:13 +0100 Subject: [PATCH 11/16] minor improvement to a comment header. --- source/BLE.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/source/BLE.cpp b/source/BLE.cpp index 22bba15..28bfd0b 100644 --- a/source/BLE.cpp +++ b/source/BLE.cpp @@ -41,7 +41,8 @@ BLE::init() * BLE::Instance() and BLE constructor rely upon a static array of initializers * to create actual BLE transport instances. A description of these instances * and initializers is supposed to be put in some .json file contributing to - * yotta's configuration (typically the target.json). Here's a sample: + * yotta's configuration (typically in the target definition described by + * target.json). Here's a sample: * * "config": { * ... @@ -51,6 +52,7 @@ BLE::init() * "initializer" : "createBLEInstance" * } * } + * ... * } * * The following macros result in translating the above config into a static From dd032631d78dfa081b7ef0204f92800f49e07df1 Mon Sep 17 00:00:00 2001 From: Marcus Chang Date: Tue, 8 Sep 2015 15:59:34 +0100 Subject: [PATCH 12/16] Changed onConnection and onDisconnection to accept object/methods and merged them with the addTo-callchain. All calls to onConnection and onDisconnection will now be added to a call chain. --- ble/BLE.h | 16 +++---------- ble/Gap.h | 70 +++++++++++++++++++++---------------------------------- 2 files changed, 30 insertions(+), 56 deletions(-) diff --git a/ble/BLE.h b/ble/BLE.h index 109bc0f..d95471c 100644 --- a/ble/BLE.h +++ b/ble/BLE.h @@ -1151,7 +1151,7 @@ public: } /** - * Used to setup a callback for GAP disconnection. + * Append to a chain of callbacks to be invoked upon GAP disconnection. * * @note: This API is now *deprecated* and will be dropped in the future. * You should use the parallel API from Gap directly. A former call @@ -1162,19 +1162,9 @@ public: gap().onDisconnection(disconnectionCallback); } - /** - * Append to a chain of callbacks to be invoked upon disconnection; these - * callbacks receive no context and are therefore different from the - * onDisconnection callback. - * - * @note: This API is now *deprecated* and will be dropped in the future. - * You should use the parallel API from Gap directly. A former call - * to ble.addToDisconnectionCallchain(...) should be replaced with - * ble.gap().addToDisconnectionCallchain(...). - */ template - void addToDisconnectionCallChain(T *tptr, void (T::*mptr)(void)) { - gap().addToDisconnectionCallChain(tptr, mptr); + void onDisconnection(T *tptr, void (T::*mptr)(const Gap::DisconnectionCallbackParams_t*)) { + gap().onDisconnection(tptr, mptr); } /** diff --git a/ble/Gap.h b/ble/Gap.h index 692bd25..06793e9 100644 --- a/ble/Gap.h +++ b/ble/Gap.h @@ -21,11 +21,9 @@ #include "GapAdvertisingParams.h" #include "GapScanningParams.h" #include "GapEvents.h" -#include "CallChain.h" +#include "CallChainOfFunctionPointersWithContext.h" #include "FunctionPointerWithContext.h" -using namespace mbed; - /* Forward declarations for classes which will only be used for pointers or references in the following. */ class GapAdvertisingParams; class GapScanningParams; @@ -126,6 +124,17 @@ public: } }; + struct DisconnectionCallbackParams_t { + Handle_t handle; + DisconnectionReason_t reason; + + DisconnectionCallbackParams_t(Handle_t handleIn, + DisconnectionReason_t reasonIn) : + handle(handleIn), + reason(reasonIn) + {} + }; + static const uint16_t UNIT_1_25_MS = 1250; /**< Number of microseconds in 1.25 milliseconds. */ static uint16_t MSEC_TO_GAP_DURATION_UNITS(uint32_t durationInMillis) { return (durationInMillis * 1000) / UNIT_1_25_MS; @@ -134,7 +143,7 @@ public: typedef void (*TimeoutEventCallback_t)(TimeoutSource_t source); typedef void (*ConnectionEventCallback_t)(const ConnectionCallbackParams_t *params); - typedef void (*DisconnectionEventCallback_t)(Handle_t, DisconnectionReason_t); + typedef void (*DisconnectionEventCallback_t)(const DisconnectionCallbackParams_t *params); typedef FunctionPointerWithContext RadioNotificationEventCallback_t; /* @@ -214,7 +223,7 @@ public: * @param scanParams * Paramters to be used while scanning for the peer. * @return BLE_ERROR_NONE if connection establishment procedure is started - * successfully. The connectionCallback (if set) will be invoked upon + * successfully. The connectionCallChain (if set) will be invoked upon * a connection event. */ virtual ble_error_t connect(const Address_t peerAddr, @@ -891,36 +900,20 @@ public: void onTimeout(TimeoutEventCallback_t callback) {timeoutCallback = callback;} /** - * Setup a callback for connection events. Refer to ConnectionEventCallback_t. + * Append to a chain of callbacks to be invoked upon GAP connection. */ - void onConnection(ConnectionEventCallback_t callback) {connectionCallback = callback;} + void onConnection(ConnectionEventCallback_t callback) {connectionCallChain.add(callback);} - /** - * Set the application callback for disconnection events. - * @param callback - * Pointer to the unique callback. - */ - void onDisconnection(DisconnectionEventCallback_t callback) {disconnectionCallback = callback;} - - /** - * Append to a chain of callbacks to be invoked upon connection; these - * callbacks receive no context and are therefore different from the - * connectionCallback callback. - * @param callback - * function pointer to be invoked upon connection; receives no context. - */ template - void addToConnectionCallChain(T *tptr, void (T::*mptr)(void)) {connectionCallChain.add(tptr, mptr);} + void onConnection(T *tptr, void (T::*mptr)(const ConnectionCallbackParams_t*)) {connectionCallChain.add(tptr, mptr);} /** - * Append to a chain of callbacks to be invoked upon disconnection; these - * callbacks receive no context and are therefore different from the - * disconnectionCallback callback. - * @param callback - * function pointer to be invoked upon disconnection; receives no context. + * Append to a chain of callbacks to be invoked upon GAP disconnection. */ + void onDisconnection(DisconnectionEventCallback_t callback) {disconnectionCallChain.add(callback);} + template - void addToDisconnectionCallChain(T *tptr, void (T::*mptr)(void)) {disconnectionCallChain.add(tptr, mptr);} + void onDisconnection(T *tptr, void (T::*mptr)(const DisconnectionCallbackParams_t*)) {disconnectionCallChain.add(tptr, mptr);} /** * Set the application callback for radio-notification events. @@ -968,8 +961,6 @@ protected: state(), scanningActive(false), timeoutCallback(NULL), - connectionCallback(NULL), - disconnectionCallback(NULL), radioNotificationCallback(), onAdvertisementReport(), connectionCallChain(), @@ -988,19 +979,14 @@ public: const Address_t ownAddr, const ConnectionParams_t *connectionParams) { state.connected = 1; - if (connectionCallback) { - ConnectionCallbackParams_t callbackParams(handle, role, peerAddrType, peerAddr, ownAddrType, ownAddr, connectionParams); - connectionCallback(&callbackParams); - } - connectionCallChain.call(); + ConnectionCallbackParams_t callbackParams(handle, role, peerAddrType, peerAddr, ownAddrType, ownAddr, connectionParams); + connectionCallChain.call(&callbackParams); } void processDisconnectionEvent(Handle_t handle, DisconnectionReason_t reason) { state.connected = 0; - if (disconnectionCallback) { - disconnectionCallback(handle, reason); - } - disconnectionCallChain.call(); + DisconnectionCallbackParams_t callbackParams(handle, reason); + disconnectionCallChain.call(&callbackParams); } void processAdvertisementReport(const Address_t peerAddr, @@ -1036,12 +1022,10 @@ protected: protected: TimeoutEventCallback_t timeoutCallback; - ConnectionEventCallback_t connectionCallback; - DisconnectionEventCallback_t disconnectionCallback; RadioNotificationEventCallback_t radioNotificationCallback; AdvertisementReportCallback_t onAdvertisementReport; - CallChain connectionCallChain; - CallChain disconnectionCallChain; + CallChainOfFunctionPointersWithContext connectionCallChain; + CallChainOfFunctionPointersWithContext disconnectionCallChain; private: /* disallow copy and assignment */ From 1811f21091c869003d9c0f8696f455d89c0c2c3a Mon Sep 17 00:00:00 2001 From: Austin Blackstone Date: Fri, 25 Sep 2015 16:17:14 -0500 Subject: [PATCH 13/16] updated eddystone service and added config service. --- ble/services/EddystoneConfigService.h | 548 ++++++++++++++++++++++++++ ble/services/EddystoneService.h | 357 ++++++++++------- 2 files changed, 765 insertions(+), 140 deletions(-) create mode 100644 ble/services/EddystoneConfigService.h diff --git a/ble/services/EddystoneConfigService.h b/ble/services/EddystoneConfigService.h new file mode 100644 index 0000000..635e280 --- /dev/null +++ b/ble/services/EddystoneConfigService.h @@ -0,0 +1,548 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ +#define SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ + +#include "mbed.h" +#include "ble/BLE.h" +#include "ble/services/EddystoneService.h" + +#define EDDYSTONE_NUM_UID_FRAMES 10 +#define EDDYSTONE_NUM_URL_FRAMES 50 + + +#define UUID_URI_BEACON(FIRST, SECOND) { \ + 0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba, \ + 0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8, \ +} + +static const uint8_t UUID_URI_BEACON_SERVICE[] = UUID_URI_BEACON(0x20, 0x80); +static const uint8_t UUID_LOCK_STATE_CHAR[] = UUID_URI_BEACON(0x20, 0x81); +static const uint8_t UUID_LOCK_CHAR[] = UUID_URI_BEACON(0x20, 0x82); +static const uint8_t UUID_UNLOCK_CHAR[] = UUID_URI_BEACON(0x20, 0x83); +static const uint8_t UUID_URI_DATA_CHAR[] = UUID_URI_BEACON(0x20, 0x84); +static const uint8_t UUID_FLAGS_CHAR[] = UUID_URI_BEACON(0x20, 0x85); +static const uint8_t UUID_ADV_POWER_LEVELS_CHAR[] = UUID_URI_BEACON(0x20, 0x86); +static const uint8_t UUID_TX_POWER_MODE_CHAR[] = UUID_URI_BEACON(0x20, 0x87); +static const uint8_t UUID_BEACON_PERIOD_CHAR[] = UUID_URI_BEACON(0x20, 0x88); +static const uint8_t UUID_RESET_CHAR[] = UUID_URI_BEACON(0x20, 0x89); +extern const uint8_t BEACON_EDDYSTONE[2]; + +/** +* @class EddystoneConfigService +* @brief Eddystone Configuration Service. Can be used to set URL, adjust power levels, and set flags. +* See https://github.com/google/eddystone +* +*/ +class EddystoneConfigService +{ +public: + /** + * @brief Transmission Power Modes for UriBeacon + */ + static const uint8_t TX_POWER_MODE_LOWEST = 0; /*!< Lowest TX power mode */ + static const uint8_t TX_POWER_MODE_LOW = 1; /*!< Low TX power mode */ + static const uint8_t TX_POWER_MODE_MEDIUM = 2; /*!< Medium TX power mode */ + static const uint8_t TX_POWER_MODE_HIGH = 3; /*!< High TX power mode */ + static const unsigned NUM_POWER_MODES = 4; /*!< Number of Power Modes defined */ + + static const int ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. + static const int SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets + + typedef uint8_t Lock_t[16]; /* 128 bits */ + typedef int8_t PowerLevels_t[NUM_POWER_MODES]; + + // There are currently 3 subframes defined, URI, UID, and TLM +#define EDDYSTONE_MAX_FRAMETYPE 3 + void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t); + uint8_t frameIndex; + static const int URI_DATA_MAX = 18; + typedef uint8_t UriData_t[URI_DATA_MAX]; + + // UID Frame Type subfields + static const int UID_NAMESPACEID_SIZE = 10; + typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE]; + static const int UID_INSTANCEID_SIZE = 6; + typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE]; + + // Eddystone Frame Type ID + static const uint8_t FRAME_TYPE_UID = 0x00; + static const uint8_t FRAME_TYPE_URL = 0x10; + static const uint8_t FRAME_TYPE_TLM = 0x20; + + static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14Bytes + static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes + + struct Params_t { + // Config Data + bool isConfigured; // Flag for configuration being complete, True = configured, false = not configured. Reset at instantiation, used for external callbacks. + uint8_t lockedState; + Lock_t lock; + uint8_t flags; + PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels + uint8_t txPowerMode; // Firmware power levels used with setTxPower() + uint16_t beaconPeriod; + // TLM Frame Data + uint8_t tlmVersion; // version of TLM packet + bool tlmEnabled; + float tlmBeaconPeriod; // how often to broadcat TLM frame, in S + // URI Frame Data + uint8_t uriDataLength; + UriData_t uriData; + bool uriEnabled; + float uriBeaconPeriod; // how often to broadcast URIFrame, in S + // UID Frame Data + UIDNamespaceID_t uidNamespaceID; // UUID type, Namespace ID, 10B + UIDInstanceID_t uidInstanceID; // UUID type, Instance ID, 6B + bool uidEnabled; + float uidBeaconPeriod; // how often to broadcast UID Frame, in S + }; + + /** + * @param[ref] ble + * BLEDevice object for the underlying controller. + * @param[in/out] paramsIn + * Reference to application-visible beacon state, loaded + * from persistent storage at startup. + * @param[in] defaultAdvPowerLevelsIn + * Default power-levels array; applies only if the resetToDefaultsFlag is true. + */ + EddystoneConfigService(BLEDevice &bleIn, + Params_t ¶msIn, + PowerLevels_t &defaultAdvPowerLevelsIn, + PowerLevels_t &radioPowerLevelsIn) : + ble(bleIn), + params(paramsIn), // Initialize URL Data + defaultAdvPowerLevels(defaultAdvPowerLevelsIn), + radioPowerLevels(radioPowerLevelsIn), + initSucceeded(false), + resetFlag(), + defaultUidNamespaceID(), // Initialize UID Data + defaultUidInstanceID(), + defaultUidPower(defaultAdvPowerLevelsIn[params.txPowerMode]), + uidIsSet(false), + defaultUriDataLength(), + defaultUriData(), + defaultUrlPower(defaultAdvPowerLevelsIn[params.txPowerMode]), + urlIsSet(false), + tlmIsSet(false), + lockedStateChar(UUID_LOCK_STATE_CHAR, ¶ms.lockedState), + lockChar(UUID_LOCK_CHAR, ¶ms.lock), + uriDataChar(UUID_URI_DATA_CHAR, params.uriData, 0, URI_DATA_MAX, + GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE), + unlockChar(UUID_UNLOCK_CHAR, ¶ms.lock), + flagsChar(UUID_FLAGS_CHAR, ¶ms.flags), + advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), + txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), + beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), + resetChar(UUID_RESET_CHAR, &resetFlag) + { + // set eddystone as not configured yet. Used to exit config before timeout if GATT services are written to. + params.isConfigured = false; + } + + /* + * @breif Start EddystoneConfig advertising. This function should be called after the EddystoneConfig constructor and after all the frames have been added. + * @paramsP[in] resetToDefaultsFlag + * Applies to the state of the 'paramsIn' parameter. + * If true, it indicates that paramsIn is potentially + * un-initialized, and default values should be used + * instead. Otherwise, paramsIn overrides the defaults. + * + */ + void start(bool resetToDefaultsFlag){ + INFO("reset to defaults flag = %d", resetToDefaultsFlag); + if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { + INFO("Reset to Defaults triggered"); + resetToDefaultsFlag = true; + } + + lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback); + unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback); + uriDataChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::uriDataWriteAuthorizationCallback); + flagsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); + advPowerLevelsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); + txPowerModeChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::powerModeAuthorizationCallback); + beaconPeriodChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); + resetChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback); + + static GattCharacteristic *charTable[] = { + &lockedStateChar, &lockChar, &unlockChar, &uriDataChar, + &flagsChar, &advPowerLevelsChar, &txPowerModeChar, &beaconPeriodChar, &resetChar + }; + + GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); + + ble.addService(configService); + if (resetToDefaultsFlag) { + resetToDefaults(); + } else { + updateCharacteristicValues(); + } + + ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback); + + setupEddystoneConfigAdvertisements(); /* Setup advertising for the configService. */ + + initSucceeded = true; + } + + /* + * Check if eddystone initialized successfully + */ + bool initSuccessfully(void) const { + return initSucceeded; + } + + /* + * @breif Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied. + * + * @param[in] tlmVersionIn Version of the TLM frame being used + * @param[in] advPeriodInMin how long between TLM frames being advertised, this is measured in minutes. + * + */ + void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){ + DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f",tlmVersionIn,advPeriodInSec); + defaultTlmVersion = tlmVersionIn; + TlmBatteryVoltage = 0; + TlmBeaconTemp = 0; + TlmPduCount = 0; + TlmTimeSinceBoot = 0; + defaultTlmAdvPeriod = advPeriodInSec; + tlmIsSet = true; // flag to add this to eddystone service when config is done + + } + + /* + * @breif Function to update the default values for the URI frame. Only applied if Reset Defaults is applied. + * + * @param[in] uriIn url to advertise + * @param[in] advPeriod how long to advertise the url for, measured in number of ADV frames. + * + */ + void setDefaultURIFrameData(const char * uriIn, float advPeriod = 1){ + DBG("Setting Default URI Data"); + // Set URL Frame + EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting + if (defaultUriDataLength > URI_DATA_MAX) { + return; + } + memcpy(defaultUriData,uriIn,URI_DATA_MAX); + //defaultUriDataLength = strlen(uriIn); + INFO("\t default URI = %s : %d", uriIn, defaultUriDataLength); +// defaultUriData = (UriData_t *)uriIn; + defaultUriAdvPeriod = advPeriod; + urlIsSet = true; // flag to add this to eddystone service when config is done + } + + /* + * @breif Function to update the default values for the UID frame. Only applied if Reset Defaults is applied. + * + * @param[in] namespaceID 10Byte Namespace ID + * @param[in] instanceID 6Byte Instance ID + * @param[in] advPeriod how long to advertise the URL for, measured in the number of adv frames. + * + */ + void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10){ + //Set UID frame + DBG("Setting default UID Data"); + memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); + memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); + defaultUidAdvPeriod = advPeriod; + uidIsSet = true; // flag to add this to eddystone service when config is done + } + + /* Start out by advertising the configService for a limited time after + * startup; and switch to the normal non-connectible beacon functionality + * afterwards. */ + void setupEddystoneConfigAdvertisements() { + const char DEVICE_NAME[] = "eddystone Config"; + + ble.clearAdvertisingPayload(); + + ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); + + // UUID is in different order in the ADV frame (!) + uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)]; + for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) { + reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1]; + } + ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID)); + ble.accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG); + ble.accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast(&DEVICE_NAME), sizeof(DEVICE_NAME)); + ble.accumulateScanResponse( + GapAdvertisingData::TX_POWER_LEVEL, + reinterpret_cast(&defaultAdvPowerLevels[EddystoneConfigService::TX_POWER_MODE_LOW]), + sizeof(uint8_t)); + + ble.setTxPower(radioPowerLevels[params.txPowerMode]); + ble.setDeviceName(reinterpret_cast(&DEVICE_NAME)); + ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); + ble.setAdvertisingInterval(GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(ADVERTISING_INTERVAL_MSEC)); + } + + /* + * This function actually impliments the Eddystone Beacon service. It can be called with the help of the wrapper function + * to load saved config params, or it can be called explicitly to reset the eddystone beacon to hardcoded values on each reset. + * + */ + void setupEddystoneAdvertisements() { + DBG("Switching Config -> adv"); + // Save params to storage + extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */ + saveURIBeaconConfigParams(¶ms); + INFO("Saved Params to Memory.") + // Setup Eddystone Service + static EddystoneService eddyServ(ble,params.beaconPeriod,radioPowerLevels[params.txPowerMode]); + // Set configured frames (TLM,UID,URI...etc) + if(params.tlmEnabled){ + eddyServ.setTLMFrameData(params.tlmVersion,params.tlmBeaconPeriod); + } + if(params.uriEnabled){ + eddyServ.setURLFrameData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriBeaconPeriod); + } + if(params.uidEnabled){ + eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode], (uint8_t *) params.uidNamespaceID, (uint8_t *) params.uidInstanceID, params.uidBeaconPeriod); + } + // Start Advertising the eddystone service. + eddyServ.start(); + } + +private: + + /* + * This callback is invoked when a GATT client attempts to modify any of the + * characteristics of this service. Attempts to do so are also applied to + * the internal state of this service object. + */ + void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) { + uint16_t handle = writeParams->handle; + + if (handle == lockChar.getValueHandle()) { + // Validated earlier + memcpy(params.lock, writeParams->data, sizeof(Lock_t)); + // Set the state to be locked by the lock code (note: zeros are a valid lock) + params.lockedState = true; + INFO("Device Locked"); + } else if (handle == unlockChar.getValueHandle()) { + // Validated earlier + params.lockedState = false; + INFO("Device Unlocked"); + } else if (handle == uriDataChar.getValueHandle()) { + params.uriDataLength = writeParams->len; + memset(params.uriData,0x00,URI_DATA_MAX); // clear URI string + memcpy(params.uriData, writeParams->data, params.uriDataLength); // set URI string + params.uriEnabled = true; + INFO("URI = %s, URILen = %d", writeParams->data, writeParams->len); + } else if (handle == flagsChar.getValueHandle()) { + params.flags = *(writeParams->data); + INFO("flagsChar = 0x%x",params.flags); + } else if (handle == advPowerLevelsChar.getValueHandle()) { + memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t)); + INFO("PowerLevelsChar = %4x",params.advPowerLevels); + } else if (handle == txPowerModeChar.getValueHandle()) { + params.txPowerMode = *(writeParams->data); + INFO("TxPowerModeChar = %d",params.txPowerMode); + } else if (handle == beaconPeriodChar.getValueHandle()) { + params.beaconPeriod = *((uint16_t *)(writeParams->data)); + INFO("BeaconPeriod = %d",params.beaconPeriod); + + /* Re-map beaconPeriod to within permissible bounds if necessary. */ + if (params.beaconPeriod != 0) { + bool paramsUpdated = false; + if (params.beaconPeriod < ble.getMinAdvertisingInterval()) { + params.beaconPeriod = ble.getMinAdvertisingInterval(); + paramsUpdated = true; + } else if (params.beaconPeriod > ble.getMaxAdvertisingInterval()) { + params.beaconPeriod = ble.getMaxAdvertisingInterval(); + paramsUpdated = true; + } + if (paramsUpdated) { + ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); + } + } + } else if (handle == resetChar.getValueHandle()) { + INFO("Reset triggered from Config Service, resetting to defaults"); + resetToDefaults(); + } + updateCharacteristicValues(); + params.isConfigured = true; // some configuration data has been passed, on disconnect switch to advertising mode. + } + + /* + * Reset the default values. + */ + void resetToDefaults(void) { + INFO("Resetting to defaults"); + // General + params.lockedState = false; + memset(params.lock, 0, sizeof(Lock_t)); + params.flags = 0x10; + memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t)); + params.txPowerMode = TX_POWER_MODE_LOW; + params.beaconPeriod = 1000; + + // TLM Frame + params.tlmVersion = defaultTlmVersion; + params.tlmBeaconPeriod = defaultTlmAdvPeriod; + params.tlmEnabled = tlmIsSet; + + // URL Frame + memcpy(params.uriData, defaultUriData, URI_DATA_MAX); + params.uriDataLength = defaultUriDataLength; + params.uriBeaconPeriod = defaultUriAdvPeriod; + params.uriEnabled = urlIsSet; + + // UID Frame + memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE); + memcpy(params.uidInstanceID, defaultUidInstanceID, UID_INSTANCEID_SIZE); + params.uidBeaconPeriod = defaultUidAdvPeriod; + params.uidEnabled = uidIsSet; + + updateCharacteristicValues(); + } + + /* + * Internal helper function used to update the GATT database following any + * change to the internal state of the service object. + */ + void updateCharacteristicValues(void) { + ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), ¶ms.lockedState, 1); + ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); // TODO: this isnt updating the initial URI in config mode, need to figure out why. + INFO("updateCharacteristicValues - URI, %s : %d",params.uriData, params.uriDataLength); + ble.updateCharacteristicValue(flagsChar.getValueHandle(), ¶ms.flags, 1); + ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), + reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); + ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); + ble.updateCharacteristicValue(advPowerLevelsChar.getValueHandle(), + reinterpret_cast(params.advPowerLevels), sizeof(PowerLevels_t)); + } + +private: + void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + if (params.lockedState) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; + } else if (authParams->len != sizeof(Lock_t)) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; + } else if (authParams->offset != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; + } else { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } + } + + + void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } else if (authParams->len != sizeof(Lock_t)) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; + } else if (authParams->offset != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; + } else if (memcmp(authParams->data, params.lock, sizeof(Lock_t)) != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; + } else { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } + } + + void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + if (params.lockedState) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; + } else if (authParams->offset != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; + } else { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } + } + + void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + if (params.lockedState) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; + } else if (authParams->len != sizeof(uint8_t)) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; + } else if (authParams->offset != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; + } else if (*((uint8_t *)authParams->data) >= NUM_POWER_MODES) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED; + } else { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } + } + + template + void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { + if (params.lockedState) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION; + } else if (authParams->len != sizeof(T)) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH; + } else if (authParams->offset != 0) { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET; + } else { + authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; + } + } + + BLEDevice &ble; + Params_t ¶ms; + Ticker timeSinceBootTick; + Timeout switchFrame; +// Default value that is restored on reset + PowerLevels_t &defaultAdvPowerLevels; // this goes into the advertising frames (radio power measured at 1m from device) + PowerLevels_t &radioPowerLevels; // this configures the power levels of the radio + uint8_t lockedState; + bool initSucceeded; + uint8_t resetFlag; + bool switchFlag; + +//UID Default value that is restored on reset + UIDNamespaceID_t defaultUidNamespaceID; + UIDInstanceID_t defaultUidInstanceID; + float defaultUidAdvPeriod; + int8_t defaultUidPower; + uint16_t uidRFU; + bool uidIsSet; + +//URI Default value that is restored on reset + uint8_t defaultUriDataLength; + UriData_t defaultUriData; + int8_t defaultUrlPower; + float defaultUriAdvPeriod; + bool urlIsSet; + +//TLM Default value that is restored on reset + uint8_t defaultTlmVersion; + float defaultTlmAdvPeriod; + volatile uint16_t TlmBatteryVoltage; + volatile uint16_t TlmBeaconTemp; + volatile uint32_t TlmPduCount; + volatile uint32_t TlmTimeSinceBoot; + bool tlmIsSet; + + ReadOnlyGattCharacteristic lockedStateChar; + WriteOnlyGattCharacteristic lockChar; + GattCharacteristic uriDataChar; + WriteOnlyGattCharacteristic unlockChar; + ReadWriteGattCharacteristic flagsChar; + ReadWriteGattCharacteristic advPowerLevelsChar; + ReadWriteGattCharacteristic txPowerModeChar; + ReadWriteGattCharacteristic beaconPeriodChar; + WriteOnlyGattCharacteristic resetChar; + +}; + +#endif // SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ diff --git a/ble/services/EddystoneService.h b/ble/services/EddystoneService.h index 2d54095..3ccd426 100644 --- a/ble/services/EddystoneService.h +++ b/ble/services/EddystoneService.h @@ -19,7 +19,7 @@ #include "ble/BLE.h" #include "mbed.h" - +#include "CircularBuffer.h" static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; //Debug is disabled by default @@ -48,19 +48,21 @@ static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; class EddystoneService { public: - /** - * @brief Transmission Power Modes for UriBeacon - */ + enum FrameTypes { + NONE, + url, + uid, + tlm + }; - static const int ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. static const int SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets // There are currently 3 subframes defined, URI, UID, and TLM #define EDDYSTONE_MAX_FRAMETYPE 3 void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t); - uint8_t frameIndex; static const int URI_DATA_MAX = 18; typedef uint8_t UriData_t[URI_DATA_MAX]; + CircularBuffer overflow; // UID Frame Type subfields static const int UID_NAMESPACEID_SIZE = 10; @@ -84,7 +86,11 @@ public: * @param RFU 2B of RFU, initialized to 0x0000 and not broadcast, included for future reference. * */ - void setUIDFrameData(int8_t power, UIDNamespaceID_t namespaceID, UIDInstanceID_t instanceID, uint16_t RFU = 0x0000) { + void setUIDFrameData(int8_t power, UIDNamespaceID_t namespaceID, UIDInstanceID_t instanceID, uint32_t uidAdvPeriodIn, uint16_t RFU = 0x0000) { + if(0 == uidAdvPeriodIn){ + uidIsSet = false; + return; + } if(power > 20) { power = 20; } @@ -95,6 +101,8 @@ public: memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); uidRFU = (uint16_t)RFU; // this is probably bad form, but it doesnt really matter yet. + uidAdvPeriod = uidAdvPeriodIn; + uidIsSet = true; // set toggle to advertise UID frames return; } @@ -115,12 +123,18 @@ public: defaultUidPower = -100; } Data[index++] = defaultUidPower; // 1B Power @ 0meter + DBG("UID NamespaceID = '0x"); for(int x = 0; x < UID_NAMESPACEID_SIZE; x++) { // 10B Namespce ID Data[index++] = defaultUidNamespaceID[x]; + DBG("%x,",defaultUidNamespaceID[x]); } + DBG("'\r\n"); + DBG("UID InstancdID = '0x"); for(int x = 0; x< UID_INSTANCEID_SIZE; x++) { // 6B Instance ID Data[index++] = defaultUidInstanceID[x]; + DBG("%x,",defaultUidInstanceID[x]); } + DBG("'\r\n"); if(0 != uidRFU) { // 2B RFU, include if non-zero, otherwise ignore Data[index++] = (uint8_t)(uidRFU >> 0); Data[index++] = (uint8_t)(uidRFU >> 8); @@ -133,14 +147,21 @@ public: * Set Eddystone URL Frame information. * @param[in] power TX Power in dB measured at 0 meters from the device. * @param url URL to encode + * @param urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) * @return false on success, true on failure. */ - bool setURLFrameData(int8_t power, const char * url) { + bool setURLFrameData(int8_t power, const char * urlIn, uint32_t urlAdvPeriodIn) { + if(0 == urlAdvPeriodIn){ + urlIsSet = false; + return false; + } defaultUrlPower = power; - encodeURL(url, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting + encodeURL(urlIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting if (defaultUriDataLength > URI_DATA_MAX) { return true; // error, URL is too big } + urlAdvPeriod = urlAdvPeriodIn; + urlIsSet = true; return false; } @@ -164,16 +185,23 @@ public: /* * Set Eddystone TLM Frame information. * @param[in] Version of the TLM beacon data format + * @param[in] advPeriod how often to advertise the TLM frame for (in minutes) * @param batteryVoltage in milivolts * @param beaconTemp in 8.8 floating point notation * */ - void setTLMFrameData(uint8_t version, uint16_t batteryVoltage, uint16_t beaconTemp, uint32_t pduCount = 0, uint32_t timeSinceBoot = 0) { + void setTLMFrameData(uint8_t version = 0, uint32_t advPeriod = 60, uint16_t batteryVoltage = 0, uint16_t beaconTemp = 0, uint32_t pduCount = 0, uint32_t timeSinceBoot = 0) { + if(0 == advPeriod){ + tlmIsSet = false; + return; + } TlmVersion = version; TlmBatteryVoltage = batteryVoltage; TlmBeaconTemp = beaconTemp; TlmPduCount = pduCount; // reset TlmTimeSinceBoot = timeSinceBoot; // reset + TlmAdvPeriod = advPeriod; + tlmIsSet = true; // TLM Data has been enabled return; } @@ -191,14 +219,14 @@ public: Data[index++] = (uint8_t)(TlmBatteryVoltage>>0); // Battery Voltage[1] Data[index++] = (uint8_t)(TlmBeaconTemp>>8); // Beacon Temp[0] Data[index++] = (uint8_t)(TlmBeaconTemp>>0); // Beacon Temp[1] - Data[index++] = (uint8_t)(TlmPduCount>>24); // PDU Count [0] - Data[index++] = (uint8_t)(TlmPduCount>>16); // PDU Count [1] - Data[index++] = (uint8_t)(TlmPduCount>>8); // PDU Count [2] - Data[index++] = (uint8_t)(TlmPduCount>>0); // PDU Count [3] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>24); // Time Since Boot [0] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>16); // Time Since Boot [1] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>8); // Time Since Boot [2] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>0); // Time Since Boot [3] + Data[index++] = (uint8_t)(TlmPduCount>>24); // PDU Count [0] + Data[index++] = (uint8_t)(TlmPduCount>>16); // PDU Count [1] + Data[index++] = (uint8_t)(TlmPduCount>>8); // PDU Count [2] + Data[index++] = (uint8_t)(TlmPduCount>>0); // PDU Count [3] + Data[index++] = (uint8_t)(TlmTimeSinceBoot>>24); // Time Since Boot [0] + Data[index++] = (uint8_t)(TlmTimeSinceBoot>>16); // Time Since Boot [1] + Data[index++] = (uint8_t)(TlmTimeSinceBoot>>8); // Time Since Boot [2] + Data[index++] = (uint8_t)(TlmTimeSinceBoot>>0); // Time Since Boot [3] DBG("constructURLFrame: %d, %d",maxSize,index); return index; } @@ -264,10 +292,13 @@ public: // } // printf("\r\n"); ble.clearAdvertisingPayload(); + ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); + ble.setAdvertisingInterval(100); ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, BEACON_EDDYSTONE, sizeof(BEACON_EDDYSTONE)); ble.accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, serviceData, serviceDataLen); + return true; } @@ -277,7 +308,7 @@ public: * This function exists because of time constraints in the radioNotificationCallback, so it is effectively * broken up into two functions. */ - void swapOutFrames(void) { + void swapOutFrames(FrameTypes frameType) { uint8_t serviceData[SERVICE_DATA_MAX]; unsigned serviceDataLen = 0; //hard code in the eddystone UUID @@ -285,37 +316,114 @@ public: serviceData[serviceDataLen++] = BEACON_EDDYSTONE[1]; // if certain frames are not enabled, then skip them. Worst case TLM is always enabled - switch(frameIndex) { - case 1: + switch(frameType) { + case tlm: + // TLM frame + if(tlmIsSet) { + DBG("Swapping in TLM Frame: version=%x, Batt=%d, Temp = %d, PDUCnt = %d, TimeSinceBoot=%d",TlmVersion, TlmBatteryVoltage, TlmBeaconTemp, TlmPduCount, TlmTimeSinceBoot); + serviceDataLen += constructTLMFrame(serviceData+serviceDataLen,20); + DBG("\t Swapping in TLM Frame: len=%d",serviceDataLen); + updateAdvPacket(serviceData,serviceDataLen); + } + break; + case url: // URL Frame if(urlIsSet) { - INFO("Swapping in URL Frame: Power: %d",defaultUrlPower); + DBG("Swapping in URL Frame: Power: %d",defaultUrlPower); serviceDataLen += constructURLFrame(serviceData+serviceDataLen,20); DBG("\t Swapping in URL Frame: len=%d ",serviceDataLen); updateAdvPacket(serviceData,serviceDataLen); - switchFlag = false; - frameIndex++; - break; + //switchFlag = false; } - case 2: + break; + case uid: // UID Frame if(uidIsSet) { - INFO("Swapping in UID Frame: Power: %d",defaultUidPower); + DBG("Swapping in UID Frame: Power: %d",defaultUidPower); serviceDataLen += constructUIDFrame(serviceData+serviceDataLen,20); DBG("\t Swapping in UID Frame: len=%d",serviceDataLen); updateAdvPacket(serviceData,serviceDataLen); - switchFlag = false; - frameIndex++; - break; + //switchFlag = false; } - default: - // TLM frame - INFO("Swapping in TLM Frame: version=%x, Batt=%d, Temp = %d, PDUCnt = %d, TimeSinceBoot=%d",TlmVersion, TlmBatteryVoltage, TlmBeaconTemp, TlmPduCount, TlmTimeSinceBoot); - serviceDataLen += constructTLMFrame(serviceData+serviceDataLen,20); - DBG("\t Swapping in TLM Frame: len=%d",serviceDataLen); - updateAdvPacket(serviceData,serviceDataLen); - frameIndex++; break; + default: + ERR("You have not initialized a Frame yet, please initialize one before starting a beacon"); + ERR("uidIsSet = %d, urlIsSet = %d, tlmIsSet = %d", uidIsSet, urlIsSet, tlmIsSet); + } + } + + /* + * Callback to swap in URL frame + */ + void urlCallback(void) { + DBG("urlCallback"); + if( false == advLock) { + advLock = true; + DBG("advLock = url") + frameIndex = url; + swapOutFrames(frameIndex); + ble.startAdvertising(); + } else { + // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free + INFO("URI(%d) cannot complete, %d is currently broadcasting",url, frameIndex); + FrameTypes x = url; + overflow.push(x); + } + return; + } + + /* + * Callback to swap in UID frame + */ + void uidCallback(void) { + DBG("uidCallback"); + if( false == advLock) { + advLock = true; + DBG("advLock = uid") + frameIndex = uid; + swapOutFrames(frameIndex); + ble.startAdvertising(); + } else { + // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free + INFO("UID(%d) cannot complete, %d is currently broadcasting", uid,frameIndex); + FrameTypes x = uid; // have to do this to satisfy cont vs volatile keywords... sigh... + overflow.push(x); + } + return; + } + + /* + * Callback to swap in TLM frame + */ + void tlmCallback(void) { + DBG("tlmCallback"); + if( false == advLock) { + // OK to broadcast + advLock = true; + DBG("advLock = tlm") + frameIndex = tlm; + swapOutFrames(frameIndex); + ble.startAdvertising(); + } else { + // Someone else is broadcasting, toss it into the overflow buffer to retransmit when free + INFO("TLM(%d) cannot complete, %d is currently broadcasting",tlm ,frameIndex); + FrameTypes x = tlm; + overflow.push(x); + } + return; + } + + void stopAdvCallback(void) { + if(overflow.empty()) { + // if nothing left to transmit, stop + ble.stopAdvertising(); + advLock = false; // unlock lock + } else { + // transmit other packets at current time index + FrameTypes x = NONE; + overflow.pop(x); + INFO("Re-Transmitting %d",x); + swapOutFrames(x); } } @@ -324,47 +432,15 @@ public: */ #define EDDYSTONE_SWAPFRAME_DELAYMS 1 void radioNotificationCallback(bool radioActive) { - //DBG("RadioNotificationCallback : %d, %d, %d, %d",radioActive,frameIndex,TlmPduCount,TlmTimeSinceBoot); // Update PDUCount TlmPduCount++; - frameIndex = frameIndex % EDDYSTONE_MAX_FRAMETYPE; - - - // True just before an frame is sent, fale just after a frame is sent + // True just before an frame is sent, false just after a frame is sent if(radioActive) { // Do Nothing } else { - // state machine to control which packet is being sent - switch(frameIndex) { - case 0: // TLM Frame - switchFrame.attach_us(this, &EddystoneService::swapOutFrames, EDDYSTONE_SWAPFRAME_DELAYMS); - switchFlag = true; - break; - case 1: // URL Frame - // switch out packets - if(switchFlag) { - switchFrame.attach_us(this, &EddystoneService::swapOutFrames, EDDYSTONE_SWAPFRAME_DELAYMS); - switchFlag = false; - } else { - if((TlmPduCount % 10) == 0) { // every 10 adv packets switch the frame - switchFlag = true; - } - } - break; - case 2: // UIDFrame - // switch out packets - if(switchFlag ) { - switchFrame.attach_us(this, &EddystoneService::swapOutFrames, EDDYSTONE_SWAPFRAME_DELAYMS); - switchFlag = false; - } else { - if((TlmPduCount % 10) == 0) { // every 10 adv packets switch the frame - switchFlag = true; - } - } - break; - } + // Packet has been sent, disable advertising + stopAdv.attach_us(this, &EddystoneService::stopAdvCallback, 1); } - return; } @@ -373,102 +449,102 @@ public: * this function should be used in leu of the config service. * * @param bleIn ble object used to broadcast eddystone information - * @oaram beaconPeriodus is how often ble broadcasts are mde, in mili seconds + * @param beaconPeriodus is how often ble broadcasts are mde, in mili seconds * @param txPowerLevel sets the broadcasting power level. - * @param uidNamespaceID 10Byte Namespace UUID - * @param uidInstanceID 6Byte Instance UUID - * @param url shortened URL to broadcast (pass in as a string) - * @param urlLen length of shortened url - * @param tlmVersion version of telemetry data field to use (default to 0x00) * */ EddystoneService(BLEDevice &bleIn, - uint16_t beaconPeriodus = 100, - uint8_t txPowerLevel = 0, - uint8_t * uidNamespaceID = NULL, - uint8_t * uidInstanceID = NULL, - const char * url = NULL, - uint8_t urlLen = 0, - uint8_t tlmVersion = 0) : - ble(bleIn) - { - uint8_t serviceData[SERVICE_DATA_MAX]; - unsigned serviceDataLen = 0; - ERR("This function is not fully implemented yet, dont use it!!"); - // Check optional frames, set their 'isSet' flags appropriately - if((uidNamespaceID != NULL) & (uidInstanceID != NULL)) { - uidIsSet = true; - setUIDFrameData(txPowerLevel,uidNamespaceID, uidInstanceID); - } else { - uidIsSet = false; + uint16_t beaconPeriodus = 100, + uint8_t txPowerIn = 0) : + ble(bleIn), + advPeriodus(beaconPeriodus), + txPower(txPowerIn), + advLock(false), + frameIndex(NONE) { + + } + + /* + * @breif this function starts eddystone advertising based on configured frames. + */ + void start(void) { + // Initialize Frame transition, start with URL to pass eddystone validator app on first try + if (urlIsSet) { + frameIndex = url; + urlTicker.attach(this, &EddystoneService::urlCallback, urlAdvPeriod); + DBG("attached urlCallback every %d seconds", urlAdvPeriod); } - if(url != NULL) { - urlIsSet = true; - setURLFrameData(txPowerLevel,url); - } else { - uidIsSet = false; + if (uidIsSet) { + frameIndex = uid; + uidTicker.attach(this, &EddystoneService::uidCallback, uidAdvPeriod); + DBG("attached uidCallback every %d seconds", uidAdvPeriod); } - // Default TLM frame to version 0x00, start all values at zero to be spec compliant. - setTLMFrameData(tlmVersion, 0x00,0x00); - - // Initialize Frame transition - frameIndex = 0; - uidRFU = 0; - switchFlag = true; - - /* Reinitialize the BLE stack. This will clear away the existing services and advertising state. */ - ble.shutdown(); - ble.init(); - ble.setTxPower(txPowerLevel); - ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); - ble.setAdvertisingInterval(beaconPeriodus); - - // Make double sure the PDUCount and TimeSinceBoot fields are set to zero at reset - updateTlmPduCount(0); - updateTlmTimeSinceBoot(0); - - // Construct TLM Frame in initial advertising. - serviceData[serviceDataLen++] = BEACON_EDDYSTONE[0]; - serviceData[serviceDataLen++] = BEACON_EDDYSTONE[1]; - serviceDataLen += constructTLMFrame(serviceData+serviceDataLen,SERVICE_DATA_MAX); - - updateAdvPacket(serviceData, serviceDataLen); - ble.gap().startAdvertising(); - ble.gap().onRadioNotification(this,&EddystoneService::radioNotificationCallback); - timeSinceBootTick.attach(this,&EddystoneService::tsbCallback,0.1); // incriment the TimeSinceBoot ticker every 0.1s + if(tlmIsSet) { + frameIndex = tlm; + // Make double sure the PDUCount and TimeSinceBoot fields are set to zero at reset + updateTlmPduCount(0); + updateTlmTimeSinceBoot(0); + timeSinceBootTick.attach(this,&EddystoneService::tsbCallback,0.1); // incriment the TimeSinceBoot ticker every 0.1s + tlmTicker.attach(this, &EddystoneService::tlmCallback, TlmAdvPeriod); + DBG("attached tlmCallback every %d seconds", TlmAdvPeriod); + } + if(NONE == frameIndex) { + error("No Frames were Initialized! Please initialize a frame before starting an eddystone beacon."); + } + //uidRFU = 0; + ble.setTxPower(txPower); +// ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); +// ble.setAdvertisingInterval(advPeriodus); +// ble.gap().startAdvertising(); + ble.gap().onRadioNotification(this,&EddystoneService::radioNotificationCallback); } private: - + // Eddystone Variables BLEDevice &ble; - Ticker timeSinceBootTick; - Timeout switchFrame; -// Default value that is restored on reset - size_t defaultUriDataLength; + uint16_t advPeriodus; + uint8_t txPower; + Ticker timeSinceBootTick; // counter that counts time since boot + volatile bool advLock; + volatile FrameTypes frameIndex; + Timeout stopAdv; + + + // URI Frame Variables + uint8_t defaultUriDataLength; UriData_t defaultUriData; + int8_t defaultUrlPower; + bool urlIsSet; // flag that enables / disable URI Frames + uint32_t urlAdvPeriod; // how long the url frame will be advertised for + Ticker urlTicker; + + // UID Frame Variables UIDNamespaceID_t defaultUidNamespaceID; UIDInstanceID_t defaultUidInstanceID; int8_t defaultUidPower; - int8_t defaultUrlPower; uint16_t uidRFU; - bool uidIsSet; - bool urlIsSet; - bool switchFlag; + bool uidIsSet; // flag that enables / disable UID Frames + uint32_t uidAdvPeriod; // how long the uid frame will be advertised for + Ticker uidTicker; -// Private Variables for Telemetry Data + // TLM Frame Variables uint8_t TlmVersion; volatile uint16_t TlmBatteryVoltage; volatile uint16_t TlmBeaconTemp; volatile uint32_t TlmPduCount; volatile uint32_t TlmTimeSinceBoot; + bool tlmIsSet; // flag that enables / disables TLM frames + uint32_t TlmAdvPeriod; // number of minutes between adv frames + Ticker tlmTicker; public: /* * Encode a human-readable URI into the binary format defined by URIBeacon spec (https://github.com/google/uribeacon/tree/master/specification). */ - static void encodeURL(const char *uriDataIn, UriData_t uriDataOut, size_t &sizeofURIDataOut) { + static void encodeURL(const char *uriDataIn, UriData_t uriDataOut, uint8_t &sizeofURIDataOut) { + DBG("Encode URL = %s",uriDataIn); const char *prefixes[] = { "http://www.", "https://www.", @@ -528,6 +604,7 @@ public: } } /* This is the default case where we've got an ordinary character which doesn't match a suffix. */ + INFO("Encoding URI: No Suffix Found"); if (i == NUM_SUFFIXES) { uriDataOut[sizeofURIDataOut++] = *uriDataIn; ++uriDataIn; From d389c42692c453bc88c94f4300d856a5ee316efc Mon Sep 17 00:00:00 2001 From: Austin Blackstone Date: Mon, 28 Sep 2015 13:56:41 -0500 Subject: [PATCH 14/16] patch to ensure corred UUID being broadcast during Config. --- ble/services/EddystoneConfigService.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ble/services/EddystoneConfigService.h b/ble/services/EddystoneConfigService.h index 635e280..0bb81be 100644 --- a/ble/services/EddystoneConfigService.h +++ b/ble/services/EddystoneConfigService.h @@ -241,10 +241,8 @@ public: if (defaultUriDataLength > URI_DATA_MAX) { return; } - memcpy(defaultUriData,uriIn,URI_DATA_MAX); - //defaultUriDataLength = strlen(uriIn); - INFO("\t default URI = %s : %d", uriIn, defaultUriDataLength); -// defaultUriData = (UriData_t *)uriIn; + INFO("\t URI input = %s : %d", uriIn, defaultUriDataLength); + INFO("\t default URI = %s : %d ",defaultUriData,defaultUriDataLength ); defaultUriAdvPeriod = advPeriod; urlIsSet = true; // flag to add this to eddystone service when config is done } From 5aa7895578f18d137682624f3f4d41daee0aca0b Mon Sep 17 00:00:00 2001 From: Rohit Grover Date: Tue, 29 Sep 2015 08:41:18 +0100 Subject: [PATCH 15/16] mostly white-sapce improvements --- ble/services/EddystoneConfigService.h | 298 +++++++++++++------------- ble/services/EddystoneService.h | 285 ++++++++++++------------ 2 files changed, 295 insertions(+), 288 deletions(-) diff --git a/ble/services/EddystoneConfigService.h b/ble/services/EddystoneConfigService.h index 0bb81be..5a06b8b 100644 --- a/ble/services/EddystoneConfigService.h +++ b/ble/services/EddystoneConfigService.h @@ -14,17 +14,13 @@ * limitations under the License. */ -#ifndef SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ -#define SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ +#ifndef SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ +#define SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ #include "mbed.h" #include "ble/BLE.h" #include "ble/services/EddystoneService.h" -#define EDDYSTONE_NUM_UID_FRAMES 10 -#define EDDYSTONE_NUM_URL_FRAMES 50 - - #define UUID_URI_BEACON(FIRST, SECOND) { \ 0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba, \ 0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8, \ @@ -40,7 +36,7 @@ static const uint8_t UUID_ADV_POWER_LEVELS_CHAR[] = UUID_URI_BEACON(0x20, 0x86); static const uint8_t UUID_TX_POWER_MODE_CHAR[] = UUID_URI_BEACON(0x20, 0x87); static const uint8_t UUID_BEACON_PERIOD_CHAR[] = UUID_URI_BEACON(0x20, 0x88); static const uint8_t UUID_RESET_CHAR[] = UUID_URI_BEACON(0x20, 0x89); -extern const uint8_t BEACON_EDDYSTONE[2]; +extern const uint8_t BEACON_EDDYSTONE[2]; /** * @class EddystoneConfigService @@ -50,34 +46,34 @@ extern const uint8_t BEACON_EDDYSTONE[2]; */ class EddystoneConfigService { -public: +public: /** * @brief Transmission Power Modes for UriBeacon */ - static const uint8_t TX_POWER_MODE_LOWEST = 0; /*!< Lowest TX power mode */ - static const uint8_t TX_POWER_MODE_LOW = 1; /*!< Low TX power mode */ - static const uint8_t TX_POWER_MODE_MEDIUM = 2; /*!< Medium TX power mode */ - static const uint8_t TX_POWER_MODE_HIGH = 3; /*!< High TX power mode */ - static const unsigned NUM_POWER_MODES = 4; /*!< Number of Power Modes defined */ + enum { + TX_POWER_MODE_LOWEST, + TX_POWER_MODE_LOW, + TX_POWER_MODE_MEDIUM, + TX_POWER_MODE_HIGH, + NUM_POWER_MODES + }; - static const int ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. - static const int SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets + static const unsigned ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service. + static const unsigned SERVICE_DATA_MAX = 31; // Maximum size of service data in ADV packets - typedef uint8_t Lock_t[16]; /* 128 bits */ + typedef uint8_t Lock_t[16]; /* 128 bits */ typedef int8_t PowerLevels_t[NUM_POWER_MODES]; // There are currently 3 subframes defined, URI, UID, and TLM #define EDDYSTONE_MAX_FRAMETYPE 3 - void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t); - uint8_t frameIndex; - static const int URI_DATA_MAX = 18; - typedef uint8_t UriData_t[URI_DATA_MAX]; + static const unsigned URI_DATA_MAX = 18; + typedef uint8_t UriData_t[URI_DATA_MAX]; // UID Frame Type subfields - static const int UID_NAMESPACEID_SIZE = 10; - typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE]; - static const int UID_INSTANCEID_SIZE = 6; - typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE]; + static const size_t UID_NAMESPACEID_SIZE = 10; + typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE]; + static const size_t UID_INSTANCEID_SIZE = 6; + typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE]; // Eddystone Frame Type ID static const uint8_t FRAME_TYPE_UID = 0x00; @@ -89,27 +85,28 @@ public: struct Params_t { // Config Data - bool isConfigured; // Flag for configuration being complete, True = configured, false = not configured. Reset at instantiation, used for external callbacks. - uint8_t lockedState; - Lock_t lock; - uint8_t flags; - PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels - uint8_t txPowerMode; // Firmware power levels used with setTxPower() - uint16_t beaconPeriod; + bool isConfigured; // Flag for configuration being complete, + // True = configured, false = not configured. Reset at instantiation, used for external callbacks. + uint8_t lockedState; + Lock_t lock; + uint8_t flags; + PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels + uint8_t txPowerMode; // Firmware power levels used with setTxPower() + uint16_t beaconPeriod; // TLM Frame Data - uint8_t tlmVersion; // version of TLM packet - bool tlmEnabled; - float tlmBeaconPeriod; // how often to broadcat TLM frame, in S + uint8_t tlmVersion; // version of TLM packet + bool tlmEnabled; + float tlmBeaconPeriod; // how often to broadcat TLM frame, in seconds. // URI Frame Data - uint8_t uriDataLength; - UriData_t uriData; - bool uriEnabled; - float uriBeaconPeriod; // how often to broadcast URIFrame, in S + uint8_t uriDataLength; + UriData_t uriData; + bool uriEnabled; + float uriBeaconPeriod; // how often to broadcast URIFrame, in seconds. // UID Frame Data - UIDNamespaceID_t uidNamespaceID; // UUID type, Namespace ID, 10B - UIDInstanceID_t uidInstanceID; // UUID type, Instance ID, 6B - bool uidEnabled; - float uidBeaconPeriod; // how often to broadcast UID Frame, in S + UIDNamespaceID_t uidNamespaceID; // UUID type, Namespace ID, 10B + UIDInstanceID_t uidInstanceID; // UUID type, Instance ID, 6B + bool uidEnabled; + float uidBeaconPeriod; // how often to broadcast UID Frame, in seconds. }; /** @@ -149,27 +146,9 @@ public: advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, ¶ms.advPowerLevels), txPowerModeChar(UUID_TX_POWER_MODE_CHAR, ¶ms.txPowerMode), beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, ¶ms.beaconPeriod), - resetChar(UUID_RESET_CHAR, &resetFlag) - { + resetChar(UUID_RESET_CHAR, &resetFlag) { // set eddystone as not configured yet. Used to exit config before timeout if GATT services are written to. params.isConfigured = false; - } - - /* - * @breif Start EddystoneConfig advertising. This function should be called after the EddystoneConfig constructor and after all the frames have been added. - * @paramsP[in] resetToDefaultsFlag - * Applies to the state of the 'paramsIn' parameter. - * If true, it indicates that paramsIn is potentially - * un-initialized, and default values should be used - * instead. Otherwise, paramsIn overrides the defaults. - * - */ - void start(bool resetToDefaultsFlag){ - INFO("reset to defaults flag = %d", resetToDefaultsFlag); - if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { - INFO("Reset to Defaults triggered"); - resetToDefaultsFlag = true; - } lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback); unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback); @@ -188,16 +167,33 @@ public: GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); ble.addService(configService); + ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback); + } + + /** + * @brief Start EddystoneConfig advertising. This function should be called + * after the EddystoneConfig constructor and after all the frames have been added. + * + * @paramsP[in] resetToDefaultsFlag + * Applies to the state of the 'paramsIn' parameter. + * If true, it indicates that paramsIn is potentially + * un-initialized, and default values should be used + * instead. Otherwise, paramsIn overrides the defaults. + */ + void start(bool resetToDefaultsFlag){ + INFO("reset to defaults flag = %d", resetToDefaultsFlag); + if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { + INFO("Reset to Defaults triggered"); + resetToDefaultsFlag = true; + } + if (resetToDefaultsFlag) { resetToDefaults(); } else { updateCharacteristicValues(); } - - ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback); setupEddystoneConfigAdvertisements(); /* Setup advertising for the configService. */ - initSucceeded = true; } @@ -207,48 +203,47 @@ public: bool initSuccessfully(void) const { return initSucceeded; } - + /* - * @breif Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied. + * @brief Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied. * * @param[in] tlmVersionIn Version of the TLM frame being used * @param[in] advPeriodInMin how long between TLM frames being advertised, this is measured in minutes. * */ void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){ - DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f",tlmVersionIn,advPeriodInSec); - defaultTlmVersion = tlmVersionIn; - TlmBatteryVoltage = 0; - TlmBeaconTemp = 0; - TlmPduCount = 0; - TlmTimeSinceBoot = 0; + DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f", tlmVersionIn, advPeriodInSec); + defaultTlmVersion = tlmVersionIn; + TlmBatteryVoltage = 0; + TlmBeaconTemp = 0; + TlmPduCount = 0; + TlmTimeSinceBoot = 0; defaultTlmAdvPeriod = advPeriodInSec; - tlmIsSet = true; // flag to add this to eddystone service when config is done - + tlmIsSet = true; // flag to add this to eddystone service when config is done } - + /* - * @breif Function to update the default values for the URI frame. Only applied if Reset Defaults is applied. + * @brief Function to update the default values for the URI frame. Only applied if Reset Defaults is applied. * * @param[in] uriIn url to advertise * @param[in] advPeriod how long to advertise the url for, measured in number of ADV frames. * */ - void setDefaultURIFrameData(const char * uriIn, float advPeriod = 1){ + void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1){ DBG("Setting Default URI Data"); // Set URL Frame - EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting + EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting if (defaultUriDataLength > URI_DATA_MAX) { return; } INFO("\t URI input = %s : %d", uriIn, defaultUriDataLength); - INFO("\t default URI = %s : %d ",defaultUriData,defaultUriDataLength ); + INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength ); defaultUriAdvPeriod = advPeriod; - urlIsSet = true; // flag to add this to eddystone service when config is done + urlIsSet = true; // flag to add this to eddystone service when config is done } - + /* - * @breif Function to update the default values for the UID frame. Only applied if Reset Defaults is applied. + * @brief Function to update the default values for the UID frame. Only applied if Reset Defaults is applied. * * @param[in] namespaceID 10Byte Namespace ID * @param[in] instanceID 6Byte Instance ID @@ -261,7 +256,7 @@ public: memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); defaultUidAdvPeriod = advPeriod; - uidIsSet = true; // flag to add this to eddystone service when config is done + uidIsSet = true; // flag to add this to eddystone service when config is done } /* Start out by advertising the configService for a limited time after @@ -304,24 +299,26 @@ public: extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */ saveURIBeaconConfigParams(¶ms); INFO("Saved Params to Memory.") - // Setup Eddystone Service - static EddystoneService eddyServ(ble,params.beaconPeriod,radioPowerLevels[params.txPowerMode]); + // Setup Eddystone Service + static EddystoneService eddyServ(ble, params.beaconPeriod, radioPowerLevels[params.txPowerMode]); // Set configured frames (TLM,UID,URI...etc) - if(params.tlmEnabled){ - eddyServ.setTLMFrameData(params.tlmVersion,params.tlmBeaconPeriod); + if (params.tlmEnabled) { + eddyServ.setTLMFrameData(params.tlmVersion, params.tlmBeaconPeriod); } - if(params.uriEnabled){ + if (params.uriEnabled) { eddyServ.setURLFrameData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriBeaconPeriod); } - if(params.uidEnabled){ - eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode], (uint8_t *) params.uidNamespaceID, (uint8_t *) params.uidInstanceID, params.uidBeaconPeriod); - } - // Start Advertising the eddystone service. - eddyServ.start(); + if (params.uidEnabled) { + eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode], + (uint8_t *)params.uidNamespaceID, + (uint8_t *)params.uidInstanceID, + params.uidBeaconPeriod); + } + // Start Advertising the eddystone service. + eddyServ.start(); } private: - /* * This callback is invoked when a GATT client attempts to modify any of the * characteristics of this service. Attempts to do so are also applied to @@ -342,32 +339,32 @@ private: INFO("Device Unlocked"); } else if (handle == uriDataChar.getValueHandle()) { params.uriDataLength = writeParams->len; - memset(params.uriData,0x00,URI_DATA_MAX); // clear URI string + memset(params.uriData, 0x00, URI_DATA_MAX); // clear URI string memcpy(params.uriData, writeParams->data, params.uriDataLength); // set URI string params.uriEnabled = true; INFO("URI = %s, URILen = %d", writeParams->data, writeParams->len); } else if (handle == flagsChar.getValueHandle()) { params.flags = *(writeParams->data); - INFO("flagsChar = 0x%x",params.flags); + INFO("flagsChar = 0x%x", params.flags); } else if (handle == advPowerLevelsChar.getValueHandle()) { memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t)); - INFO("PowerLevelsChar = %4x",params.advPowerLevels); + INFO("PowerLevelsChar = %4x", params.advPowerLevels); } else if (handle == txPowerModeChar.getValueHandle()) { params.txPowerMode = *(writeParams->data); - INFO("TxPowerModeChar = %d",params.txPowerMode); + INFO("TxPowerModeChar = %d", params.txPowerMode); } else if (handle == beaconPeriodChar.getValueHandle()) { params.beaconPeriod = *((uint16_t *)(writeParams->data)); - INFO("BeaconPeriod = %d",params.beaconPeriod); + INFO("BeaconPeriod = %d", params.beaconPeriod); /* Re-map beaconPeriod to within permissible bounds if necessary. */ if (params.beaconPeriod != 0) { bool paramsUpdated = false; if (params.beaconPeriod < ble.getMinAdvertisingInterval()) { params.beaconPeriod = ble.getMinAdvertisingInterval(); - paramsUpdated = true; + paramsUpdated = true; } else if (params.beaconPeriod > ble.getMaxAdvertisingInterval()) { params.beaconPeriod = ble.getMaxAdvertisingInterval(); - paramsUpdated = true; + paramsUpdated = true; } if (paramsUpdated) { ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); @@ -387,30 +384,30 @@ private: void resetToDefaults(void) { INFO("Resetting to defaults"); // General - params.lockedState = false; + params.lockedState = false; memset(params.lock, 0, sizeof(Lock_t)); - params.flags = 0x10; + params.flags = 0x10; memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t)); - params.txPowerMode = TX_POWER_MODE_LOW; - params.beaconPeriod = 1000; - + params.txPowerMode = TX_POWER_MODE_LOW; + params.beaconPeriod = 1000; + // TLM Frame - params.tlmVersion = defaultTlmVersion; + params.tlmVersion = defaultTlmVersion; params.tlmBeaconPeriod = defaultTlmAdvPeriod; - params.tlmEnabled = tlmIsSet; - + params.tlmEnabled = tlmIsSet; + // URL Frame memcpy(params.uriData, defaultUriData, URI_DATA_MAX); - params.uriDataLength = defaultUriDataLength; - params.uriBeaconPeriod = defaultUriAdvPeriod; - params.uriEnabled = urlIsSet; - + params.uriDataLength = defaultUriDataLength; + params.uriBeaconPeriod = defaultUriAdvPeriod; + params.uriEnabled = urlIsSet; + // UID Frame memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE); memcpy(params.uidInstanceID, defaultUidInstanceID, UID_INSTANCEID_SIZE); params.uidBeaconPeriod = defaultUidAdvPeriod; - params.uidEnabled = uidIsSet; - + params.uidEnabled = uidIsSet; + updateCharacteristicValues(); } @@ -420,8 +417,7 @@ private: */ void updateCharacteristicValues(void) { ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), ¶ms.lockedState, 1); - ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); // TODO: this isnt updating the initial URI in config mode, need to figure out why. - INFO("updateCharacteristicValues - URI, %s : %d",params.uriData, params.uriDataLength); + ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); ble.updateCharacteristicValue(flagsChar.getValueHandle(), ¶ms.flags, 1); ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast(¶ms.beaconPeriod), sizeof(uint16_t)); @@ -443,7 +439,6 @@ private: } } - void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) { authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS; @@ -495,41 +490,41 @@ private: } } - BLEDevice &ble; - Params_t ¶ms; - Ticker timeSinceBootTick; - Timeout switchFrame; -// Default value that is restored on reset - PowerLevels_t &defaultAdvPowerLevels; // this goes into the advertising frames (radio power measured at 1m from device) - PowerLevels_t &radioPowerLevels; // this configures the power levels of the radio - uint8_t lockedState; - bool initSucceeded; - uint8_t resetFlag; - bool switchFlag; + BLEDevice &ble; + Params_t ¶ms; + Ticker timeSinceBootTick; + Timeout switchFrame; + // Default value that is restored on reset + PowerLevels_t &defaultAdvPowerLevels; // this goes into the advertising frames (radio power measured at 1m from device) + PowerLevels_t &radioPowerLevels; // this configures the power levels of the radio + uint8_t lockedState; + bool initSucceeded; + uint8_t resetFlag; + bool switchFlag; -//UID Default value that is restored on reset - UIDNamespaceID_t defaultUidNamespaceID; - UIDInstanceID_t defaultUidInstanceID; - float defaultUidAdvPeriod; - int8_t defaultUidPower; - uint16_t uidRFU; - bool uidIsSet; + //UID Default value that is restored on reset + UIDNamespaceID_t defaultUidNamespaceID; + UIDInstanceID_t defaultUidInstanceID; + float defaultUidAdvPeriod; + int8_t defaultUidPower; + uint16_t uidRFU; + bool uidIsSet; -//URI Default value that is restored on reset - uint8_t defaultUriDataLength; - UriData_t defaultUriData; - int8_t defaultUrlPower; - float defaultUriAdvPeriod; - bool urlIsSet; + //URI Default value that is restored on reset + uint8_t defaultUriDataLength; + UriData_t defaultUriData; + int8_t defaultUrlPower; + float defaultUriAdvPeriod; + bool urlIsSet; -//TLM Default value that is restored on reset - uint8_t defaultTlmVersion; - float defaultTlmAdvPeriod; - volatile uint16_t TlmBatteryVoltage; - volatile uint16_t TlmBeaconTemp; - volatile uint32_t TlmPduCount; - volatile uint32_t TlmTimeSinceBoot; - bool tlmIsSet; + //TLM Default value that is restored on reset + uint8_t defaultTlmVersion; + float defaultTlmAdvPeriod; + volatile uint16_t TlmBatteryVoltage; + volatile uint16_t TlmBeaconTemp; + volatile uint32_t TlmPduCount; + volatile uint32_t TlmTimeSinceBoot; + bool tlmIsSet; ReadOnlyGattCharacteristic lockedStateChar; WriteOnlyGattCharacteristic lockChar; @@ -540,7 +535,6 @@ private: ReadWriteGattCharacteristic txPowerModeChar; ReadWriteGattCharacteristic beaconPeriodChar; WriteOnlyGattCharacteristic resetChar; - }; -#endif // SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_ +#endif // SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ diff --git a/ble/services/EddystoneService.h b/ble/services/EddystoneService.h index 3ccd426..dcf0eaf 100644 --- a/ble/services/EddystoneService.h +++ b/ble/services/EddystoneService.h @@ -24,20 +24,32 @@ static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; //Debug is disabled by default #if 0 -#define DBG(x, ...) printf("[EddyStone: DBG]"x" \t[%s,%d]\r\n", ##__VA_ARGS__,__FILE__,__LINE__); -#define WARN(x, ...) printf("[EddyStone: WARN]"x" \t[%s,%d]\r\n", ##__VA_ARGS__,__FILE__,__LINE__); -#define ERR(x, ...) printf("[EddyStone: ERR]"x" \t[%s,%d]\r\n", ##__VA_ARGS__,__FILE__,__LINE__); -#else +#define DBG(MSG, ...) printf("[EddyStone: DBG]" MSG " \t[%s,%d]\r\n", \ + ## __VA_ARGS__, \ + __FILE__, \ + __LINE__); +#define WARN(MSG, ...) printf("[EddyStone: WARN]" MSG " \t[%s,%d]\r\n", \ + ## __VA_ARGS__, \ + __FILE__, \ + __LINE__); +#define ERR(MSG, ...) printf("[EddyStone: ERR]" MSG " \t[%s,%d]\r\n", \ + ## __VA_ARGS__, \ + __FILE__, \ + __LINE__); +#else // if 0 #define DBG(x, ...) //wait_us(10); #define WARN(x, ...) //wait_us(10); #define ERR(x, ...) -#endif +#endif // if 0 #if 0 -#define INFO(x, ...) printf("[EddyStone: INFO]"x" \t[%s,%d]\r\n", ##__VA_ARGS__,__FILE__,__LINE__); -#else +#define INFO(x, ...) printf("[EddyStone: INFO]"x " \t[%s,%d]\r\n", \ + ## __VA_ARGS__, \ + __FILE__, \ + __LINE__); +#else // if 0 #define INFO(x, ...) -#endif +#endif // if 0 /** * @class Eddystone @@ -62,7 +74,7 @@ public: void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t); static const int URI_DATA_MAX = 18; typedef uint8_t UriData_t[URI_DATA_MAX]; - CircularBuffer overflow; + CircularBuffer overflow; // UID Frame Type subfields static const int UID_NAMESPACEID_SIZE = 10; @@ -78,90 +90,98 @@ public: static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14Bytes static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes - /* - * Set Eddystone UID Frame information. - * @param[in] power TX Power in dB measured at 0 meters from the device. Range of -100 to +20 dB. - * @param namespaceID 10B namespace ID - * @param instanceID 6B instance ID - * @param RFU 2B of RFU, initialized to 0x0000 and not broadcast, included for future reference. - * - */ - void setUIDFrameData(int8_t power, UIDNamespaceID_t namespaceID, UIDInstanceID_t instanceID, uint32_t uidAdvPeriodIn, uint16_t RFU = 0x0000) { - if(0 == uidAdvPeriodIn){ + /** + * Set Eddystone UID Frame information. + * + * @param[in] power TX Power in dB measured at 0 meters from the device. Range of -100 to +20 dB. + * @param[in] namespaceID 10B namespace ID + * @param[in] instanceID 6B instance ID + * @param[in] RFU 2B of RFU, initialized to 0x0000 and not broadcast, included for future reference. + */ + void setUIDFrameData(int8_t power, + UIDNamespaceID_t namespaceID, + UIDInstanceID_t instanceID, + uint32_t uidAdvPeriodIn, + uint16_t RFU = 0x0000) { + if (0 == uidAdvPeriodIn) { uidIsSet = false; return; } - if(power > 20) { + if (power > 20) { power = 20; } - if(power < -100) { + if (power < -100) { power = -100; } + defaultUidPower = power; memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE); memcpy(defaultUidInstanceID, instanceID, UID_INSTANCEID_SIZE); - uidRFU = (uint16_t)RFU; // this is probably bad form, but it doesnt really matter yet. + uidRFU = (uint16_t)RFU; // this is probably bad form, but it doesn't really matter yet. uidAdvPeriod = uidAdvPeriodIn; - uidIsSet = true; // set toggle to advertise UID frames - return; + uidIsSet = true; // set toggle to advertise UID frames } /* * Construct UID frame from private variables * @param[in/out] Data pointer to array to store constructed frame in - * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to + * @param[in] maxSize number of bytes left in array, effectively how much empty space is available to write to * @return number of bytes used. negative number indicates error message. */ - int constructUIDFrame(uint8_t * Data, uint8_t maxSize) { + unsigned constructUIDFrame(uint8_t *Data, uint8_t maxSize) { + unsigned index = 0; - int index = 0; Data[index++] = FRAME_TYPE_UID; // 1B Type - if(defaultUidPower > 20) { - defaultUidPower = 20; // enforce range of vaild values. + + if (defaultUidPower > 20) { + defaultUidPower = 20; // enforce range of vaild values. } - if(defaultUidPower < -100) { + if (defaultUidPower < -100) { defaultUidPower = -100; } Data[index++] = defaultUidPower; // 1B Power @ 0meter + DBG("UID NamespaceID = '0x"); - for(int x = 0; x < UID_NAMESPACEID_SIZE; x++) { // 10B Namespce ID + for (size_t x = 0; x < UID_NAMESPACEID_SIZE; x++) { // 10B Namespace ID Data[index++] = defaultUidNamespaceID[x]; - DBG("%x,",defaultUidNamespaceID[x]); + DBG("%x,", defaultUidNamespaceID[x]); } DBG("'\r\n"); - DBG("UID InstancdID = '0x"); - for(int x = 0; x< UID_INSTANCEID_SIZE; x++) { // 6B Instance ID + + DBG("UID InstanceID = '0x"); + for (size_t x = 0; x< UID_INSTANCEID_SIZE; x++) { // 6B Instance ID Data[index++] = defaultUidInstanceID[x]; - DBG("%x,",defaultUidInstanceID[x]); + DBG("%x,", defaultUidInstanceID[x]); } DBG("'\r\n"); - if(0 != uidRFU) { // 2B RFU, include if non-zero, otherwise ignore + + if (0 != uidRFU) { // 2B RFU, include if non-zero, otherwise ignore Data[index++] = (uint8_t)(uidRFU >> 0); Data[index++] = (uint8_t)(uidRFU >> 8); } - DBG("construcUIDFrame %d, %d",maxSize,index); + DBG("construcUIDFrame %d, %d", maxSize, index); return index; } - /* - * Set Eddystone URL Frame information. - * @param[in] power TX Power in dB measured at 0 meters from the device. - * @param url URL to encode - * @param urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) - * @return false on success, true on failure. - */ - bool setURLFrameData(int8_t power, const char * urlIn, uint32_t urlAdvPeriodIn) { - if(0 == urlAdvPeriodIn){ + /** + * Set Eddystone URL Frame information. + * @param[in] power TX Power in dB measured at 0 meters from the device. + * @param[in] url URL to encode + * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) + * @return false on success, true on failure. + */ + bool setURLFrameData(int8_t power, const char *urlIn, uint32_t urlAdvPeriodIn) { + if (0 == urlAdvPeriodIn) { urlIsSet = false; return false; } defaultUrlPower = power; encodeURL(urlIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting if (defaultUriDataLength > URI_DATA_MAX) { - return true; // error, URL is too big + return true; // error, URL is too big } urlAdvPeriod = urlAdvPeriodIn; - urlIsSet = true; + urlIsSet = true; return false; } @@ -171,14 +191,14 @@ public: * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to * @return number of bytes used. negative number indicates error message. */ - int constructURLFrame(uint8_t * Data, uint8_t maxSize) { + int constructURLFrame(uint8_t *Data, uint8_t maxSize) { int index = 0; Data[index++] = FRAME_TYPE_URL; // 1B Type Data[index++] = defaultUrlPower; // 1B TX Power - for(int x = 0; x < defaultUriDataLength; x++) { // 18B of URL Prefix + encoded URL + for (int x = 0; x < defaultUriDataLength; x++) { // 18B of URL Prefix + encoded URL Data[index++] = defaultUriData[x]; } - DBG("constructURLFrame: %d, %d",maxSize,index); + DBG("constructURLFrame: %d, %d", maxSize, index); return index; } @@ -190,19 +210,23 @@ public: * @param beaconTemp in 8.8 floating point notation * */ - void setTLMFrameData(uint8_t version = 0, uint32_t advPeriod = 60, uint16_t batteryVoltage = 0, uint16_t beaconTemp = 0, uint32_t pduCount = 0, uint32_t timeSinceBoot = 0) { - if(0 == advPeriod){ + void setTLMFrameData(uint8_t version = 0, + uint32_t advPeriod = 60, + uint16_t batteryVoltage = 0, + uint16_t beaconTemp = 0, + uint32_t pduCount = 0, + uint32_t timeSinceBoot = 0) { + if (0 == advPeriod) { tlmIsSet = false; return; } - TlmVersion = version; + TlmVersion = version; TlmBatteryVoltage = batteryVoltage; - TlmBeaconTemp = beaconTemp; - TlmPduCount = pduCount; // reset - TlmTimeSinceBoot = timeSinceBoot; // reset - TlmAdvPeriod = advPeriod; - tlmIsSet = true; // TLM Data has been enabled - return; + TlmBeaconTemp = beaconTemp; + TlmPduCount = pduCount; // reset + TlmTimeSinceBoot = timeSinceBoot; // reset + TlmAdvPeriod = advPeriod; + tlmIsSet = true; // TLM Data has been enabled } /* @@ -211,23 +235,23 @@ public: * @param[in] maxSize number of bytes left in array, effectively how much emtpy space is available to write to * @return number of bytes used. negative number indicates error message. */ - int constructTLMFrame(uint8_t * Data, uint8_t maxSize) { + int constructTLMFrame(uint8_t *Data, uint8_t maxSize) { int index = 0; Data[index++] = FRAME_TYPE_TLM; // Eddystone frame type = Telemetry Data[index++] = TlmVersion; // TLM Version Number - Data[index++] = (uint8_t)(TlmBatteryVoltage>>8); // Battery Voltage[0] - Data[index++] = (uint8_t)(TlmBatteryVoltage>>0); // Battery Voltage[1] - Data[index++] = (uint8_t)(TlmBeaconTemp>>8); // Beacon Temp[0] - Data[index++] = (uint8_t)(TlmBeaconTemp>>0); // Beacon Temp[1] - Data[index++] = (uint8_t)(TlmPduCount>>24); // PDU Count [0] - Data[index++] = (uint8_t)(TlmPduCount>>16); // PDU Count [1] - Data[index++] = (uint8_t)(TlmPduCount>>8); // PDU Count [2] - Data[index++] = (uint8_t)(TlmPduCount>>0); // PDU Count [3] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>24); // Time Since Boot [0] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>16); // Time Since Boot [1] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>8); // Time Since Boot [2] - Data[index++] = (uint8_t)(TlmTimeSinceBoot>>0); // Time Since Boot [3] - DBG("constructURLFrame: %d, %d",maxSize,index); + Data[index++] = (uint8_t)(TlmBatteryVoltage >> 8); // Battery Voltage[0] + Data[index++] = (uint8_t)(TlmBatteryVoltage >> 0); // Battery Voltage[1] + Data[index++] = (uint8_t)(TlmBeaconTemp >> 8); // Beacon Temp[0] + Data[index++] = (uint8_t)(TlmBeaconTemp >> 0); // Beacon Temp[1] + Data[index++] = (uint8_t)(TlmPduCount >> 24); // PDU Count [0] + Data[index++] = (uint8_t)(TlmPduCount >> 16); // PDU Count [1] + Data[index++] = (uint8_t)(TlmPduCount >> 8); // PDU Count [2] + Data[index++] = (uint8_t)(TlmPduCount >> 0); // PDU Count [3] + Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 24); // Time Since Boot [0] + Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 16); // Time Since Boot [1] + Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 8); // Time Since Boot [2] + Data[index++] = (uint8_t)(TlmTimeSinceBoot >> 0); // Time Since Boot [3] + DBG("constructURLFrame: %d, %d", maxSize, index); return index; } @@ -238,7 +262,6 @@ public: */ void updateTlmBatteryVoltage(uint16_t voltagemv) { TlmBatteryVoltage = voltagemv; - return; } /* @@ -248,7 +271,6 @@ public: */ void updateTlmBeaconTemp(uint16_t temp) { TlmBeaconTemp = temp; - return; } /* @@ -258,7 +280,6 @@ public: */ void updateTlmPduCount(uint32_t pduCount) { TlmPduCount = pduCount; - return; } /* @@ -268,7 +289,6 @@ public: */ void updateTlmTimeSinceBoot(uint32_t timeSinceBoot) { TlmTimeSinceBoot = timeSinceBoot; - return; } /* @@ -286,11 +306,7 @@ public: bool updateAdvPacket(uint8_t serviceData[], unsigned serviceDataLen) { // Fields from the Service DBG("Updating AdvFrame: %d", serviceDataLen); -// printf("\r\n"); -// for(int x = 0; x Date: Tue, 29 Sep 2015 09:33:30 +0100 Subject: [PATCH 16/16] Release 0.4.8 ============= * Introduce an Instance() class method to BLE to allow access to the BLE singleton(s) using instanceID. Calling BLE::Instance() is preferable to constructing a BLE object directly because Instance() returns references to internally created singletons. * We've added an initial prototype for a yotta-config based initialization for BLE transports. It is conceivable to have multiple BLE transports available to a system concurrently in which case Instance() can be passed an instanceID. There's also a BLE::NUM_INSTANCES--instanceID passed to Instance() should be less than NUM_INSTANCES for the returned BLE singleton to be useful. The config system now allows the target to specify multiple BLE instances. BLE::Instance() and BLE constructor rely upon a static array of initializers to create actual BLE transport instances. A description of these instances and initializers is supposed to be put in some .json file contributing to yotta's configuration (typically the target.json). Here's a sample: "config": { ... "ble_instances": { "count": 1, "0" : { "initializer" : "createBLEInstance" } } } Refer to http://yottadocs.mbed.com/reference/config.html. Note: The configuration system is currently experimental. Some of the behaviour described below may change in backwards-incompatible ways with minor updates to yotta. The use of this feature is optional. Initialization would continue to work like before as long as there is a default createBLEInstance() method available. * We've updated our support for Google's Eddystone beacon by adding the EddystoneConfigService. * Added onConnection() and onDisconnection() now append to a callback chain internally. Please note that this has also changed the callbackType for onDisconnection; resulting in a minor breaking change for API. All previous programs using onDisconnection() would need to adapt. * Handle the case of a NULL transport pointer for BLE. * We now disallow copy constructor and assignment operator for BLE. --- module.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/module.json b/module.json index ab75196..1230e27 100644 --- a/module.json +++ b/module.json @@ -1,6 +1,6 @@ { "name": "ble", - "version": "0.4.7", + "version": "0.4.8", "description": "The BLE module offers a high level abstraction for using Bluetooth Low Energy on multiple platforms.", "keywords": [ "Bluetooth", @@ -30,4 +30,4 @@ "mbed-drivers": "*" } } -} \ No newline at end of file +}