High level Bluetooth Low Energy API and radio abstraction layer
Fork of BLE_API by
Revision 1209:e3d4f8c7787b, committed 2017-02-22
- Comitter:
- VicenteFerrara
- Date:
- Wed Feb 22 23:25:59 2017 +0000
- Parent:
- 1208:65474dc93927
- Commit message:
- a
Changed in this revision
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/BatteryService.h --- a/ble/services/BatteryService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,77 +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 __BLE_BATTERY_SERVICE_H__ -#define __BLE_BATTERY_SERVICE_H__ - -#include "ble/BLE.h" - -/** -* @class BatteryService -* @brief BLE Battery Service. This service displays the battery level from 0% to 100%, represented as an 8bit number. -* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.battery_service.xml -* Battery Level Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.battery_level.xml -*/ -class BatteryService { -public: - /** - * @param[in] _ble - * BLE object for the underlying controller. - * @param[in] level - * 8bit batterly level. Usually used to represent percentage of batterly charge remaining. - */ - BatteryService(BLE &_ble, uint8_t level = 100) : - ble(_ble), - batteryLevel(level), - batteryLevelCharacteristic(GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, &batteryLevel, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) { - - GattCharacteristic *charTable[] = {&batteryLevelCharacteristic}; - GattService batteryService(GattService::UUID_BATTERY_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(batteryService); - } - - /** - * @brief Update the battery level with a new value. Valid values lie between 0 and 100, - * anything outside this range will be ignored. - * - * @param newLevel - * Update to battery level. - */ - void updateBatteryLevel(uint8_t newLevel) { - batteryLevel = newLevel; - ble.gattServer().write(batteryLevelCharacteristic.getValueHandle(), &batteryLevel, 1); - } - -protected: - /** - * A reference to the underlying BLE instance that this object is attached to. - * The services and characteristics will be registered in this BLE instance. - */ - BLE &ble; - - /** - * The current battery level represented as an integer from 0% to 100%. - */ - uint8_t batteryLevel; - /** - * A ReadOnlyGattCharacteristic that allows access to the peer device to the - * batteryLevel value through BLE. - */ - ReadOnlyGattCharacteristic<uint8_t> batteryLevelCharacteristic; -}; - -#endif /* #ifndef __BLE_BATTERY_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/DFUService.h --- a/ble/services/DFUService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,146 +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. - */ - -#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" { -#include "dfu_app_handler.h" -} - -extern const uint8_t DFUServiceBaseUUID[]; -extern const uint16_t DFUServiceShortUUID; -extern const uint16_t DFUServiceControlCharacteristicShortUUID; - -extern const uint8_t DFUServiceUUID[]; -extern const uint8_t DFUServiceControlCharacteristicUUID[]; -extern const uint8_t DFUServicePacketCharacteristicUUID[]; - -/** -* @class DFUService -* @brief Device Firmware Update Service. -*/ -class DFUService { -public: - /** - * @brief Signature for the handover callback. The application may provide this - * callback when setting up the DFU service. The callback is then - * invoked before handing control over to the bootloader. - */ - typedef void (*ResetPrepare_t)(void); - -public: - /** - * @brief Adds Device Firmware Update Service to an existing BLE object. - * - * @param[ref] _ble - * BLE object for the underlying controller. - * @param[in] _handoverCallback - * Application-specific handover callback. - */ - DFUService(BLE &_ble, ResetPrepare_t _handoverCallback = NULL) : - ble(_ble), - controlPoint(DFUServiceControlCharacteristicUUID, controlBytes, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - packet(DFUServicePacketCharacteristicUUID, packetBytes, SIZEOF_PACKET_BYTES, SIZEOF_PACKET_BYTES, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), - controlBytes(), - packetBytes() { - static bool serviceAdded = false; /* We only add the DFU service once. */ - if (serviceAdded) { - return; - } - - /* Set an initial value for control bytes, so that the application's DFU service can - * be distinguished from the real DFU service provided by the bootloader. */ - controlBytes[0] = 0xFF; - controlBytes[1] = 0xFF; - - GattCharacteristic *dfuChars[] = {&controlPoint, &packet}; - GattService dfuService(DFUServiceUUID, dfuChars, sizeof(dfuChars) / sizeof(GattCharacteristic *)); - - ble.addService(dfuService); - handoverCallback = _handoverCallback; - serviceAdded = true; - - ble.onDataWritten(this, &DFUService::onDataWritten); - } - - /** - * @brief Get the handle for the value attribute of the control characteristic. - */ - uint16_t getControlHandle(void) const { - return controlPoint.getValueHandle(); - } - - /** - * @brief This callback allows the DFU service to receive the initial trigger to - * hand control over to the bootloader. First, the application is given a - * chance to clean up. - * - * @param[in] params - * Information about the characterisitc being updated. - */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == controlPoint.getValueHandle()) { - /* At present, writing anything will do the trick - this needs to be improved. */ - if (handoverCallback) { - handoverCallback(); - } - - // 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); - } - } - -protected: - static const unsigned SIZEOF_CONTROL_BYTES = 2; - static const unsigned SIZEOF_PACKET_BYTES = 20; - -protected: - BLE &ble; - - /**< Writing to the control characteristic triggers the handover to DFU - * bootloader. At present, writing anything will do the trick - this needs - * to be improved. */ - WriteOnlyArrayGattCharacteristic<uint8_t, SIZEOF_CONTROL_BYTES> controlPoint; - - /**< The packet characteristic in this service doesn't do anything meaningful; - * it is only a placeholder to mimic the corresponding characteristic in the - * actual DFU service implemented by the bootloader. Without this, some - * FOTA clients might get confused, because service definitions change after - * handing control over to the bootloader. */ - GattCharacteristic packet; - - uint8_t controlBytes[SIZEOF_CONTROL_BYTES]; - uint8_t packetBytes[SIZEOF_PACKET_BYTES]; - - static ResetPrepare_t handoverCallback; /**< Application-specific handover callback. */ -}; - -#endif /* #ifndef __BLE_DFU_SERVICE_H__*/ -#endif /* #ifdef TARGET_NRF51822 */ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/DeviceInformationService.h --- a/ble/services/DeviceInformationService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,138 +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 __BLE_DEVICE_INFORMATION_SERVICE_H__ -#define __BLE_DEVICE_INFORMATION_SERVICE_H__ - -#include "ble/BLE.h" - -/** -* @class DeviceInformationService -* @brief BLE Device Information Service -* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.device_information.xml -* Manufacturer Name String Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.manufacturer_name_string.xml -*/ -class DeviceInformationService { -public: - /** - * @brief Device Information Service Constructor: copies device-specific information - * into the BLE stack. - * - * @param[in] _ble - * A reference to a BLE object for the underlying controller. - * @param[in] manufacturersName - * The name of the manufacturer of the device. - * @param[in] modelNumber - * The model number that is assigned by the device vendor. - * @param[in] serialNumber - * The serial number for a particular instance of the device. - * @param[in] hardwareRevision - * The hardware revision for the hardware within the device. - * @param[in] firmwareRevision - * The device's firmware version. - * @param[in] softwareRevision - * The device's software version. - */ - DeviceInformationService(BLE &_ble, - const char *manufacturersName = NULL, - const char *modelNumber = NULL, - const char *serialNumber = NULL, - const char *hardwareRevision = NULL, - const char *firmwareRevision = NULL, - const char *softwareRevision = NULL) : - ble(_ble), - manufacturersNameStringCharacteristic(GattCharacteristic::UUID_MANUFACTURER_NAME_STRING_CHAR, - (uint8_t *)manufacturersName, - (manufacturersName != NULL) ? strlen(manufacturersName) : 0, /* Min length */ - (manufacturersName != NULL) ? strlen(manufacturersName) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ), - modelNumberStringCharacteristic(GattCharacteristic::UUID_MODEL_NUMBER_STRING_CHAR, - (uint8_t *)modelNumber, - (modelNumber != NULL) ? strlen(modelNumber) : 0, /* Min length */ - (modelNumber != NULL) ? strlen(modelNumber) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ), - serialNumberStringCharacteristic(GattCharacteristic::UUID_SERIAL_NUMBER_STRING_CHAR, - (uint8_t *)serialNumber, - (serialNumber != NULL) ? strlen(serialNumber) : 0, /* Min length */ - (serialNumber != NULL) ? strlen(serialNumber) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ), - hardwareRevisionStringCharacteristic(GattCharacteristic::UUID_HARDWARE_REVISION_STRING_CHAR, - (uint8_t *)hardwareRevision, - (hardwareRevision != NULL) ? strlen(hardwareRevision) : 0, /* Min length */ - (hardwareRevision != NULL) ? strlen(hardwareRevision) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ), - firmwareRevisionStringCharacteristic(GattCharacteristic::UUID_FIRMWARE_REVISION_STRING_CHAR, - (uint8_t *)firmwareRevision, - (firmwareRevision != NULL) ? strlen(firmwareRevision) : 0, /* Min length */ - (firmwareRevision != NULL) ? strlen(firmwareRevision) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ), - softwareRevisionStringCharacteristic(GattCharacteristic::UUID_SOFTWARE_REVISION_STRING_CHAR, - (uint8_t *)softwareRevision, - (softwareRevision != NULL) ? strlen(softwareRevision) : 0, /* Min length */ - (softwareRevision != NULL) ? strlen(softwareRevision) : 0, /* Max length */ - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ) - { - static bool serviceAdded = false; /* We only add the information service once. */ - if (serviceAdded) { - return; - } - - GattCharacteristic *charTable[] = {&manufacturersNameStringCharacteristic, - &modelNumberStringCharacteristic, - &serialNumberStringCharacteristic, - &hardwareRevisionStringCharacteristic, - &firmwareRevisionStringCharacteristic, - &softwareRevisionStringCharacteristic}; - GattService deviceInformationService(GattService::UUID_DEVICE_INFORMATION_SERVICE, charTable, - sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(deviceInformationService); - serviceAdded = true; - } - -protected: - /** - * A reference to the BLE instance object to which the services and - * characteristics will be added. - */ - BLE &ble; - /** - * BLE characterising to allow BLE peers access to the manufacturer's name. - */ - GattCharacteristic manufacturersNameStringCharacteristic; - /** - * BLE characterising to allow BLE peers access to the model number. - */ - GattCharacteristic modelNumberStringCharacteristic; - /** - * BLE characterising to allow BLE peers access to the serial number. - */ - GattCharacteristic serialNumberStringCharacteristic; - /** - * BLE characterising to allow BLE peers access to the hardware revision string. - */ - GattCharacteristic hardwareRevisionStringCharacteristic; - /** - * BLE characterising to allow BLE peers access to the firmware revision string. - */ - GattCharacteristic firmwareRevisionStringCharacteristic; - /** - * BLE characterising to allow BLE peers access to the software revision string. - */ - GattCharacteristic softwareRevisionStringCharacteristic; -}; - -#endif /* #ifndef __BLE_DEVICE_INFORMATION_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/EddystoneConfigService.h --- a/ble/services/EddystoneConfigService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,542 +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 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
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/EddystoneService.h --- a/ble/services/EddystoneService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,653 +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 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
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/EnvironmentalService.h --- a/ble/services/EnvironmentalService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,106 +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 __BLE_ENVIRONMENTAL_SERVICE_H__ -#define __BLE_ENVIRONMENTAL_SERVICE_H__ - -#include "ble/BLE.h" - -/** -* @class EnvironmentalService -* @brief BLE Environmental Service. This service provides temperature, humidity and pressure measurement. -* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.environmental_sensing.xml -* Temperature: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature.xml -* Humidity: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.humidity.xml -* Pressure: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.pressure.xml -*/ -class EnvironmentalService { -public: - typedef int16_t TemperatureType_t; - typedef uint16_t HumidityType_t; - typedef uint32_t PressureType_t; - - /** - * @brief EnvironmentalService constructor. - * @param ble Reference to BLE device. - * @param temperature_en Enable this characteristic. - * @param humidity_en Enable this characteristic. - * @param pressure_en Enable this characteristic. - */ - EnvironmentalService(BLE& _ble) : - ble(_ble), - temperatureCharacteristic(GattCharacteristic::UUID_TEMPERATURE_CHAR, &temperature), - humidityCharacteristic(GattCharacteristic::UUID_HUMIDITY_CHAR, &humidity), - pressureCharacteristic(GattCharacteristic::UUID_PRESSURE_CHAR, &pressure) - { - static bool serviceAdded = false; /* We should only ever need to add the information service once. */ - if (serviceAdded) { - return; - } - - GattCharacteristic *charTable[] = { &humidityCharacteristic, - &pressureCharacteristic, - &temperatureCharacteristic }; - - GattService environmentalService(GattService::UUID_ENVIRONMENTAL_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.gattServer().addService(environmentalService); - serviceAdded = true; - } - - /** - * @brief Update humidity characteristic. - * @param newHumidityVal New humidity measurement. - */ - void updateHumidity(HumidityType_t newHumidityVal) - { - humidity = (HumidityType_t) (newHumidityVal * 100); - ble.gattServer().write(humidityCharacteristic.getValueHandle(), (uint8_t *) &humidity, sizeof(HumidityType_t)); - } - - /** - * @brief Update pressure characteristic. - * @param newPressureVal New pressure measurement. - */ - void updatePressure(PressureType_t newPressureVal) - { - pressure = (PressureType_t) (newPressureVal * 10); - ble.gattServer().write(pressureCharacteristic.getValueHandle(), (uint8_t *) &pressure, sizeof(PressureType_t)); - } - - /** - * @brief Update temperature characteristic. - * @param newTemperatureVal New temperature measurement. - */ - void updateTemperature(float newTemperatureVal) - { - temperature = (TemperatureType_t) (newTemperatureVal * 100); - ble.gattServer().write(temperatureCharacteristic.getValueHandle(), (uint8_t *) &temperature, sizeof(TemperatureType_t)); - } - -private: - BLE& ble; - - TemperatureType_t temperature; - HumidityType_t humidity; - PressureType_t pressure; - - ReadOnlyGattCharacteristic<TemperatureType_t> temperatureCharacteristic; - ReadOnlyGattCharacteristic<HumidityType_t> humidityCharacteristic; - ReadOnlyGattCharacteristic<PressureType_t> pressureCharacteristic; -}; - -#endif /* #ifndef __BLE_ENVIRONMENTAL_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/HealthThermometerService.h --- a/ble/services/HealthThermometerService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,150 +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 __BLE_HEALTH_THERMOMETER_SERVICE_H__ -#define __BLE_HEALTH_THERMOMETER_SERVICE_H__ - -#include "ble/BLE.h" - -/** -* @class HealthThermometerService -* @brief BLE Health Thermometer Service. This service provides the location of the thermometer and the temperature. -* Service: https://developer.bluetooth.org/gatt/profiles/Pages/ProfileViewer.aspx?u=org.bluetooth.profile.health_thermometer.xml -* Temperature Measurement: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature_measurement.xml -* Temperature Type: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature_type.xml -*/ -class HealthThermometerService { -public: - /** - * @enum Sensor Location. - * @brief Location of sensor on the body. - */ - enum SensorLocation_t { - LOCATION_ARMPIT = 1, /*!< Armpit. */ - LOCATION_BODY, /*!< Body. */ - LOCATION_EAR, /*!< Ear. */ - LOCATION_FINGER, /*!< Finger. */ - LOCATION_GI_TRACT, /*!< GI tract */ - LOCATION_MOUTH, /*!< Mouth. */ - LOCATION_RECTUM, /*!< Rectum. */ - LOCATION_TOE, /*!< Toe. */ - LOCATION_EAR_DRUM, /*!< Eardrum. */ - }; - -public: - /** - * @brief Add the Health Thermometer Service to an existing BLE object, initialize with temperature and location. - * @param[ref] _ble Reference to the BLE device. - * @param[in] initialTemp Initial value in celsius. - * @param[in] _location - */ - HealthThermometerService(BLE &_ble, float initialTemp, uint8_t _location) : - ble(_ble), - valueBytes(initialTemp), - tempMeasurement(GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, (TemperatureValueBytes *)valueBytes.getPointer(), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - tempLocation(GattCharacteristic::UUID_TEMPERATURE_TYPE_CHAR, &_location) { - - GattCharacteristic *hrmChars[] = {&tempMeasurement, &tempLocation, }; - GattService hrmService(GattService::UUID_HEALTH_THERMOMETER_SERVICE, hrmChars, sizeof(hrmChars) / sizeof(GattCharacteristic *)); - - ble.addService(hrmService); - } - - /** - * @brief Update the temperature being broadcast. - * - * @param[in] temperature - * Floating point value of the temperature. - * - */ - void updateTemperature(float temperature) { - if (ble.getGapState().connected) { - valueBytes.updateTemperature(temperature); - ble.gattServer().write(tempMeasurement.getValueHandle(), valueBytes.getPointer(), sizeof(TemperatureValueBytes)); - } - } - - /** - * @brief Update the location. - * @param loc - * New location value. - */ - void updateLocation(SensorLocation_t loc) { - ble.gattServer().write(tempLocation.getValueHandle(), reinterpret_cast<uint8_t *>(&loc), sizeof(uint8_t)); - } - -private: - /* Private internal representation for the bytes used to work with the vaulue of the temperature characteristic. */ - struct TemperatureValueBytes { - static const unsigned OFFSET_OF_FLAGS = 0; - static const unsigned OFFSET_OF_VALUE = OFFSET_OF_FLAGS + sizeof(uint8_t); - static const unsigned SIZEOF_VALUE_BYTES = sizeof(uint8_t) + sizeof(float); - - static const unsigned TEMPERATURE_UNITS_FLAG_POS = 0; - static const unsigned TIMESTAMP_FLAG_POS = 1; - static const unsigned TEMPERATURE_TYPE_FLAG_POS = 2; - - static const uint8_t TEMPERATURE_UNITS_CELSIUS = 0; - static const uint8_t TEMPERATURE_UNITS_FAHRENHEIT = 1; - - TemperatureValueBytes(float initialTemperature) : bytes() { - /* Assumption: temperature values are expressed in celsius */ - bytes[OFFSET_OF_FLAGS] = (TEMPERATURE_UNITS_CELSIUS << TEMPERATURE_UNITS_FLAG_POS) | - (false << TIMESTAMP_FLAG_POS) | - (false << TEMPERATURE_TYPE_FLAG_POS); - updateTemperature(initialTemperature); - } - - void updateTemperature(float temp) { - uint32_t temp_ieee11073 = quick_ieee11073_from_float(temp); - memcpy(&bytes[OFFSET_OF_VALUE], &temp_ieee11073, sizeof(float)); - } - - uint8_t *getPointer(void) { - return bytes; - } - - const uint8_t *getPointer(void) const { - return bytes; - } - -private: - /** - * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type. - * @param temperature The temperature as a float. - * @return The temperature in 11073-20601 FLOAT-Type format. - */ - uint32_t quick_ieee11073_from_float(float temperature) { - uint8_t exponent = 0xFE; //Exponent is -2 - uint32_t mantissa = (uint32_t)(temperature * 100); - - return (((uint32_t)exponent) << 24) | mantissa; - } - -private: - /* First byte: 8-bit flags. Second field is a float holding the temperature value. */ - /* See https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.temperature_measurement.xml */ - uint8_t bytes[SIZEOF_VALUE_BYTES]; - }; - -protected: - BLE &ble; - TemperatureValueBytes valueBytes; - ReadOnlyGattCharacteristic<TemperatureValueBytes> tempMeasurement; - ReadOnlyGattCharacteristic<uint8_t> tempLocation; -}; - -#endif /* #ifndef __BLE_HEALTH_THERMOMETER_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/HeartRateService.h --- a/ble/services/HeartRateService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,194 +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 __BLE_HEART_RATE_SERVICE_H__ -#define __BLE_HEART_RATE_SERVICE_H__ - -#include "ble/BLE.h" - -/** -* @class HeartRateService -* @brief BLE Service for HeartRate. This BLE Service contains the location of the sensor and the heart rate in beats per minute. -* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.heart_rate.xml -* HRM Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml -* Location: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.body_sensor_location.xml -*/ -class HeartRateService { -public: - /** - * @enum SensorLocation - * @brief Location of the heart rate sensor on body. - */ - enum { - LOCATION_OTHER = 0, /*!< Other location. */ - LOCATION_CHEST, /*!< Chest. */ - LOCATION_WRIST, /*!< Wrist. */ - LOCATION_FINGER, /*!< Finger. */ - LOCATION_HAND, /*!< Hand. */ - LOCATION_EAR_LOBE, /*!< Earlobe. */ - LOCATION_FOOT, /*!< Foot. */ - }; - -public: - /** - * @brief Constructor with 8-bit HRM Counter value. - * - * @param[ref] _ble - * Reference to the underlying BLE. - * @param[in] hrmCounter (8-bit) - * Initial value for the HRM counter. - * @param[in] location - * Sensor's location. - */ - HeartRateService(BLE &_ble, uint8_t hrmCounter, uint8_t location) : - ble(_ble), - valueBytes(hrmCounter), - hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, valueBytes.getPointer(), - valueBytes.getNumValueBytes(), HeartRateValueBytes::MAX_VALUE_BYTES, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, &location), - controlPoint(GattCharacteristic::UUID_HEART_RATE_CONTROL_POINT_CHAR, &controlPointValue) { - setupService(); - } - - /** - * @brief Constructor with a 16-bit HRM Counter value. - * - * @param[in] _ble - * Reference to the underlying BLE. - * @param[in] hrmCounter (8-bit) - * Initial value for the HRM counter. - * @param[in] location - * Sensor's location. - */ - HeartRateService(BLE &_ble, uint16_t hrmCounter, uint8_t location) : - ble(_ble), - valueBytes(hrmCounter), - hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, valueBytes.getPointer(), - valueBytes.getNumValueBytes(), HeartRateValueBytes::MAX_VALUE_BYTES, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY), - hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, &location), - controlPoint(GattCharacteristic::UUID_HEART_RATE_CONTROL_POINT_CHAR, &controlPointValue) { - setupService(); - } - - /** - * @brief Set a new 8-bit value for the heart rate. - * - * @param[in] hrmCounter - * Heart rate in BPM. - */ - void updateHeartRate(uint8_t hrmCounter) { - valueBytes.updateHeartRate(hrmCounter); - ble.gattServer().write(hrmRate.getValueHandle(), valueBytes.getPointer(), valueBytes.getNumValueBytes()); - } - - /** - * Set a new 16-bit value for the heart rate. - * - * @param[in] hrmCounter - * Heart rate in BPM. - */ - void updateHeartRate(uint16_t hrmCounter) { - valueBytes.updateHeartRate(hrmCounter); - ble.gattServer().write(hrmRate.getValueHandle(), valueBytes.getPointer(), valueBytes.getNumValueBytes()); - } - - /** - * This callback allows the heart rate service to receive updates to the - * controlPoint characteristic. - * - * @param[in] params - * Information about the characterisitc being updated. - */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == controlPoint.getValueAttribute().getHandle()) { - /* Do something here if the new value is 1; else you can override this method by - * extending this class. - * @NOTE: If you are extending this class, be sure to also call - * ble.onDataWritten(this, &ExtendedHRService::onDataWritten); in - * your constructor. - */ - } - } - -protected: - void setupService(void) { - GattCharacteristic *charTable[] = {&hrmRate, &hrmLocation, &controlPoint}; - GattService hrmService(GattService::UUID_HEART_RATE_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(hrmService); - ble.onDataWritten(this, &HeartRateService::onDataWritten); - } - -protected: - /* Private internal representation for the bytes used to work with the value of the heart rate characteristic. */ - struct HeartRateValueBytes { - static const unsigned MAX_VALUE_BYTES = 3; /* Flags, and up to two bytes for heart rate. */ - static const unsigned FLAGS_BYTE_INDEX = 0; - - static const unsigned VALUE_FORMAT_BITNUM = 0; - static const uint8_t VALUE_FORMAT_FLAG = (1 << VALUE_FORMAT_BITNUM); - - HeartRateValueBytes(uint8_t hrmCounter) : valueBytes() { - updateHeartRate(hrmCounter); - } - - HeartRateValueBytes(uint16_t hrmCounter) : valueBytes() { - updateHeartRate(hrmCounter); - } - - void updateHeartRate(uint8_t hrmCounter) { - valueBytes[FLAGS_BYTE_INDEX] &= ~VALUE_FORMAT_FLAG; - valueBytes[FLAGS_BYTE_INDEX + 1] = hrmCounter; - } - - void updateHeartRate(uint16_t hrmCounter) { - valueBytes[FLAGS_BYTE_INDEX] |= VALUE_FORMAT_FLAG; - valueBytes[FLAGS_BYTE_INDEX + 1] = (uint8_t)(hrmCounter & 0xFF); - valueBytes[FLAGS_BYTE_INDEX + 2] = (uint8_t)(hrmCounter >> 8); - } - - uint8_t *getPointer(void) { - return valueBytes; - } - - const uint8_t *getPointer(void) const { - return valueBytes; - } - - unsigned getNumValueBytes(void) const { - return 1 + ((valueBytes[FLAGS_BYTE_INDEX] & VALUE_FORMAT_FLAG) ? sizeof(uint16_t) : sizeof(uint8_t)); - } - - private: - /* First byte: 8-bit values, no extra info. Second byte: uint8_t HRM value */ - /* See https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml */ - uint8_t valueBytes[MAX_VALUE_BYTES]; - }; - -protected: - BLE &ble; - - HeartRateValueBytes valueBytes; - uint8_t controlPointValue; - - GattCharacteristic hrmRate; - ReadOnlyGattCharacteristic<uint8_t> hrmLocation; - WriteOnlyGattCharacteristic<uint8_t> controlPoint; -}; - -#endif /* #ifndef __BLE_HEART_RATE_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/LinkLossService.h --- a/ble/services/LinkLossService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,103 +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 __BLE_LINK_LOSS_SERVICE_H__ -#define __BLE_LINK_LOSS_SERVICE_H__ - -#include "ble/Gap.h" - -/** -* @class LinkLossService -* @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: - enum AlertLevel_t { - NO_ALERT = 0, - MILD_ALERT = 1, - HIGH_ALERT = 2 - }; - - typedef void (* callback_t)(AlertLevel_t level); - - /** - * @param[ref] ble - * BLE object for the underlying controller. - */ - LinkLossService(BLE &bleIn, callback_t callbackIn, AlertLevel_t levelIn = NO_ALERT) : - ble(bleIn), - alertLevel(levelIn), - callback(callbackIn), - alertLevelChar(GattCharacteristic::UUID_ALERT_LEVEL_CHAR, reinterpret_cast<uint8_t *>(&alertLevel)) { - static bool serviceAdded = false; /* We should only ever add one LinkLoss service. */ - if (serviceAdded) { - return; - } - - GattCharacteristic *charTable[] = {&alertLevelChar}; - GattService linkLossService(GattService::UUID_LINK_LOSS_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.gattServer().addService(linkLossService); - serviceAdded = true; - - ble.gap().onDisconnection(this, &LinkLossService::onDisconnectionFilter); - ble.gattServer().onDataWritten(this, &LinkLossService::onDataWritten); - } - - /** - * Update the callback. - */ - void setCallback(callback_t newCallback) { - callback = newCallback; - } - - /** - * Update alertness level. - */ - void setAlertLevel(AlertLevel_t newLevel) { - alertLevel = newLevel; - } - -protected: - /** - * This callback allows receiving updates to the AlertLevel characteristic. - * - * @param[in] params - * Information about the characterisitc being updated. - */ - virtual void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == alertLevelChar.getValueHandle()) { - alertLevel = *reinterpret_cast<const AlertLevel_t *>(params->data); - } - } - - void onDisconnectionFilter(const Gap::DisconnectionCallbackParams_t *params) { - if (alertLevel != NO_ALERT) { - callback(alertLevel); - } - } - -protected: - BLE &ble; - AlertLevel_t alertLevel; - callback_t callback; - - ReadWriteGattCharacteristic<uint8_t> alertLevelChar; -}; - -#endif /* __BLE_LINK_LOSS_SERVICE_H__ */ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/UARTService.h --- a/ble/services/UARTService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,206 +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 __BLE_UART_SERVICE_H__ -#define __BLE_UART_SERVICE_H__ - -#ifdef YOTTA_CFG_MBED_OS -#include "mbed-drivers/mbed.h" -#include "mbed-drivers/Stream.h" -#else -#include "mbed.h" -#include "Stream.h" -#endif - -#include "ble/UUID.h" -#include "ble/BLE.h" - -extern const uint8_t UARTServiceBaseUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint16_t UARTServiceShortUUID; -extern const uint16_t UARTServiceTXCharacteristicShortUUID; -extern const uint16_t UARTServiceRXCharacteristicShortUUID; - -extern const uint8_t UARTServiceUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UARTServiceUUID_reversed[UUID::LENGTH_OF_LONG_UUID]; - -extern const uint8_t UARTServiceTXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UARTServiceRXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID]; - -/** -* @class UARTService. -* @brief BLE Service to enable UART over BLE. -*/ -class UARTService { -public: - /**< 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: - - /** - * @param[ref] ble - * BLE object for the underlying controller. - */ - UARTService(BLE &_ble) : - ble(_ble), - receiveBuffer(), - sendBuffer(), - sendBufferIndex(0), - numBytesReceived(0), - receiveBufferIndex(0), - txCharacteristic(UARTServiceTXCharacteristicUUID, receiveBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE), - rxCharacteristic(UARTServiceRXCharacteristicUUID, sendBuffer, 1, BLE_UART_SERVICE_MAX_DATA_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) { - GattCharacteristic *charTable[] = {&txCharacteristic, &rxCharacteristic}; - GattService uartService(UARTServiceUUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); - - ble.addService(uartService); - ble.onDataWritten(this, &UARTService::onDataWritten); - } - - /** - * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. - */ - uint16_t getTXCharacteristicHandle() { - return txCharacteristic.getValueAttribute().getHandle(); - } - - /** - * Note: TX and RX characteristics are to be interpreted from the viewpoint of the GATT client using this service. - */ - uint16_t getRXCharacteristicHandle() { - return rxCharacteristic.getValueAttribute().getHandle(); - } - - /** - * We attempt to collect bytes before pushing them to the UART RX - * characteristic; writing to the RX characteristic then generates - * notifications for the client. Updates made in quick succession to a - * 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 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 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; - const uint8_t *buffer = static_cast<const uint8_t *>(_buffer); - - if (ble.getGapState().connected) { - unsigned bufferIndex = 0; - while (length) { - unsigned bytesRemainingInSendBuffer = BLE_UART_SERVICE_MAX_DATA_LEN - sendBufferIndex; - unsigned bytesToCopy = (length < bytesRemainingInSendBuffer) ? length : bytesRemainingInSendBuffer; - - /* Copy bytes into sendBuffer. */ - memcpy(&sendBuffer[sendBufferIndex], &buffer[bufferIndex], bytesToCopy); - length -= bytesToCopy; - sendBufferIndex += bytesToCopy; - bufferIndex += bytesToCopy; - - /* Have we collected enough? */ - if ((sendBufferIndex == BLE_UART_SERVICE_MAX_DATA_LEN) || - // (sendBuffer[sendBufferIndex - 1] == '\r') || - (sendBuffer[sendBufferIndex - 1] == '\n')) { - ble.gattServer().write(getRXCharacteristicHandle(), static_cast<const uint8_t *>(sendBuffer), sendBufferIndex); - sendBufferIndex = 0; - } - } - } - - return origLength; - } - - /** - * Helper function to write out strings. - * @param str The received string. - * @return Number of characters appended to the rxCharacteristic. - */ - size_t writeString(const char *str) { - return write(str, strlen(str)); - } - - /** - * Override for Stream::_putc(). - * @param c - * This function writes the character c, cast to an unsigned char, to stream. - * @return - * The character written as an unsigned char cast to an int or EOF on error. - */ - int _putc(int c) { - return (write(&c, 1) == 1) ? 1 : EOF; - } - - /** - * Override for Stream::_getc(). - * @return - * The character read. - */ - int _getc() { - if (receiveBufferIndex == numBytesReceived) { - return EOF; - } - - return receiveBuffer[receiveBufferIndex++]; - } - -protected: - /** - * 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; if that's - * not used, this method can be used as a callback directly. - */ - void onDataWritten(const GattWriteCallbackParams *params) { - if (params->handle == getTXCharacteristicHandle()) { - uint16_t bytesRead = params->len; - if (bytesRead <= BLE_UART_SERVICE_MAX_DATA_LEN) { - numBytesReceived = bytesRead; - receiveBufferIndex = 0; - memcpy(receiveBuffer, params->data, numBytesReceived); - } - } - } - -protected: - BLE &ble; - - uint8_t receiveBuffer[BLE_UART_SERVICE_MAX_DATA_LEN]; /**< The local buffer into which we receive - * inbound data before forwarding it to the - * application. */ - - uint8_t sendBuffer[BLE_UART_SERVICE_MAX_DATA_LEN]; /**< The local buffer into which outbound data is - * accumulated before being pushed to the - * rxCharacteristic. */ - uint8_t sendBufferIndex; - uint8_t numBytesReceived; - uint8_t receiveBufferIndex; - - GattCharacteristic txCharacteristic; /**< From the point of view of the external client, this is the characteristic - * they'd write into in order to communicate with this application. */ - GattCharacteristic rxCharacteristic; /**< From the point of view of the external client, this is the characteristic - * they'd read from in order to receive the bytes transmitted by this - * application. */ -}; - -#endif /* #ifndef __BLE_UART_SERVICE_H__*/ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/URIBeaconConfigService.h --- a/ble/services/URIBeaconConfigService.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,472 +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 SERVICES_URIBEACONCONFIGSERVICE_H_ -#define SERVICES_URIBEACONCONFIGSERVICE_H_ - -#include "ble/BLE.h" - -#ifdef YOTTA_CFG_MBED_OS -#include "mbed-drivers/mbed.h" -#else -#include "mbed.h" -#endif - -extern const uint8_t UUID_URI_BEACON_SERVICE[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_LOCK_STATE_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_LOCK_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_UNLOCK_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_URI_DATA_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_FLAGS_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_ADV_POWER_LEVELS_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_TX_POWER_MODE_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_BEACON_PERIOD_CHAR[UUID::LENGTH_OF_LONG_UUID]; -extern const uint8_t UUID_RESET_CHAR[UUID::LENGTH_OF_LONG_UUID]; - -extern const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)]; - -/** -* @class URIBeaconConfigService -* @brief UriBeacon Configuration Service. Can be used to set URL, adjust power levels, and set flags. -* See http://uribeacon.org -* -*/ -class URIBeaconConfigService { - 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]; - - static const int URI_DATA_MAX = 18; - typedef uint8_t UriData_t[URI_DATA_MAX]; - - struct Params_t { - Lock_t lock; - 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(). - uint16_t beaconPeriod; - }; - - /** - * @param[ref] ble - * BLE object for the underlying controller. - * @param[in/out] paramsIn - * Reference to application-visible beacon state, loaded - * from persistent storage at startup. - * @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. - * @param[in] defaultUriDataIn - * 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. - */ - URIBeaconConfigService(BLE &bleIn, - Params_t ¶msIn, - bool resetToDefaultsFlag, - const char *defaultURIDataIn, - PowerLevels_t &defaultAdvPowerLevelsIn) : - ble(bleIn), - params(paramsIn), - defaultUriDataLength(), - defaultUriData(), - defaultAdvPowerLevels(defaultAdvPowerLevelsIn), - initSucceeded(false), - resetFlag(), - lockedStateChar(UUID_LOCK_STATE_CHAR, &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) { - - encodeURI(defaultURIDataIn, defaultUriData, defaultUriDataLength); - if (defaultUriDataLength > URI_DATA_MAX) { - return; - } - - if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) { - resetToDefaultsFlag = true; - } - if (resetToDefaultsFlag) { - resetToDefaults(); - } else { - updateCharacteristicValues(); - } - - lockedState = isLocked(); - - lockChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::lockAuthorizationCallback); - unlockChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::unlockAuthorizationCallback); - uriDataChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::uriDataWriteAuthorizationCallback); - flagsChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback<uint8_t>); - advPowerLevelsChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback<PowerLevels_t>); - txPowerModeChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::powerModeAuthorizationCallback); - beaconPeriodChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::basicAuthorizationCallback<uint16_t>); - resetChar.setWriteAuthorizationCallback(this, &URIBeaconConfigService::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, &URIBeaconConfigService::onDataWrittenCallback); - - setupURIBeaconConfigAdvertisements(); /* Set up advertising for the config service. */ - - initSucceeded = true; - } - - bool configuredSuccessfully(void) const { - return initSucceeded; - } - - /* 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"; - - ble.gap().clearAdvertisingPayload(); - - ble.gap().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.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID)); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG); - ble.gap().accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast<const uint8_t *>(&DEVICE_NAME), sizeof(DEVICE_NAME)); - ble.gap().accumulateScanResponse(GapAdvertisingData::TX_POWER_LEVEL, - reinterpret_cast<uint8_t *>(&defaultAdvPowerLevels[URIBeaconConfigService::TX_POWER_MODE_LOW]), - sizeof(uint8_t)); - - ble.gap().setTxPower(params.advPowerLevels[params.txPowerMode]); - ble.gap().setDeviceName(reinterpret_cast<const uint8_t *>(&DEVICE_NAME)); - ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); - 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. */ - void setupURIBeaconAdvertisements() - { - /* Reinitialize the BLE stack. This will clear away the existing services and advertising state. */ - ble.shutdown(); - ble.init(); - - // Fields from the service. - unsigned beaconPeriod = params.beaconPeriod; - unsigned txPowerMode = params.txPowerMode; - unsigned uriDataLength = params.uriDataLength; - URIBeaconConfigService::UriData_t &uriData = params.uriData; - 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. */ - saveURIBeaconConfigParams(¶ms); - - ble.gap().clearAdvertisingPayload(); - ble.gap().setTxPower(params.advPowerLevels[params.txPowerMode]); - ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); - ble.gap().setAdvertisingInterval(beaconPeriod); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, BEACON_UUID, sizeof(BEACON_UUID)); - - uint8_t serviceData[SERVICE_DATA_MAX]; - unsigned serviceDataLen = 0; - serviceData[serviceDataLen++] = BEACON_UUID[0]; - serviceData[serviceDataLen++] = BEACON_UUID[1]; - serviceData[serviceDataLen++] = flags; - serviceData[serviceDataLen++] = advPowerLevels[txPowerMode]; - for (unsigned j = 0; j < uriDataLength; j++) { - serviceData[serviceDataLen++] = uriData[j]; - } - ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, serviceData, serviceDataLen); - } - - private: - // True if the lock bits are non-zero. - bool isLocked() { - Lock_t testLock; - memset(testLock, 0, sizeof(Lock_t)); - return memcmp(params.lock, testLock, sizeof(Lock_t)); - } - - /* - * This callback is invoked when a GATT client attempts to modify any of the - * 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, - memcpy(params.lock, writeParams->data, sizeof(Lock_t)); - // Use isLocked() in case bits are being set to all zeros. - lockedState = isLocked(); - } else if (handle == unlockChar.getValueHandle()) { - // Validated earlier. - memset(params.lock, 0, sizeof(Lock_t)); - lockedState = false; - } else if (handle == uriDataChar.getValueHandle()) { - params.uriDataLength = writeParams->len; - memcpy(params.uriData, writeParams->data, params.uriDataLength); - } else if (handle == flagsChar.getValueHandle()) { - params.flags = *(writeParams->data); - } else if (handle == advPowerLevelsChar.getValueHandle()) { - memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t)); - } else if (handle == txPowerModeChar.getValueHandle()) { - params.txPowerMode = *(writeParams->data); - } else if (handle == beaconPeriodChar.getValueHandle()) { - params.beaconPeriod = *((uint16_t *)(writeParams->data)); - - /* Remap beaconPeriod to within permissible bounds if necessary. */ - if (params.beaconPeriod != 0) { - bool paramsUpdated = false; - if (params.beaconPeriod < ble.gap().getMinAdvertisingInterval()) { - params.beaconPeriod = ble.gap().getMinAdvertisingInterval(); - paramsUpdated = true; - } else if (params.beaconPeriod > ble.gap().getMaxAdvertisingInterval()) { - params.beaconPeriod = ble.gap().getMaxAdvertisingInterval(); - paramsUpdated = true; - } - if (paramsUpdated) { - ble.gattServer().write(beaconPeriodChar.getValueHandle(), reinterpret_cast<uint8_t *>(¶ms.beaconPeriod), sizeof(uint16_t)); - } - } - } else if (handle == resetChar.getValueHandle()) { - resetToDefaults(); - } - } - - /* - * Reset the default values. - */ - void resetToDefaults(void) { - lockedState = false; - memset(params.lock, 0, sizeof(Lock_t)); - memcpy(params.uriData, defaultUriData, URI_DATA_MAX); - params.uriDataLength = defaultUriDataLength; - params.flags = 0; - memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t)); - params.txPowerMode = TX_POWER_MODE_LOW; - params.beaconPeriod = 1000; - 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.gattServer().write(lockedStateChar.getValueHandle(), &lockedState, 1); - ble.gattServer().write(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength); - ble.gattServer().write(flagsChar.getValueHandle(), ¶ms.flags, 1); - ble.gattServer().write(beaconPeriodChar.getValueHandle(), - reinterpret_cast<uint8_t *>(¶ms.beaconPeriod), sizeof(uint16_t)); - ble.gattServer().write(txPowerModeChar.getValueHandle(), ¶ms.txPowerMode, 1); - ble.gattServer().write(advPowerLevelsChar.getValueHandle(), - reinterpret_cast<uint8_t *>(params.advPowerLevels), sizeof(PowerLevels_t)); - } - -protected: - void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) { - if (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 (!lockedState) { - 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 (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 (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 (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; - } - } - -protected: - 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. - - uint8_t lockedState; - bool initSucceeded; - uint8_t resetFlag; - - 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; - -public: - /* - * 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[] = { - "http://www.", - "https://www.", - "http://", - "https://", - "urn:uuid:" - }; - 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 that doesn't match a suffix. */ - if (i == NUM_SUFFIXES) { - uriDataOut[sizeofURIDataOut++] = *uriDataIn; - ++uriDataIn; - } - } - } -}; - -#endif // SERVICES_URIBEACONCONFIGSERVICE_H_ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b ble/services/iBeacon.h --- a/ble/services/iBeacon.h Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,75 +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 __BLE_IBEACON_H__ -#define __BLE_IBEACON_H__ - -#include "core_cmInstr.h" -#include "ble/BLE.h" - -/** -* @class iBeacon -* @brief iBeacon Service. This sets up a device to broadcast advertising packets to mimic an iBeacon. -*/ -class iBeacon -{ -public: - typedef const uint8_t LocationUUID_t[16]; - - union Payload { - uint8_t raw[25]; - struct { - uint16_t companyID; - uint8_t ID; - uint8_t len; - uint8_t proximityUUID[16]; - uint16_t majorNumber; - uint16_t minorNumber; - uint8_t txPower; - }; - - Payload(LocationUUID_t uuid, uint16_t majNum, uint16_t minNum, uint8_t transmitPower, uint16_t companyIDIn) : - companyID(companyIDIn), ID(0x02), len(0x15), majorNumber(__REV16(majNum)), minorNumber(__REV16(minNum)), txPower(transmitPower) - { - memcpy(proximityUUID, uuid, sizeof(LocationUUID_t)); - } - }; - -public: - iBeacon(BLE &_ble, - LocationUUID_t uuid, - uint16_t majNum, - uint16_t minNum, - uint8_t txP = 0xC8, - uint16_t compID = 0x004C) : - ble(_ble), data(uuid, majNum, minNum, txP, compID) - { - // 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. - ble.accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, data.raw, sizeof(data.raw)); - - // Set advertising type. - ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); - } - -protected: - BLE &ble; - Payload data; -}; - -typedef iBeacon iBeaconService; /* This type-alias is deprecated. Please use iBeacon directly. This alias may be dropped from a future release. */ - -#endif //__BLE_IBEACON_H__ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b source/services/DFUService.cpp --- a/source/services/DFUService.cpp Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,44 +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. - */ - -#ifdef TARGET_NRF51822 /* DFU only supported on nrf51 platforms */ - -#include "ble/services/DFUService.h" - -const uint8_t DFUServiceBaseUUID[] = { - 0x00, 0x00, 0x00, 0x00, 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint16_t DFUServiceShortUUID = 0x1530; -const uint16_t DFUServiceControlCharacteristicShortUUID = 0x1531; -const uint16_t DFUServicePacketCharacteristicShortUUID = 0x1532; - -const uint8_t DFUServiceUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServiceShortUUID >> 8), (uint8_t)(DFUServiceShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint8_t DFUServiceControlCharacteristicUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServiceControlCharacteristicShortUUID >> 8), (uint8_t)(DFUServiceControlCharacteristicShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; -const uint8_t DFUServicePacketCharacteristicUUID[] = { - 0x00, 0x00, (uint8_t)(DFUServicePacketCharacteristicShortUUID >> 8), (uint8_t)(DFUServicePacketCharacteristicShortUUID & 0xFF), 0x12, 0x12, 0xEF, 0xDE, - 0x15, 0x23, 0x78, 0x5F, 0xEA, 0xBC, 0xD1, 0x23, -}; - -DFUService::ResetPrepare_t DFUService::handoverCallback = NULL; - -#endif /* #ifdef TARGET_NRF51822 */ \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b source/services/UARTService.cpp --- a/source/services/UARTService.cpp Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,41 +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. - */ - -#include "ble/services/UARTService.h" - -const uint8_t UARTServiceBaseUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, 0x00, 0x00, 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint16_t UARTServiceShortUUID = 0x0001; -const uint16_t UARTServiceTXCharacteristicShortUUID = 0x0002; -const uint16_t UARTServiceRXCharacteristicShortUUID = 0x0003; -const uint8_t UARTServiceUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceShortUUID >> 8), (uint8_t)(UARTServiceShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint8_t UARTServiceUUID_reversed[UUID::LENGTH_OF_LONG_UUID] = { - 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, - 0x93, 0xF3, 0xA3, 0xB5, (uint8_t)(UARTServiceShortUUID & 0xFF), (uint8_t)(UARTServiceShortUUID >> 8), 0x40, 0x6E -}; -const uint8_t UARTServiceTXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceTXCharacteristicShortUUID >> 8), (uint8_t)(UARTServiceTXCharacteristicShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; -const uint8_t UARTServiceRXCharacteristicUUID[UUID::LENGTH_OF_LONG_UUID] = { - 0x6E, 0x40, (uint8_t)(UARTServiceRXCharacteristicShortUUID >> 8), (uint8_t)(UARTServiceRXCharacteristicShortUUID & 0xFF), 0xB5, 0xA3, 0xF3, 0x93, - 0xE0, 0xA9, 0xE5, 0x0E, 0x24, 0xDC, 0xCA, 0x9E, -}; \ No newline at end of file
diff -r 65474dc93927 -r e3d4f8c7787b source/services/URIBeaconConfigService.cpp --- a/source/services/URIBeaconConfigService.cpp Wed Sep 14 14:18:00 2016 +0100 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,35 +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. - */ - -#include "ble/services/URIBeaconConfigService.h" - -#define UUID_URI_BEACON(FIRST, SECOND) { \ - 0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba, \ - 0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8, \ -} - -const uint8_t UUID_URI_BEACON_SERVICE[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x80); -const uint8_t UUID_LOCK_STATE_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x81); -const uint8_t UUID_LOCK_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x82); -const uint8_t UUID_UNLOCK_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x83); -const uint8_t UUID_URI_DATA_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x84); -const uint8_t UUID_FLAGS_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x85); -const uint8_t UUID_ADV_POWER_LEVELS_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x86); -const uint8_t UUID_TX_POWER_MODE_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x87); -const uint8_t UUID_BEACON_PERIOD_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x88); -const uint8_t UUID_RESET_CHAR[UUID::LENGTH_OF_LONG_UUID] = UUID_URI_BEACON(0x20, 0x89); - -const uint8_t BEACON_UUID[sizeof(UUID::ShortUUIDBytes_t)] = {0xD8, 0xFE}; \ No newline at end of file