Software can read HMC5883L
Fork of BLE_API by
Revision 1053:ec4a5b9b254e, committed 2016-01-11
- Comitter:
- vcoubard
- Date:
- Mon Jan 11 08:51:32 2016 +0000
- Parent:
- 1052:b55e1ad3e1b3
- Child:
- 1054:f59e5d9a992a
- Commit message:
- Synchronized with git rev 13bf70b6
Author: Rohit Grover
Release 2.1.5
=============
A minor release to separate the concept of minlen and len in
GattCharacteristic. Also contains some improvements to documentation.
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.gitignore Mon Jan 11 08:51:32 2016 +0000 @@ -0,0 +1,2 @@ +# Ignore the generated Doxygen output +apidoc/ \ No newline at end of file
--- a/CONTRIBUTING.md Mon Jan 11 08:51:31 2016 +0000 +++ b/CONTRIBUTING.md Mon Jan 11 08:51:32 2016 +0000 @@ -1,7 +1,7 @@ # Hello! We are an open source project of [ARM mbed](https://www.mbed.com). Contributions via [pull request](https://github.com/ARMmbed/ble/pulls), and [bug reports](https://github.com/ARMmbed/ble/issues) are welcome! -Please submit your pull request to the 'develop' branch of this module. Commits to develop will merge into master at the time of the next release. +Please submit your pull request to the `develop` branch of [this module](https://github.com/ARMmbed/ble/tree/develop). Commits to develop will be merge into the master branch at the time of the next release. # Contributor agreement For your pull request to be accepted, we will need you to agree to our [contributor agreement](https://developer.mbed.org/contributor_agreement/) to give us the necessary rights to use and distribute your contributions. (To click through the agreement create an account on mbed.com and log in.) \ No newline at end of file
--- a/DOXYGEN_FRONTPAGE.md Mon Jan 11 08:51:31 2016 +0000 +++ b/DOXYGEN_FRONTPAGE.md Mon Jan 11 08:51:32 2016 +0000 @@ -1,16 +1,31 @@ -#BLE API +# BLE API {#mainpage} -The BLE module within mbed OS offers a high level abstraction for using +The BLE module within mbed OS offers a high abstraction level for using Bluetooth Low Energy on multiple platforms. -This documentation describes the internal structure of mbed -(BLE_API)[https://github.com/armmbed/ble]. It was automatically generated from -specially formatted comment blocks in BLE_API's source code using Doxygen. -(See http://www.stack.nl/~dimitri/doxygen/ for more information on Doxygen). +This documentation describes the internal structure of the mbed +[BLE API](https://github.com/armmbed/ble). It was automatically generated from +specially formatted comment blocks in BLE API's source code using Doxygen (see http://www.stack.nl/~dimitri/doxygen/ for more information on Doxygen). + +For getting started with BLE on mbed, check our [introduction +page](https://docs.mbed.com/docs/ble-intros/en/latest/). + +For mbed OS examples using BLE, check [this +repository](https://github.com/armmbed/ble-examples). For mbed-classic +examples, please refer to [code under mbed.org](https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/). + +## Supported Services -For getting started with BLE on mbed, check our (introduction -page)[https://docs.mbed.com/docs/ble-intros/en/latest/]. +Currently supported reference services include: -For mbed OS examples using BLE, check (this -repository)[https://github.com/armmbed/ble-examples]. For mbed-classic -examples, refer to (code under mbed.org)[https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/]. \ No newline at end of file +* [Battery](@ref BatteryService) +* [Device Firmware Update (DFU)](@ref DFUService) +* [Device Information](@ref DeviceInformationService) +* [Health Thermometer](@ref HealthThermometerService) +* [Heart Rate](@ref HeartRateService) +* [UART](@ref UARTService) +* [UriBeacon](@ref URIBeaconConfigService) +* [iBeacon](@ref iBeacon) + +The [documentation](https://docs.mbed.com/docs/ble-intros/en/latest/AdvSamples/Overview/) +contains an overview on how to create new, application-specific services. \ No newline at end of file
--- a/README.md Mon Jan 11 08:51:31 2016 +0000 +++ b/README.md Mon Jan 11 08:51:32 2016 +0000 @@ -2,7 +2,7 @@ This is the Github repo for the `BLE_API` used by developer.mbed.org. Please see the [mbed BLE Homepage](https://developer.mbed.org/teams/Bluetooth-Low-Energy/) for all documentation, code examples and general help. # Supported Services -Supported GATT services and constantly being added and can be found in the (`ble/ble/services/`)[https://github.com/ARMmbed/ble/tree/master/ble/services] folder. +Supported GATT services and constantly being added and can be found in the [ble/services/](https://github.com/ARMmbed/ble/tree/master/ble/services) folder. Currently supported services include: * Battery @@ -16,10 +16,13 @@ * UriBeacon * iBeacon +The [documentation](https://docs.mbed.com/docs/ble-intros/en/latest/AdvSamples/Overview/) +contains an overview on how to create new, application-specific services. + # Getting Started The mbed BLE API is meant to be used in projects on developer.mbed.org. Please see examples and sample project files there. A good starting point are these pages: * [mbed BLE Homepage](https://developer.mbed.org/teams/Bluetooth-Low-Energy/) for all things BLE * [mbed BLE Getting Started Guide](https://developer.mbed.org/forum/team-63-Bluetooth-Low-Energy-community/topic/5262/) a wonderful primer on using BLE with mbed * [mbed BLE doc](https://docs.mbed.com/docs/ble-intros/en/latest/) for an introduction to mbed BLE -* [mbed BLE API page](https://developer.mbed.org/teams/Bluetooth-Low-Energy/code/BLE_API/docs/tip/) for the API in generated by doxygen \ No newline at end of file +* [mbed BLE API page](https://docs.mbed.com/docs/ble-api/en/latest/api/index.html) for the Doxygen API documentation \ No newline at end of file
--- a/ble.doxyfile Mon Jan 11 08:51:31 2016 +0000 +++ b/ble.doxyfile Mon Jan 11 08:51:32 2016 +0000 @@ -664,7 +664,7 @@ # directories like "/usr/src/myproject". Separate the files or directories # with spaces. -INPUT = . +INPUT = # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is @@ -682,7 +682,7 @@ # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl -FILE_PATTERNS = *.h *.cpp +FILE_PATTERNS = *.h *.cpp *.md # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. @@ -696,7 +696,7 @@ # Note that relative paths are relative to the directory from which doxygen is # run. -EXCLUDE = configs +EXCLUDE = configs CONTRIBUTING.md README.md # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded @@ -789,7 +789,7 @@ # (index.html). This can be useful if you have a project on for instance GitHub # and want reuse the introduction page also for the doxygen output. -USE_MDFILE_AS_MAINPAGE = +USE_MDFILE_AS_MAINPAGE = DOXYGEN_FRONTPAGE.md #--------------------------------------------------------------------------- # configuration options related to source browsing @@ -1611,18 +1611,7 @@ # undefined via #undef or recursively expanded use the := operator # instead of the = operator. -PREDEFINED = WIN32 \ - NTLM \ - USE_LZO \ - ENABLE_FRAGMENT \ - P2MP \ - P2MP_SERVER \ - USE_CRYPTO \ - USE_SSL \ - ENABLE_PLUGIN \ - ENABLE_MANAGEMENT \ - ENABLE_OCC \ - HAVE_GETTIMEOFDAY +PREDEFINED = TARGET_NRF51822 # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded.
--- a/ble/CharacteristicDescriptorDiscovery.h Mon Jan 11 08:51:31 2016 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,57 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-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. - */ - -#ifndef __CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__ -#define __CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__ - -#include "FunctionPointerWithContext.h" - -class DiscoveredCharacteristic; -class DiscoveredCharacteristicDescriptor; - -class CharacteristicDescriptorDiscovery { -public: - /* - * Exposed application callback types. - */ - struct DiscoveryCallbackParams_t { - const DiscoveredCharacteristic& characteristic; - const DiscoveredCharacteristicDescriptor& descriptor; - }; - - struct TerminationCallbackParams_t { - const DiscoveredCharacteristic& characteristic; - ble_error_t status; - }; - - /** - * Callback type for when a matching characteristic descriptor is found during - * characteristic descriptor discovery. The receiving function is passed in a - * pointer to a DiscoveryCallbackParams_t object which will remain - * valid for the lifetime of the callback. Memory for this object is owned by - * the BLE_API eventing framework. The application can safely make a persistent - * shallow-copy of this object in order to work with the service beyond the - * callback. - */ - typedef FunctionPointerWithContext<const DiscoveryCallbackParams_t*> DiscoveryCallback_t; - - /** - * Callback type for when characteristic descriptor discovery terminates. - */ - typedef FunctionPointerWithContext<const TerminationCallbackParams_t*> TerminationCallback_t; -}; - -#endif // ifndef __CHARACTERISTIC_DESCRIPTOR_DISCOVERY_H__ \ No newline at end of file
--- a/ble/DiscoveredCharacteristic.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/DiscoveredCharacteristic.h Mon Jan 11 08:51:32 2016 +0000 @@ -21,9 +21,6 @@ #include "Gap.h" #include "GattAttribute.h" #include "GattClient.h" -#include "CharacteristicDescriptorDiscovery.h" -#include "ble/DiscoveredCharacteristicDescriptor.h" - /** * Structure for holding information about the service and the characteristics @@ -49,26 +46,31 @@ bool indicate(void) const {return _indicate; } bool authSignedWrite(void) const {return _authSignedWrite;} - friend bool operator==(Properties_t rhs, Properties_t lhs) { - return rhs._broadcast == lhs._broadcast && - rhs._read == lhs._read && - rhs._writeWoResp == lhs._writeWoResp && - rhs._write == lhs._write && - rhs._notify == lhs._notify && - rhs._indicate == lhs._indicate && - rhs._authSignedWrite == lhs._authSignedWrite; - } - - friend bool operator!=(Properties_t rhs, Properties_t lhs) { - return !(rhs == lhs); - } - private: operator uint8_t() const; /* Disallow implicit conversion into an integer. */ operator unsigned() const; /* Disallow implicit conversion into an integer. */ }; /** + * Structure for holding information about the service and the characteristics + * found during the discovery process. + */ + struct DiscoveredDescriptor { + GattAttribute::Handle_t handle; /**< Descriptor Handle. */ + UUID uuid; /**< Descriptor UUID. */ + }; + + /** + * Callback type for when a characteristic descriptor is found during descriptor- + * discovery. The receiving function is passed in a pointer to a + * DiscoveredDescriptor object which will remain valid for the lifetime + * of the callback. Memory for this object is owned by the BLE_API eventing + * framework. The application can safely make a persistent shallow-copy of + * this object in order to work with the characteristic beyond the callback. + */ + typedef void (*DescriptorCallback_t)(const DiscoveredDescriptor *); + + /** * Initiate (or continue) a read for the value attribute, optionally at a * given offset. If the characteristic or descriptor to be read is longer * than ATT_MTU - 1, this function must be called multiple times with @@ -108,13 +110,13 @@ /** * Initiate a GATT Characteristic Descriptor Discovery procedure for descriptors within this characteristic. * - * @param onCharacteristicDiscovered This callback will be called every time a descriptor is discovered - * @param onTermination This callback will be called when the discovery process is over. + * @param callback + * @param matchingUUID + * Filter for descriptors. Defaults to wildcard which will discover all descriptors. * * @return BLE_ERROR_NONE if descriptor discovery is launched successfully; else an appropriate error. */ - ble_error_t discoverDescriptors(const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& onCharacteristicDiscovered, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& onTermination) const; + ble_error_t discoverDescriptors(DescriptorCallback_t callback, const UUID &matchingUUID = UUID::ShortUUIDBytes_t(BLE_UUID_UNKNOWN)) const; /** * Perform a write procedure. @@ -153,56 +155,19 @@ return props; } - GattAttribute::Handle_t getDeclHandle(void) const { + const GattAttribute::Handle_t& getDeclHandle(void) const { return declHandle; } - - GattAttribute::Handle_t getValueHandle(void) const { + const GattAttribute::Handle_t& getValueHandle(void) const { return valueHandle; } - GattAttribute::Handle_t getLastHandle(void) const { - return lastHandle; - } - - void setLastHandle(GattAttribute::Handle_t last) { - lastHandle = last; - } - - GattClient* getGattClient() { - return gattc; - } - - const GattClient* getGattClient() const { - return gattc; - } - - Gap::Handle_t getConnectionHandle() const { - return connHandle; - } - - friend bool operator==(const DiscoveredCharacteristic& rhs, const DiscoveredCharacteristic& lhs) { - return rhs.gattc == lhs.gattc && - rhs.uuid == lhs.uuid && - rhs.props == lhs.props && - rhs.declHandle == lhs.declHandle && - rhs.valueHandle == lhs.valueHandle && - rhs.lastHandle == lhs.lastHandle && - rhs.connHandle == lhs.connHandle; - } - - friend bool operator !=(const DiscoveredCharacteristic& rhs, const DiscoveredCharacteristic& lhs) { - return !(rhs == lhs); - } - public: DiscoveredCharacteristic() : gattc(NULL), uuid(UUID::ShortUUIDBytes_t(0)), props(), declHandle(GattAttribute::INVALID_HANDLE), - valueHandle(GattAttribute::INVALID_HANDLE), - lastHandle(GattAttribute::INVALID_HANDLE), - connHandle() { + valueHandle(GattAttribute::INVALID_HANDLE) { /* empty */ } @@ -214,7 +179,6 @@ Properties_t props; GattAttribute::Handle_t declHandle; GattAttribute::Handle_t valueHandle; - GattAttribute::Handle_t lastHandle; Gap::Handle_t connHandle; };
--- a/ble/DiscoveredCharacteristicDescriptor.h Mon Jan 11 08:51:31 2016 +0000 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,66 +0,0 @@ -/* 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 __DISCOVERED_CHARACTERISTIC_DESCRIPTOR_H__ -#define __DISCOVERED_CHARACTERISTIC_DESCRIPTOR_H__ - -#include "UUID.h" -#include "Gap.h" -#include "GattAttribute.h" -#include "GattClient.h" -#include "CharacteristicDescriptorDiscovery.h" - - -/** - * - */ -class DiscoveredCharacteristicDescriptor { - -public: - DiscoveredCharacteristicDescriptor( - GattClient* client, Gap::Handle_t connectionHandle, GattAttribute::Handle_t gattHandle, const UUID& uuid) : - _client(client), _connectionHandle(connectionHandle), _uuid(uuid), _gattHandle(gattHandle) { - - } - - GattClient* client() { - return _client; - } - - const GattClient* client() const { - return _client; - } - - Gap::Handle_t connectionHandle() const { - return _connectionHandle; - } - - const UUID& uuid(void) const { - return _uuid; - } - - GattAttribute::Handle_t gattHandle() const { - return _gattHandle; - } - -private: - GattClient *_client; - Gap::Handle_t _connectionHandle; - UUID _uuid; - GattAttribute::Handle_t _gattHandle; -}; - -#endif /*__DISCOVERED_CHARACTERISTIC_DESCRIPTOR_H__*/ \ No newline at end of file
--- a/ble/GattAttribute.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/GattAttribute.h Mon Jan 11 08:51:32 2016 +0000 @@ -33,8 +33,8 @@ * The UUID to use for this attribute. * @param[in] valuePtr * The memory holding the initial value. - * @param[in] initialLen - * The min length in bytes of this attribute's value. + * @param[in] len + * The length in bytes of this attribute's value. * @param[in] maxLen * The max length in bytes of this attribute's value. * @@ -47,8 +47,8 @@ * * @endcode */ - GattAttribute(const UUID &uuid, uint8_t *valuePtr = NULL, uint16_t initialLen = 0, uint16_t maxLen = 0) : - _uuid(uuid), _valuePtr(valuePtr), _initialLen(initialLen), _lenMax(maxLen), _len(initialLen), _handle() { + GattAttribute(const UUID &uuid, uint8_t *valuePtr = NULL, uint16_t len = 0, uint16_t maxLen = 0) : + _uuid(uuid), _valuePtr(valuePtr), _lenMax(maxLen), _len(len), _handle() { /* Empty */ } @@ -56,7 +56,6 @@ Handle_t getHandle(void) const {return _handle; } const UUID &getUUID(void) const {return _uuid; } uint16_t getLength(void) const {return _len; } - uint16_t getInitialLength(void) const {return _initialLen;} uint16_t getMaxLength(void) const {return _lenMax; } uint16_t *getLengthPtr(void) {return &_len; } void setHandle(Handle_t id) {_handle = id; } @@ -65,7 +64,6 @@ private: UUID _uuid; /* Characteristic UUID. */ uint8_t *_valuePtr; - uint16_t _initialLen; /* Initial length of the value. */ uint16_t _lenMax; /* Maximum length of the value. */ uint16_t _len; /* Current length of the value. */ Handle_t _handle;
--- a/ble/GattCharacteristic.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/GattCharacteristic.h Mon Jan 11 08:51:32 2016 +0000 @@ -307,8 +307,8 @@ * The memory holding the initial value. The value is copied * into the stack when the enclosing service is added, and * is thereafter maintained internally by the stack. - * @param[in] initialLen - * The min length in bytes of this characteristic's value. + * @param[in] len + * The length in bytes of this characteristic's value. * @param[in] maxLen * The max length in bytes of this characteristic's value. * @param[in] props @@ -321,19 +321,19 @@ * @param[in] numDescriptors * The number of descriptors in the previous array. * - * @NOTE: If valuePtr == NULL, initialLength == 0, and properties == READ + * @NOTE: If valuePtr == NULL, length == 0, and properties == READ * for the value attribute of a characteristic, then that particular * characteristic may be considered optional and dropped while * instantiating the service with the underlying BLE stack. */ GattCharacteristic(const UUID &uuid, uint8_t *valuePtr = NULL, - uint16_t initialLen = 0, + uint16_t len = 0, uint16_t maxLen = 0, uint8_t props = BLE_GATT_CHAR_PROPERTIES_NONE, GattAttribute *descriptors[] = NULL, unsigned numDescriptors = 0) : - _valueAttribute(uuid, valuePtr, initialLen, maxLen), + _valueAttribute(uuid, valuePtr, len, maxLen), _properties(props), _requiredSecurity(SecurityManager::SECURITY_MODE_ENCRYPTION_OPEN_LINK), _descriptors(descriptors),
--- a/ble/GattClient.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/GattClient.h Mon Jan 11 08:51:32 2016 +0000 @@ -20,7 +20,6 @@ #include "Gap.h" #include "GattAttribute.h" #include "ServiceDiscovery.h" -#include "CharacteristicDescriptorDiscovery.h" #include "GattCallbackParamTypes.h" @@ -306,53 +305,6 @@ } /** - * @brief launch discovery of descriptors for a given characteristic - * @details This function will discover all descriptors available for a - * specific characteristic. - * - * @param characteristic The characteristic targeted by this discovery - * @param callback This is the application callback for each descriptors - * found. - * @note service discovery may still be active when the callback is issued; - * calling asynchronous BLE-stack APIs from within this application callback - * might cause the stack to abort the discovery. If this becomes an issue, - * it may be better to make local copy of the DiscoveredCharacteristicDescriptor - * and wait for characteristic descriptor discovery to terminate before - * operating on the descriptor. - * - * @return - * BLE_ERROR_NONE if characteristic descriptor discovery is launched - * successfully; else an appropriate error. - */ - virtual ble_error_t discoverCharacteristicDescriptors( - const DiscoveredCharacteristic& characteristic, - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& discoveryCallback, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& terminationCallback) { - (void) characteristic; - (void) discoveryCallback; - (void) terminationCallback; - return BLE_ERROR_NOT_IMPLEMENTED; /* Requesting action from porter(s): override this API if this capability is supported. */ - } - - /** - * Is characteristic descriptor discovery currently active? - */ - virtual bool isCharacteristicDescriptorsDiscoveryActive(const DiscoveredCharacteristic& characteristic) const - { - (void) characteristic; - return false; /* Requesting action from porter(s): override this API if this capability is supported. */ - } - - /** - * Terminate an ongoing characteristic descriptor discovery. This should result - * in an invocation of the TerminationCallback if characteristic descriptor discovery is active. - */ - virtual void terminateCharacteristicDescriptorsDiscovery(const DiscoveredCharacteristic& characteristic) { - /* Requesting action from porter(s): override this API if this capability is supported. */ - (void) characteristic; - } - - /** * Set up a callback for when the GATT client receives an update event * corresponding to a change in the value of a characteristic on the remote * GATT server.
--- a/ble/blecommon.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/blecommon.h Mon Jan 11 08:51:32 2016 +0000 @@ -22,9 +22,7 @@ #endif -/** @defgroup BLE_UUID_VALUES assigned values for BLE UUIDs. - * @{ */ -/* Generic UUIDs, applicable to all services. */ +/*! @brief Assigned values for BLE UUIDs. */ enum { BLE_UUID_UNKNOWN = 0x0000, /**< Reserved UUID. */ BLE_UUID_SERVICE_PRIMARY = 0x2800, /**< Primary Service. */ @@ -50,11 +48,10 @@ BLE_UUID_GAP_CHARACTERISTIC_RECONN_ADDR = 0x2A03, /**< Reconnection Address Characteristic. */ BLE_UUID_GAP_CHARACTERISTIC_PPCP = 0x2A04, /**< Peripheral Preferred Connection Parameters Characteristic. */ }; -/** @} */ -/** @defgroup BLE_APPEARANCES Bluetooth appearance values. +/*! Bluetooth appearance values. * @note Retrieved from http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml - * @{ */ + */ enum { BLE_APPEARANCE_UNKNOWN = 0, /**< Unknown. */ BLE_APPEARANCE_GENERIC_PHONE = 64, /**< Generic Phone. */ @@ -106,13 +103,9 @@ BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_POD = 5187, /**< Location Pod (Outdoor Sports Activity subtype). */ BLE_APPEARANCE_OUTDOOR_SPORTS_ACT_LOC_AND_NAV_POD = 5188, /**< Location and Navigation Pod (Outdoor Sports Activity subtype). */ }; -/** @} */ + -/**************************************************************************/ -/*! - \brief Error codes for the BLE API -*/ -/**************************************************************************/ +/*! @brief Error codes for the BLE API. */ enum ble_error_t { BLE_ERROR_NONE = 0, /**< No error. */ BLE_ERROR_BUFFER_OVERFLOW = 1, /**< The requested action would cause a buffer overflow and has been aborted. */
--- a/ble/services/DFUService.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/services/DFUService.h Mon Jan 11 08:51:32 2016 +0000 @@ -14,13 +14,17 @@ * limitations under the License. */ +#ifdef TARGET_NRF51822 /* DFU only supported on nrf51 platforms */ + #ifndef __BLE_DFU_SERVICE_H__ #define __BLE_DFU_SERVICE_H__ #include "ble/BLE.h" #include "ble/UUID.h" -extern "C" void bootloader_start(void); +extern "C" { +#include "dfu_app_handler.h" +} extern const uint8_t DFUServiceBaseUUID[]; extern const uint16_t DFUServiceShortUUID; @@ -101,7 +105,15 @@ handoverCallback(); } - bootloader_start(); + // Call bootloader_start implicitly trough a event handler call + // it is a work around for bootloader_start not being public in sdk 8.1 + ble_dfu_t p_dfu; + ble_dfu_evt_t p_evt; + + p_dfu.conn_handle = params->connHandle; + p_evt.ble_dfu_evt_type = BLE_DFU_START; + + dfu_app_on_dfu_evt(&p_dfu, &p_evt); } } @@ -130,4 +142,5 @@ static ResetPrepare_t handoverCallback; /**< Application-specific handover callback. */ }; -#endif /* #ifndef __BLE_DFU_SERVICE_H__*/ \ No newline at end of file +#endif /* #ifndef __BLE_DFU_SERVICE_H__*/ +#endif /* #ifdef TARGET_NRF51822 */ \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ble/services/EddystoneConfigService.h Mon Jan 11 08:51:32 2016 +0000 @@ -0,0 +1,542 @@ +/* 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_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ +#define SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ + +#warning ble/services/EddystoneConfigService.h is deprecated. Please use the example in 'github.com/ARMmbed/ble-examples/tree/master/BLE_EddystoneService'. + +#include "mbed.h" +#include "ble/BLE.h" +#include "ble/services/EddystoneService.h" + +#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. 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 + */ + enum { + TX_POWER_MODE_LOWEST, + TX_POWER_MODE_LOW, + TX_POWER_MODE_MEDIUM, + TX_POWER_MODE_HIGH, + NUM_POWER_MODES + }; + + 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 int8_t PowerLevels_t[NUM_POWER_MODES]; + + // There are currently three subframes defined: URI, UID, and TLM. +#define EDDYSTONE_MAX_FRAMETYPE 3 + static const unsigned URI_DATA_MAX = 18; + typedef uint8_t UriData_t[URI_DATA_MAX]; + + // UID Frame Type subfields. + 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; + 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 14B. + 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 seconds. + // URI Frame Data + 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 seconds. + }; + + /** + * @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 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; + + lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback); + unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback); + uriDataChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::uriDataWriteAuthorizationCallback); + flagsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>); + advPowerLevelsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<PowerLevels_t>); + txPowerModeChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::powerModeAuthorizationCallback); + beaconPeriodChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint16_t>); + resetChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>); + + 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); + 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(); + } + + setupEddystoneConfigAdvertisements(); /* Set up advertising for the config service. */ + initSucceeded = true; + } + + /* + * Check if Eddystone initialized successfully. + */ + bool initSuccessfully(void) const { + return initSucceeded; + } + + /* + * @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, 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 = 0x8000; + TlmPduCount = 0; + TlmTimeSinceBoot = 0; + defaultTlmAdvPeriod = advPeriodInSec; + tlmIsSet = true; // Flag to add this to Eddystone service when config is done. + } + + /* + * @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, 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; + } + 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. + } + + /* + * @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. + * @param[in] advPeriod How long to advertise the URL, 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 config service for a limited time after + * startup, then switch to the normal non-connectible beacon functionality. + */ + void setupEddystoneConfigAdvertisements() { + const char DEVICE_NAME[] = "eddystone Config"; + + ble.clearAdvertisingPayload(); + + ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); + + // UUID is in a 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<const uint8_t *>(&DEVICE_NAME), sizeof(DEVICE_NAME)); + ble.accumulateScanResponse( + GapAdvertisingData::TX_POWER_LEVEL, + reinterpret_cast<uint8_t *>(&defaultAdvPowerLevels[EddystoneConfigService::TX_POWER_MODE_LOW]), + sizeof(uint8_t)); + + ble.setTxPower(radioPowerLevels[params.txPowerMode]); + ble.setDeviceName(reinterpret_cast<const uint8_t *>(&DEVICE_NAME)); + ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); + ble.setAdvertisingInterval(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.") + // Set up Eddystone Service. + static EddystoneService eddyServ(ble, params.beaconPeriod, radioPowerLevels[params.txPowerMode]); + // Set configured frames (TLM, UID, URI and so on). + if (params.tlmEnabled) { + eddyServ.setTLMFrameData(params.tlmVersion, params.tlmBeaconPeriod); + } + if (params.uriEnabled) { + eddyServ.setURLFrameEncodedData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriDataLength, 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, writeParams->len); // 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<uint8_t *>(¶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 = (uint16_t) defaultUriAdvPeriod * 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); + ble.updateCharacteristicValue(flagsChar.getValueHandle(), ¶ms.flags, 1); + ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), + reinterpret_cast<uint8_t *>(¶ms.beaconPeriod), sizeof(uint16_t)); + ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); + ble.updateCharacteristicValue(advPowerLevelsChar.getValueHandle(), + reinterpret_cast<uint8_t *>(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 <typename T> + 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<uint8_t> lockedStateChar; + WriteOnlyGattCharacteristic<Lock_t> lockChar; + GattCharacteristic uriDataChar; + WriteOnlyGattCharacteristic<Lock_t> unlockChar; + ReadWriteGattCharacteristic<uint8_t> flagsChar; + ReadWriteGattCharacteristic<PowerLevels_t> advPowerLevelsChar; + ReadWriteGattCharacteristic<uint8_t> txPowerModeChar; + ReadWriteGattCharacteristic<uint16_t> beaconPeriodChar; + WriteOnlyGattCharacteristic<uint8_t> resetChar; +}; + +#endif // SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_ \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ble/services/EddystoneService.h Mon Jan 11 08:51:32 2016 +0000 @@ -0,0 +1,653 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-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. + */ + +#ifndef SERVICES_EDDYSTONEBEACON_H_ +#define SERVICES_EDDYSTONEBEACON_H_ + +#warning ble/services/EddystoneService.h is deprecated. Please use the example in 'github.com/ARMmbed/ble-examples/tree/master/BLE_EddystoneService'. + +#include "ble/BLE.h" +#include "mbed.h" +#include "CircularBuffer.h" +static const uint8_t BEACON_EDDYSTONE[] = {0xAA, 0xFE}; + +//Debug is disabled by default +#if 0 +#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 // if 0 + +#if 0 +#define INFO(x, ...) printf("[EddyStone: INFO]"x " \t[%s,%d]\r\n", \ + ## __VA_ARGS__, \ + __FILE__, \ + __LINE__); +#else // if 0 +#define INFO(x, ...) +#endif // if 0 + +/** +* @class Eddystone +* @brief Eddystone Configuration Service. Can be used to set URL, adjust power levels, and set flags. +* See https://github.com/google/eddystone +* +*/ +class EddystoneService +{ +public: + enum FrameTypes { + NONE, + url, + uid, + tlm + }; + + 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); + static const int URI_DATA_MAX = 18; + typedef uint8_t UriData_t[URI_DATA_MAX]; + CircularBuffer<FrameTypes, EDDYSTONE_MAX_FRAMETYPE> overflow; + + // 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 + + /** + * 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, + float uidAdvPeriodIn, + uint16_t RFU = 0x0000) { + if (0.0f == uidAdvPeriodIn) { + uidIsSet = false; + return; + } + if (power > 20) { + power = 20; + } + 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 doesn't really matter yet. + uidAdvPeriod = uidAdvPeriodIn; + 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 empty space is available to write to + * @return number of bytes used. negative number indicates error message. + */ + unsigned constructUIDFrame(uint8_t *Data, uint8_t maxSize) { + unsigned index = 0; + + Data[index++] = FRAME_TYPE_UID; // 1B Type + + if (defaultUidPower > 20) { + defaultUidPower = 20; // enforce range of vaild values. + } + if (defaultUidPower < -100) { + defaultUidPower = -100; + } + Data[index++] = defaultUidPower; // 1B Power @ 0meter + + DBG("UID NamespaceID = '0x"); + for (size_t x = 0; x < UID_NAMESPACEID_SIZE; x++) { // 10B Namespace ID + Data[index++] = defaultUidNamespaceID[x]; + DBG("%x,", defaultUidNamespaceID[x]); + } + DBG("'\r\n"); + + 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("'\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); + } + 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[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, float urlAdvPeriodIn) { + if (0.0f == urlAdvPeriodIn) { + urlIsSet = false; + return false; + } + encodeURL(urlIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting + if (defaultUriDataLength > URI_DATA_MAX) { + return true; // error, URL is too big + } + defaultUrlPower = power; + urlAdvPeriod = urlAdvPeriodIn; + urlIsSet = true; + return false; + } + + /** + * Set Eddystone URL Frame information. + * @param[in] power TX Power in dB measured at 0 meters from the device. + * @param[in] encodedUrlIn Encoded URL + * @param[in] encodedUrlInLength Length of the encoded URL + * @param[in] urlAdvPeriodIn How long to advertise the URL frame (measured in # of adv periods) + * @return false on success, true on failure. + */ + bool setURLFrameEncodedData(int8_t power, const char *encodedUrlIn, uint8_t encodedUrlInLength, float urlAdvPeriodIn) { + if (0.0f == urlAdvPeriodIn) { + urlIsSet = false; + return false; + } + memcpy(defaultUriData, encodedUrlIn, encodedUrlInLength); + if (defaultUriDataLength > URI_DATA_MAX) { + return true; // error, URL is too big + } + defaultUrlPower = power; + defaultUriDataLength = encodedUrlInLength; + urlAdvPeriod = urlAdvPeriodIn; + urlIsSet = true; + return false; + } + + /* + * Construct URL 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 + * @return number of bytes used. negative number indicates error message. + */ + 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 + Data[index++] = defaultUriData[x]; + } + DBG("constructURLFrame: %d, %d", maxSize, index); + return index; + } + + /* + * 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 = 0, + float advPeriod = 60.0f, + uint16_t batteryVoltage = 0, + uint16_t beaconTemp = 0x8000, + uint32_t pduCount = 0, + uint32_t timeSinceBoot = 0) { + if (0.0f == 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 + } + + /* + * Construct TLM 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 + * @return number of bytes used. negative number indicates error message. + */ + int constructTLMFrame(uint8_t *Data, uint8_t maxSize) { + uint32_t now = timeSinceBootTimer.read_ms(); + TlmTimeSinceBoot += (now - lastBootTimerRead) / 100; + lastBootTimerRead = now; + + 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); + return index; + } + + /* + * Update the TLM frame battery voltage value + * @param[in] voltagemv Voltage to update the TLM field battery voltage with (in mV) + * @return nothing + */ + void updateTlmBatteryVoltage(uint16_t voltagemv) { + TlmBatteryVoltage = voltagemv; + } + + /* + * Update the TLM frame beacon temperature + * @param[in] temp Temperature of beacon (in 8.8fpn) + * @return nothing + */ + void updateTlmBeaconTemp(uint16_t temp) { + TlmBeaconTemp = temp; + } + + /* + * Update the TLM frame PDU Count field + * @param[in] pduCount Number of Advertisiting frames sent since powerup + * @return nothing + */ + void updateTlmPduCount(uint32_t pduCount) { + TlmPduCount = pduCount; + } + + /* + * Update the TLM frame Time since boot in 0.1s incriments + * @param[in] timeSinceBoot Time since boot in 0.1s incriments + * @return nothing + */ + void updateTlmTimeSinceBoot(uint32_t timeSinceBoot) { + TlmTimeSinceBoot = timeSinceBoot; + } + + /* + * Update advertising data + * @return true on success, false on failure + */ + bool updateAdvPacket(uint8_t serviceData[], unsigned serviceDataLen) { + // Fields from the Service + DBG("Updating AdvFrame: %d", serviceDataLen); + + 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; + } + + /* + * State machine for switching out frames. + * This function is called by the radioNotificationCallback when a frame needs to get swapped out. + * This function exists because of time constraints in the radioNotificationCallback, so it is effectively + * broken up into two functions. + */ + void swapOutFrames(FrameTypes frameType) { + uint8_t serviceData[SERVICE_DATA_MAX]; + unsigned serviceDataLen = 0; + //hard code in the eddystone UUID + serviceData[serviceDataLen++] = BEACON_EDDYSTONE[0]; + serviceData[serviceDataLen++] = BEACON_EDDYSTONE[1]; + + // if certain frames are not enabled, then skip them. Worst case TLM is always enabled + 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) { + 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; + } + break; + case uid: + // UID Frame + if (uidIsSet) { + 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; + } + 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); + } + } + + /* + * 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); + } + } + + /* + * 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); + } + } + + 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); + } + } + + /* + * Callback from onRadioNotification(), used to update the PDUCounter and process next state. + */ +#define EDDYSTONE_SWAPFRAME_DELAYMS 1 + void radioNotificationCallback(bool radioActive) { + // Update PDUCount + TlmPduCount++; + // True just before an frame is sent, false just after a frame is sent + if (radioActive) { + // Do Nothing + } else { + // Packet has been sent, disable advertising + stopAdv.attach_us(this, &EddystoneService::stopAdvCallback, 1); + } + } + + /* + * This function explicityly sets the parameters used by the Eddystone beacon. + * this function should be used in leu of the config service. + * + * @param bleIn ble object used to broadcast eddystone information + * @param beaconPeriodus is how often ble broadcasts are mde, in mili seconds + * @param txPowerLevel sets the broadcasting power level. + * + */ + EddystoneService(BLEDevice &bleIn, + 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, (float) advPeriodus / 1000.0f); + DBG("attached urlCallback every %d seconds", urlAdvPeriod); + } + if (uidIsSet) { + frameIndex = uid; + uidTicker.attach(this, &EddystoneService::uidCallback, uidAdvPeriod); + DBG("attached uidCallback every %d seconds", uidAdvPeriod); + } + if (tlmIsSet) { + frameIndex = tlm; + // Make double sure the PDUCount and TimeSinceBoot fields are set to zero at reset + updateTlmPduCount(0); + updateTlmTimeSinceBoot(0); + lastBootTimerRead = 0; + timeSinceBootTimer.start(); + 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.gap().onRadioNotification(this, &EddystoneService::radioNotificationCallback); + } + +private: + + // Eddystone Variables + BLEDevice &ble; + uint16_t advPeriodus; + uint8_t txPower; + Timer timeSinceBootTimer; + volatile uint32_t lastBootTimerRead; + 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 + float urlAdvPeriod; // how long the url frame will be advertised for + Ticker urlTicker; + + // UID Frame Variables + UIDNamespaceID_t defaultUidNamespaceID; + UIDInstanceID_t defaultUidInstanceID; + int8_t defaultUidPower; + uint16_t uidRFU; + bool uidIsSet; // flag that enables / disable UID Frames + float uidAdvPeriod; // how long the uid frame will be advertised for + Ticker uidTicker; + + // 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 + float 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, uint8_t &sizeofURIDataOut) { + DBG("Encode URL = %s", uriDataIn); + const char *prefixes[] = { + "http://www.", + "https://www.", + "http://", + "https://", + }; + const size_t NUM_PREFIXES = sizeof(prefixes) / sizeof(char *); + const char *suffixes[] = { + ".com/", + ".org/", + ".edu/", + ".net/", + ".info/", + ".biz/", + ".gov/", + ".com", + ".org", + ".edu", + ".net", + ".info", + ".biz", + ".gov" + }; + const size_t NUM_SUFFIXES = sizeof(suffixes) / sizeof(char *); + + sizeofURIDataOut = 0; + memset(uriDataOut, 0, sizeof(UriData_t)); + + if ((uriDataIn == NULL) || (strlen(uriDataIn) == 0)) { + return; + } + + /* + * handle prefix + */ + for (unsigned i = 0; i < NUM_PREFIXES; i++) { + size_t prefixLen = strlen(prefixes[i]); + if (strncmp(uriDataIn, prefixes[i], prefixLen) == 0) { + uriDataOut[sizeofURIDataOut++] = i; + uriDataIn += prefixLen; + break; + } + } + + /* + * handle suffixes + */ + while (*uriDataIn && (sizeofURIDataOut < URI_DATA_MAX)) { + /* check for suffix match */ + unsigned i; + for (i = 0; i < NUM_SUFFIXES; i++) { + size_t suffixLen = strlen(suffixes[i]); + if (strncmp(uriDataIn, suffixes[i], suffixLen) == 0) { + uriDataOut[sizeofURIDataOut++] = i; + uriDataIn += suffixLen; + break; /* from the for loop for checking against suffixes */ + } + } + /* 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; + } + } + } +}; + +#endif // SERVICES_EDDYSTONEBEACON_H_ \ No newline at end of file
--- a/ble/services/LinkLossService.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/services/LinkLossService.h Mon Jan 11 08:51:32 2016 +0000 @@ -21,9 +21,9 @@ /** * @class LinkLossService -* @brief This service defines behavior when a link is lost between two devices. <br> -* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.link_loss.xml <br> -* Alertness Level Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.alert_level.xml <br> +* @brief This service defines behavior when a link is lost between two devices. +* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.link_loss.xml +* Alertness Level Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.alert_level.xml */ class LinkLossService { public: @@ -67,7 +67,7 @@ } /** - * Update Alertness Level. + * Update alertness level. */ void setAlertLevel(AlertLevel_t newLevel) { alertLevel = newLevel; @@ -75,7 +75,7 @@ protected: /** - * This callback allows receiving updates to the AlertLevel Characteristic. + * This callback allows receiving updates to the AlertLevel characteristic. * * @param[in] params * Information about the characterisitc being updated.
--- a/ble/services/UARTService.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/services/UARTService.h Mon Jan 11 08:51:32 2016 +0000 @@ -40,12 +40,12 @@ extern const uint8_t UARTServiceRXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID]; /** -* @class UARTService -* @brief BLE Service to enable UART over BLE +* @class UARTService. +* @brief BLE Service to enable UART over BLE. */ class UARTService { public: - /**< Maximum length of data (in bytes) that can be transmitted by the UART service module to the peer. */ + /**< Maximum length of data (in bytes) that the UART service module can transmit to the peer. */ static const unsigned BLE_UART_SERVICE_MAX_DATA_LEN = (BLE_GATT_MTU_SIZE_DEFAULT - 3); public: @@ -87,20 +87,20 @@ /** * We attempt to collect bytes before pushing them to the UART RX - * characteristic--writing to the RX characteristic will then generate + * characteristic; writing to the RX characteristic then generates * notifications for the client. Updates made in quick succession to a - * notification-generating characteristic will result in data being buffered - * in the bluetooth stack as notifications are sent out. The stack will have - * its limits for this buffering; typically a small number under 10. + * notification-generating characteristic result in data being buffered + * in the Bluetooth stack as notifications are sent out. The stack has + * its limits for this buffering - typically a small number under 10. * Collecting data into the sendBuffer buffer helps mitigate the rate of * updates. But we shouldn't buffer a large amount of data before updating - * the characteristic otherwise the client will need to turn around and make + * the characteristic, otherwise the client needs to turn around and make * a long read request; this is because notifications include only the first * 20 bytes of the updated data. * - * @param buffer The received update - * @param length Amount of characters to be appended. - * @return Amount of characters appended to the rxCharacteristic. + * @param buffer The received update. + * @param length Number of characters to be appended. + * @return Number of characters appended to the rxCharacteristic. */ size_t write(const void *_buffer, size_t length) { size_t origLength = length; @@ -112,13 +112,13 @@ unsigned bytesRemainingInSendBuffer = BLE_UART_SERVICE_MAX_DATA_LEN - sendBufferIndex; unsigned bytesToCopy = (length < bytesRemainingInSendBuffer) ? length : bytesRemainingInSendBuffer; - /* copy bytes into sendBuffer */ + /* Copy bytes into sendBuffer. */ memcpy(&sendBuffer[sendBufferIndex], &buffer[bufferIndex], bytesToCopy); length -= bytesToCopy; sendBufferIndex += bytesToCopy; bufferIndex += bytesToCopy; - /* have we collected enough? */ + /* Have we collected enough? */ if ((sendBufferIndex == BLE_UART_SERVICE_MAX_DATA_LEN) || // (sendBuffer[sendBufferIndex - 1] == '\r') || (sendBuffer[sendBufferIndex - 1] == '\n')) { @@ -134,14 +134,14 @@ /** * Helper function to write out strings. * @param str The received string. - * @return Amount of characters appended to the rxCharacteristic. + * @return Number of characters appended to the rxCharacteristic. */ size_t writeString(const char *str) { return write(str, strlen(str)); } /** - * Override for Stream::_putc() + * Override for Stream::_putc(). * @param c * This function writes the character c, cast to an unsigned char, to stream. * @return @@ -152,7 +152,7 @@ } /** - * Override for Stream::_getc() + * Override for Stream::_getc(). * @return * The character read. */ @@ -168,7 +168,7 @@ /** * This callback allows the UART service to receive updates to the * txCharacteristic. The application should forward the call to this - * function from the global onDataWritten() callback handler; or if that's + * function from the global onDataWritten() callback handler; if that's * not used, this method can be used as a callback directly. */ void onDataWritten(const GattWriteCallbackParams *params) {
--- a/ble/services/URIBeaconConfigService.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/services/URIBeaconConfigService.h Mon Jan 11 08:51:32 2016 +0000 @@ -47,18 +47,18 @@ class URIBeaconConfigService { public: /** - * @brief Transmission Power Modes for UriBeacon + * @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 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 + static const int 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]; static const int URI_DATA_MAX = 18; @@ -69,8 +69,8 @@ uint8_t uriDataLength; UriData_t uriData; uint8_t flags; - PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels - uint8_t txPowerMode; // Firmware power levels used with setTxPower() + PowerLevels_t advPowerLevels; // Current value of AdvertisedPowerLevels. + uint8_t txPowerMode; // Firmware power levels used with setTxPower(). uint16_t beaconPeriod; }; @@ -86,9 +86,9 @@ * un-initialized, and default values should be used * instead. Otherwise, paramsIn overrides the defaults. * @param[in] defaultUriDataIn - * Default un-encoded URI; applies only if the resetToDefaultsFlag is true. + * Default un-encoded URI. Applies only if the resetToDefaultsFlag is true. * @param[in] defaultAdvPowerLevelsIn - * Default power-levels array; applies only if the resetToDefaultsFlag is true. + * Default power-levels array. Applies only if the resetToDefaultsFlag is true. */ URIBeaconConfigService(BLE &bleIn, Params_t ¶msIn, @@ -148,7 +148,7 @@ ble.addService(configService); ble.onDataWritten(this, &URIBeaconConfigService::onDataWrittenCallback); - setupURIBeaconConfigAdvertisements(); /* Setup advertising for the configService. */ + setupURIBeaconConfigAdvertisements(); /* Set up advertising for the config service. */ initSucceeded = true; } @@ -157,9 +157,9 @@ return initSucceeded; } - /* Start out by advertising the configService for a limited time after - * startup; and switch to the normal non-connectible beacon functionality - * afterwards. */ + /* Start out by advertising the config service for a limited time after + * startup. Then switch to the normal non-connectible beacon functionality. + */ void setupURIBeaconConfigAdvertisements() { const char DEVICE_NAME[] = "mUriBeacon Config"; @@ -186,14 +186,14 @@ ble.gap().setAdvertisingInterval(GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(ADVERTISING_INTERVAL_MSEC)); } - /* Helper function to switch to the non-connectible normal mode for URIBeacon. This gets called after a timeout. */ + /* Helper function to switch to the non-connectible normal mode for UriBeacon. This gets called after a timeout. */ void setupURIBeaconAdvertisements() { /* Reinitialize the BLE stack. This will clear away the existing services and advertising state. */ ble.shutdown(); ble.init(); - // Fields from the Service + // Fields from the service. unsigned beaconPeriod = params.beaconPeriod; unsigned txPowerMode = params.txPowerMode; unsigned uriDataLength = params.uriDataLength; @@ -201,7 +201,7 @@ URIBeaconConfigService::PowerLevels_t &advPowerLevels = params.advPowerLevels; uint8_t flags = params.flags; - extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */ + extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* Forward declaration; necessary to avoid a circular dependency. */ saveURIBeaconConfigParams(¶ms); ble.gap().clearAdvertisingPayload(); @@ -224,7 +224,7 @@ } private: - // True if the lock bits are non-zero + // True if the lock bits are non-zero. bool isLocked() { Lock_t testLock; memset(testLock, 0, sizeof(Lock_t)); @@ -233,19 +233,19 @@ /* * 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 + * characteristics of this service. These attempts 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 + // Validated earlier, memcpy(params.lock, writeParams->data, sizeof(Lock_t)); - // use isLocked() in case bits are being set to all 0's + // Use isLocked() in case bits are being set to all zeros. lockedState = isLocked(); } else if (handle == unlockChar.getValueHandle()) { - // Validated earlier + // Validated earlier. memset(params.lock, 0, sizeof(Lock_t)); lockedState = false; } else if (handle == uriDataChar.getValueHandle()) { @@ -260,7 +260,7 @@ } else if (handle == beaconPeriodChar.getValueHandle()) { params.beaconPeriod = *((uint16_t *)(writeParams->data)); - /* Re-map beaconPeriod to within permissible bounds if necessary. */ + /* Remap beaconPeriod to within permissible bounds if necessary. */ if (params.beaconPeriod != 0) { bool paramsUpdated = false; if (params.beaconPeriod < ble.gap().getMinAdvertisingInterval()) { @@ -378,9 +378,9 @@ BLE &ble; Params_t ¶ms; - size_t defaultUriDataLength; // Default value that is restored on reset - UriData_t defaultUriData; // Default value that is restored on reset - PowerLevels_t &defaultAdvPowerLevels; // Default value that is restored on reset + size_t defaultUriDataLength; // Default value that is restored on reset. + UriData_t defaultUriData; // Default value that is restored on reset. + PowerLevels_t &defaultAdvPowerLevels; // Default value that is restored on reset. uint8_t lockedState; bool initSucceeded; @@ -398,7 +398,7 @@ public: /* - * Encode a human-readable URI into the binary format defined by URIBeacon spec (https://github.com/google/uribeacon/tree/master/specification). + * Encode a human-readable URI into the binary format defined by the UriBeacon spec (https://github.com/google/uribeacon/tree/master/specification). */ static void encodeURI(const char *uriDataIn, UriData_t uriDataOut, size_t &sizeofURIDataOut) { const char *prefixes[] = { @@ -447,7 +447,7 @@ } /* - * handle suffixes + * Handle suffixes. */ while (*uriDataIn && (sizeofURIDataOut < URI_DATA_MAX)) { /* check for suffix match */ @@ -457,10 +457,10 @@ if (strncmp(uriDataIn, suffixes[i], suffixLen) == 0) { uriDataOut[sizeofURIDataOut++] = i; uriDataIn += suffixLen; - break; /* from the for loop for checking against suffixes */ + break; /* From the for loop for checking against suffixes. */ } } - /* This is the default case where we've got an ordinary character which doesn't match a suffix. */ + /* This is the default case where we've got an ordinary character that doesn't match a suffix. */ if (i == NUM_SUFFIXES) { uriDataOut[sizeofURIDataOut++] = *uriDataIn; ++uriDataIn;
--- a/ble/services/iBeacon.h Mon Jan 11 08:51:31 2016 +0000 +++ b/ble/services/iBeacon.h Mon Jan 11 08:51:32 2016 +0000 @@ -21,7 +21,7 @@ /** * @class iBeacon -* @brief iBeacon Service. This sets up a device to broadcast advertising packets to mimic an iBeacon<br> +* @brief iBeacon Service. This sets up a device to broadcast advertising packets to mimic an iBeacon. */ class iBeacon { @@ -56,12 +56,12 @@ uint16_t compID = 0x004C) : ble(_ble), data(uuid, majNum, minNum, txP, compID) { - // Generate the 0x020106 part of the iBeacon Prefix + // Generate the 0x020106 part of the iBeacon Prefix. ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE ); - // Generate the 0x1AFF part of the iBeacon Prefix + // Generate the 0x1AFF part of the iBeacon Prefix. ble.accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, data.raw, sizeof(data.raw)); - // Set advertising type + // Set advertising type. ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); }
--- a/module.json Mon Jan 11 08:51:31 2016 +0000 +++ b/module.json Mon Jan 11 08:51:32 2016 +0000 @@ -1,6 +1,6 @@ { "name": "ble", - "version": "2.1.0", + "version": "2.1.5", "description": "The BLE module offers a high level abstraction for using Bluetooth Low Energy on multiple platforms.", "keywords": [ "Bluetooth", @@ -26,7 +26,7 @@ "x-nucleo-idb0xa1": "ARMmbed/ble-x-nucleo-idb0xa1" }, "nrf51822": { - "ble-nrf51822": "^2.0.0" + "ble-nrf51822": "^2.1.1" }, "cordio": { "ble-wicentric": "~0.0.4"
--- a/source/DiscoveredCharacteristic.cpp Mon Jan 11 08:51:31 2016 +0000 +++ b/source/DiscoveredCharacteristic.cpp Mon Jan 11 08:51:32 2016 +0000 @@ -151,17 +151,8 @@ return error; } -ble_error_t DiscoveredCharacteristic::discoverDescriptors( - const CharacteristicDescriptorDiscovery::DiscoveryCallback_t& onCharacteristicDiscovered, - const CharacteristicDescriptorDiscovery::TerminationCallback_t& onTermination) const { - - if(!gattc) { - return BLE_ERROR_INVALID_STATE; - } - - ble_error_t err = gattc->discoverCharacteristicDescriptors( - *this, onCharacteristicDiscovered, onTermination - ); - - return err; +ble_error_t +DiscoveredCharacteristic::discoverDescriptors(DescriptorCallback_t callback, const UUID &matchingUUID) const +{ + return BLE_ERROR_NOT_IMPLEMENTED; /* TODO: this needs to be filled in. */ } \ No newline at end of file
--- a/source/services/DFUService.cpp Mon Jan 11 08:51:31 2016 +0000 +++ b/source/services/DFUService.cpp Mon Jan 11 08:51:32 2016 +0000 @@ -14,6 +14,8 @@ * limitations under the License. */ +#ifdef TARGET_NRF51822 /* DFU only supported on nrf51 platforms */ + #include "ble/services/DFUService.h" const uint8_t DFUServiceBaseUUID[] = { @@ -37,4 +39,6 @@ 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, }; -DFUService::ResetPrepare_t DFUService::handoverCallback = NULL; \ No newline at end of file +DFUService::ResetPrepare_t DFUService::handoverCallback = NULL; + +#endif /* #ifdef TARGET_NRF51822 */ \ No newline at end of file