Button initiated config service

Dependencies:   BLE_API_EddystoneConfigService_2 mbed nRF51822

Fork of BLE_EddystoneBeaconConfigService_3 by URIBeacon

EddystoneConfigService.h

Committer:
roywant
Date:
2015-09-09
Revision:
38:8fdb16f67e7c
Parent:
37:22175faa76be
Child:
39:2c73bc1ff4f5

File content as of revision 38:8fdb16f67e7c:

/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_
#define SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_

#include "mbed.h"
#include "ble/BLE.h"
#include "ble/services/EddystoneService.h"

#define EDDYSTONE_NUM_UID_FRAMES 10
#define EDDYSTONE_NUM_URL_FRAMES 50


#define UUID_URI_BEACON(FIRST, SECOND) {                         \
        0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba,       \
        0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8,          \
}

static const uint8_t UUID_URI_BEACON_SERVICE[]    = UUID_URI_BEACON(0x20, 0x80);
static const uint8_t UUID_LOCK_STATE_CHAR[]       = UUID_URI_BEACON(0x20, 0x81);
static const uint8_t UUID_LOCK_CHAR[]             = UUID_URI_BEACON(0x20, 0x82);
static const uint8_t UUID_UNLOCK_CHAR[]           = UUID_URI_BEACON(0x20, 0x83);
static const uint8_t UUID_URI_DATA_CHAR[]         = UUID_URI_BEACON(0x20, 0x84);
static const uint8_t UUID_FLAGS_CHAR[]            = UUID_URI_BEACON(0x20, 0x85);
static const uint8_t UUID_ADV_POWER_LEVELS_CHAR[] = UUID_URI_BEACON(0x20, 0x86);
static const uint8_t UUID_TX_POWER_MODE_CHAR[]    = UUID_URI_BEACON(0x20, 0x87);
static const uint8_t UUID_BEACON_PERIOD_CHAR[]    = UUID_URI_BEACON(0x20, 0x88);
static const uint8_t UUID_RESET_CHAR[]            = UUID_URI_BEACON(0x20, 0x89);
extern const uint8_t       BEACON_EDDYSTONE[2];

/**
* @class EddystoneConfigService
* @brief Eddystone Configuration Service. Can be used to set URL, adjust power levels, and set flags.
* See https://github.com/google/eddystone
*
*/
class EddystoneConfigService
{
public:
    /**
     * @brief Transmission Power Modes for UriBeacon
     */
    static const uint8_t TX_POWER_MODE_LOWEST = 0; /*!< Lowest TX power mode */
    static const uint8_t TX_POWER_MODE_LOW    = 1; /*!< Low TX power mode */
    static const uint8_t TX_POWER_MODE_MEDIUM = 2; /*!< Medium TX power mode */
    static const uint8_t TX_POWER_MODE_HIGH   = 3; /*!< High TX power mode */
    static const unsigned NUM_POWER_MODES     = 4; /*!< Number of Power Modes defined */

    static const int ADVERTISING_INTERVAL_MSEC = 1000;  // Advertising interval for config service.
    static const int SERVICE_DATA_MAX = 31;             // Maximum size of service data in ADV packets

    typedef uint8_t Lock_t[16];               /* 128 bits */
    typedef int8_t PowerLevels_t[NUM_POWER_MODES];

    // There are currently 3 subframes defined, URI, UID, and TLM
#define EDDYSTONE_MAX_FRAMETYPE 3
    void (*frames[EDDYSTONE_MAX_FRAMETYPE])(uint8_t *, uint32_t);
    uint8_t frameIndex;
    static const int URI_DATA_MAX = 18;
    typedef uint8_t  UriData_t[URI_DATA_MAX];

    // UID Frame Type subfields
    static const int UID_NAMESPACEID_SIZE = 10;
    typedef uint8_t  UIDNamespaceID_t[UID_NAMESPACEID_SIZE];
    static const int UID_INSTANCEID_SIZE = 6;
    typedef uint8_t  UIDInstanceID_t[UID_INSTANCEID_SIZE];

    // Eddystone Frame Type ID
    static const uint8_t FRAME_TYPE_UID = 0x00;
    static const uint8_t FRAME_TYPE_URL = 0x10;
    static const uint8_t FRAME_TYPE_TLM = 0x20;

    static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14Bytes
    static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes

    struct Params_t {
        uint8_t       lockedState;
        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;
        uint8_t       tlmVersion;     // version of TLM packet
        UIDNamespaceID_t uidNamespaceID; // UUID type, Namespace ID, 10B
        UIDInstanceID_t  uidInstanceID;  // UUID type, Instance ID,  6B
    };

    /**
     * @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.
     * @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]     defaultAdvPowerLevelsIn
     *                    Default power-levels array; applies only if the resetToDefaultsFlag is true.
     * @param[in]     defaultUriDataIn
     *                    Default un-encoded URI; optional parameter, applies only if the resetToDefaultsFlag is true
     * @param[in]     defaultUIDNamespaceIDIn
     *                    Default 10Byte UID Namespace ID; optional parameter, applies only if the resetToDefaultsFlag is true
     * @param[in]     defaultUIDInstanceIDIn
     *                    Default 6byte UID Instance ID; optional parameter, applies only if the resetToDefaultsFlag is true
     * @param[in]     defaultTLMVersionIn
     *                    Default TLM version; defaults to 0, applies only if the resetToDefaultsFlag is true
     */
    EddystoneConfigService(BLEDevice     &bleIn,
                           Params_t      &paramsIn,
                           bool          resetToDefaultsFlag,
                           PowerLevels_t &defaultAdvPowerLevelsIn,
                           const char   *defaultURIDataIn = NULL,
                           UIDNamespaceID_t *defaultUIDNamespaceIDIn = NULL,
                           UIDInstanceID_t  *defaultUIDInstanceIDIn = NULL,
                           uint8_t defaultTLMVersionIn = 0) :
        ble(bleIn),
        params(paramsIn),       // Initialize URL Data
        defaultUriDataLength(),
        defaultUriData(),
        defaultUidNamespaceID(), // Initialize UID Data
        defaultUidInstanceID(),
        defaultUrlPower(params.advPowerLevels[params.txPowerMode]),
        defaultUidPower(params.advPowerLevels[params.txPowerMode]),
        uidIsSet(true),
        urlIsSet(true),
        defaultAdvPowerLevels(defaultAdvPowerLevelsIn),
        initSucceeded(false),
        resetFlag(),
        lockedStateChar(UUID_LOCK_STATE_CHAR, &params.lockedState),
        TlmVersion(defaultTLMVersionIn), // Initialize TLM Data
        TlmBatteryVoltage(0),
        TlmBeaconTemp(0),
        TlmPduCount(0),
        TlmTimeSinceBoot(0),
        lockChar(UUID_LOCK_CHAR, &params.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, &params.lock),
        flagsChar(UUID_FLAGS_CHAR, &params.flags),
        advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, &params.advPowerLevels),
        txPowerModeChar(UUID_TX_POWER_MODE_CHAR, &params.txPowerMode),
        beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, &params.beaconPeriod),
        resetChar(UUID_RESET_CHAR, &resetFlag) 
        {
        //Set UID frame
        memcpy(defaultUidNamespaceID,defaultUIDNamespaceIDIn,UID_NAMESPACEID_SIZE);
        memcpy(defaultUidInstanceID,defaultUIDInstanceIDIn,UID_INSTANCEID_SIZE);
        
        // Set URL Frame
        encodeURI(defaultURIDataIn, defaultUriData, defaultUriDataLength); // encode URL to URL Formatting
        if (defaultUriDataLength > URI_DATA_MAX) {
            return;
        }

        if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) {
            resetToDefaultsFlag = true;
        }
        if (resetToDefaultsFlag) {
            resetToDefaults();
        } else {
            updateCharacteristicValues();
        }

        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);

        setupEddystoneConfigAdvertisements(); /* Setup advertising for the configService. */

        initSucceeded = true;
    }

    bool configuredSuccessfully(void) const {
        return initSucceeded;
    }

    /* Start out by advertising the configService for a limited time after
     * startup; and switch to the normal non-connectible beacon functionality
     * afterwards. */
    void setupEddystoneConfigAdvertisements() {
        const char DEVICE_NAME[] = "eddystone Config";

        ble.clearAdvertisingPayload();

        ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);

        // UUID is in different order in the ADV frame (!)
        uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)];
        for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) {
            reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1];
        }
        ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID));
        ble.accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG);
        ble.accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast<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(params.advPowerLevels[params.txPowerMode]);
        ble.setDeviceName(reinterpret_cast<const uint8_t *>(&DEVICE_NAME));
        ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
        ble.setAdvertisingInterval(GapAdvertisingParams::MSEC_TO_ADVERTISEMENT_DURATION_UNITS(ADVERTISING_INTERVAL_MSEC));
    }

    /*
    *   This function actually impliments the Eddystone Beacon service. It can be called with the help of the wrapper function
    *   to load saved config params, or it can be called explicitly to reset the eddystone beacon to hardcoded values on each reset.
    *
    */
    void setupEddystoneAdvertisements() {
        DBG("Switching Config -> adv");
        //uint8_t serviceData[SERVICE_DATA_MAX];
        //unsigned serviceDataLen = 0;
        //unsigned beaconPeriod = params.beaconPeriod;
        
        //setUIDFrameData(params.txPowerMode,defaultUidNamespaceID, defaultUidInstanceID);
        //setURLFrameData(params.txPowerMode,(char *)params.uriData);

        // Initialize Frame transition
        //frameIndex = 0;
        //uidRFU = 0;
        //switchFlag = true;


        /* Reinitialize the BLE stack. This will clear away the existing services and advertising state. */
//        ble.shutdown();
//        ble.init();
//        ble.setTxPower(params.txPowerMode);
//        ble.setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED);
//        ble.setAdvertisingInterval(beaconPeriod);
        extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */
        saveURIBeaconConfigParams(&params);

        static EddystoneService eddyServ(ble,params.beaconPeriod,params.txPowerMode, (uint8_t *) params.uidNamespaceID, (uint8_t *) params.uidInstanceID, (const char *) params.uriData, params.uriDataLength, params.tlmVersion );
//        updateTlmPduCount(0);
//        updateTlmTimeSinceBoot(0);

        // Construct TLM Frame in initial advertising.
//        serviceData[serviceDataLen++] = BEACON_EDDYSTONE[0];
//        serviceData[serviceDataLen++] = BEACON_EDDYSTONE[1];
//        serviceDataLen += constructTLMFrame(serviceData+serviceDataLen,SERVICE_DATA_MAX);

//        updateAdvPacket(serviceData, serviceDataLen);
//        ble.gap().startAdvertising();
//        ble.gap().onRadioNotification(this,&EddystoneConfigService::radioNotificationCallback);
//        timeSinceBootTick.attach(this,&EddystoneConfigService::tsbCallback,0.1); // incriment the TimeSinceBoot ticker every 0.1s
    }

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;
        } else if (handle == unlockChar.getValueHandle()) {
            // Validated earlier
            params.lockedState = false;
        } else if (handle == uriDataChar.getValueHandle()) {
            params.uriDataLength = writeParams->len;
            memcpy(params.uriData, writeParams->data, params.uriDataLength);
            memcpy(defaultUriData, writeParams->data, params.uriDataLength);
            defaultUriDataLength = params.uriDataLength;
            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",writeParams->data);
        } 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));

            /* 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 *>(&params.beaconPeriod), sizeof(uint16_t));
                }
            }
        } else if (handle == resetChar.getValueHandle()) {
            resetToDefaults();
        }
        updateCharacteristicValues();
    }

    /*
     * Reset the default values.
     */
    void resetToDefaults(void) {
        params.lockedState      = false;
        memset(params.lock, 0, sizeof(Lock_t));
        memcpy(params.uriData, defaultUriData, URI_DATA_MAX);
        params.uriDataLength    = defaultUriDataLength;
        params.flags            = 0x10;
        memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t));
        params.txPowerMode      = TX_POWER_MODE_LOW;
        params.beaconPeriod     = 1000;
        memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE);
        memcpy(params.uidInstanceID,  defaultUidInstanceID,  UID_INSTANCEID_SIZE);
        params.tlmVersion = TlmVersion;
        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(), &params.lockedState, 1);
        ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength);
        ble.updateCharacteristicValue(flagsChar.getValueHandle(), &params.flags, 1);
        ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(),
                                      reinterpret_cast<uint8_t *>(&params.beaconPeriod), sizeof(uint16_t));
        ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), &params.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            &params;
    Ticker              timeSinceBootTick;
    Timeout             switchFrame;
// Default value that is restored on reset
    uint8_t             defaultUriDataLength;
    UriData_t           defaultUriData;
    UIDNamespaceID_t    defaultUidNamespaceID;
    UIDInstanceID_t     defaultUidInstanceID;
    int8_t              defaultUidPower;
    int8_t              defaultUrlPower;
    uint16_t            uidRFU;
    bool                uidIsSet;
    bool                urlIsSet;
// Default value that is restored on reset
    PowerLevels_t       &defaultAdvPowerLevels;
    uint8_t             lockedState;
    bool                initSucceeded;
    uint8_t             resetFlag;
    bool                switchFlag;

// Private Variables for Telemetry Data
    uint8_t                      TlmVersion;
    volatile uint16_t            TlmBatteryVoltage;
    volatile uint16_t            TlmBeaconTemp;
    volatile uint32_t            TlmPduCount;
    volatile uint32_t            TlmTimeSinceBoot;

    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 URIBeacon spec (https://github.com/google/uribeacon/tree/master/specification).
     */
    static void encodeURI(const char *uriDataIn, UriData_t uriDataOut, uint8_t &sizeofURIDataOut) {
        const char *prefixes[] = {
            "http://www.",
            "https://www.",
            "http://",
            "https://",
        };
        const uint8_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 uint8_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++) {
            uint8_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++) {
                uint8_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. */
            if (i == NUM_SUFFIXES) {
                uriDataOut[sizeofURIDataOut++] = *uriDataIn;
                ++uriDataIn;
            }
        }
    }
};

#endif  // SERVICES_EDDYSTONEBEACONCONFIGSERVICE_H_