Gleb Klochkov / Mbed OS Climatcontroll_Main

Dependencies:   esp8266-driver

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers EddystoneConfigService.h Source File

EddystoneConfigService.h

00001 /* mbed Microcontroller Library
00002  * Copyright (c) 2006-2013 ARM Limited
00003  *
00004  * Licensed under the Apache License, Version 2.0 (the "License");
00005  * you may not use this file except in compliance with the License.
00006  * You may obtain a copy of the License at
00007  *
00008  *     http://www.apache.org/licenses/LICENSE-2.0
00009  *
00010  * Unless required by applicable law or agreed to in writing, software
00011  * distributed under the License is distributed on an "AS IS" BASIS,
00012  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013  * See the License for the specific language governing permissions and
00014  * limitations under the License.
00015  */
00016 
00017 #ifndef SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_
00018 #define SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_
00019 
00020 #warning ble/services/EddystoneConfigService.h is deprecated. Please use the example in 'github.com/ARMmbed/ble-examples/tree/master/BLE_EddystoneService'.
00021 
00022 #include "mbed.h"
00023 #include "ble/BLE.h"
00024 #include "ble/services/EddystoneService.h"
00025 
00026 #define UUID_URI_BEACON(FIRST, SECOND) {                         \
00027         0xee, 0x0c, FIRST, SECOND, 0x87, 0x86, 0x40, 0xba,       \
00028         0xab, 0x96, 0x99, 0xb9, 0x1a, 0xc9, 0x81, 0xd8,          \
00029 }
00030 
00031 static const uint8_t UUID_URI_BEACON_SERVICE[]    = UUID_URI_BEACON(0x20, 0x80);
00032 static const uint8_t UUID_LOCK_STATE_CHAR[]       = UUID_URI_BEACON(0x20, 0x81);
00033 static const uint8_t UUID_LOCK_CHAR[]             = UUID_URI_BEACON(0x20, 0x82);
00034 static const uint8_t UUID_UNLOCK_CHAR[]           = UUID_URI_BEACON(0x20, 0x83);
00035 static const uint8_t UUID_URI_DATA_CHAR[]         = UUID_URI_BEACON(0x20, 0x84);
00036 static const uint8_t UUID_FLAGS_CHAR[]            = UUID_URI_BEACON(0x20, 0x85);
00037 static const uint8_t UUID_ADV_POWER_LEVELS_CHAR[] = UUID_URI_BEACON(0x20, 0x86);
00038 static const uint8_t UUID_TX_POWER_MODE_CHAR[]    = UUID_URI_BEACON(0x20, 0x87);
00039 static const uint8_t UUID_BEACON_PERIOD_CHAR[]    = UUID_URI_BEACON(0x20, 0x88);
00040 static const uint8_t UUID_RESET_CHAR[]            = UUID_URI_BEACON(0x20, 0x89);
00041 extern const uint8_t BEACON_EDDYSTONE[2];
00042 
00043 /**
00044 * @class EddystoneConfigService
00045 * @brief Eddystone Configuration Service. Used to set URL, adjust power levels, and set flags.
00046 * See https://github.com/google/eddystone
00047 *
00048 */
00049 class EddystoneConfigService
00050 {
00051 public:
00052     /**
00053      * @brief Transmission Power Modes for UriBeacon
00054      */
00055     enum {
00056         TX_POWER_MODE_LOWEST,
00057         TX_POWER_MODE_LOW,
00058         TX_POWER_MODE_MEDIUM,
00059         TX_POWER_MODE_HIGH,
00060         NUM_POWER_MODES
00061     };
00062 
00063     static const unsigned ADVERTISING_INTERVAL_MSEC = 1000; // Advertising interval for config service.
00064     static const unsigned SERVICE_DATA_MAX          = 31;   // Maximum size of service data in ADV packets.
00065 
00066     typedef uint8_t Lock_t[16];                             /* 128 bits. */
00067     typedef int8_t PowerLevels_t[NUM_POWER_MODES];
00068 
00069     // There are currently three subframes defined: URI, UID, and TLM.
00070 #define EDDYSTONE_MAX_FRAMETYPE 3
00071     static const unsigned URI_DATA_MAX = 18;
00072     typedef uint8_t UriData_t[URI_DATA_MAX];
00073 
00074     // UID Frame Type subfields.
00075     static const size_t UID_NAMESPACEID_SIZE = 10;
00076     typedef uint8_t UIDNamespaceID_t[UID_NAMESPACEID_SIZE];
00077     static const size_t UID_INSTANCEID_SIZE = 6;
00078     typedef uint8_t UIDInstanceID_t[UID_INSTANCEID_SIZE];
00079 
00080     // Eddystone Frame Type ID.
00081     static const uint8_t FRAME_TYPE_UID = 0x00;
00082     static const uint8_t FRAME_TYPE_URL = 0x10;
00083     static const uint8_t FRAME_TYPE_TLM = 0x20;
00084 
00085     static const uint8_t FRAME_SIZE_TLM = 14; // TLM frame is a constant 14B.
00086     static const uint8_t FRAME_SIZE_UID = 20; // includes RFU bytes.
00087 
00088     struct Params_t {
00089         // Config Data
00090         bool             isConfigured; // Flag for configuration being complete:
00091                                        //   True = configured, False = not configured. Reset at instantiation, used for external callbacks.
00092         uint8_t          lockedState;
00093         Lock_t           lock;
00094         uint8_t          flags;
00095         PowerLevels_t    advPowerLevels;  // Current value of AdvertisedPowerLevels.
00096         uint8_t          txPowerMode;     // Firmware power levels used with setTxPower().
00097         uint16_t         beaconPeriod;
00098         // TLM Frame Data
00099         uint8_t          tlmVersion;      // Version of TLM packet.
00100         bool             tlmEnabled;
00101         float            tlmBeaconPeriod; // How often to broadcat TLM frame, in seconds.
00102         // URI Frame Data
00103         uint8_t          uriDataLength;
00104         UriData_t        uriData;
00105         bool             uriEnabled;
00106         float            uriBeaconPeriod; // How often to broadcast URIFrame, in seconds.
00107         // UID Frame Data
00108         UIDNamespaceID_t uidNamespaceID;  // UUID type, Namespace ID, 10B.
00109         UIDInstanceID_t  uidInstanceID;   // UUID type, Instance ID, 6B.
00110         bool             uidEnabled;
00111         float            uidBeaconPeriod; // How often to broadcast UID Frame, in seconds.
00112     };
00113 
00114     /**
00115      * @param[in]    bleIn
00116      *                    BLEDevice object for the underlying controller.
00117      * @param[in,out] paramsIn
00118      *                    Reference to application-visible beacon state, loaded
00119      *                    from persistent storage at startup.
00120      * @param[in]     defaultAdvPowerLevelsIn
00121      *                    Default power-levels array; applies only if resetToDefaultsFlag is true.
00122      *
00123      * @param[in]     radioPowerLevelsIn
00124      *                    Transmission power-levels to use in TX.
00125      */
00126     EddystoneConfigService (BLEDevice     &bleIn,
00127                            Params_t      &paramsIn,
00128                            PowerLevels_t &defaultAdvPowerLevelsIn,
00129                            PowerLevels_t &radioPowerLevelsIn) :
00130         ble(bleIn),
00131         params(paramsIn),       // Initialize URL data.
00132         defaultAdvPowerLevels(defaultAdvPowerLevelsIn),
00133         radioPowerLevels(radioPowerLevelsIn),
00134         initSucceeded(false),
00135         resetFlag(),
00136         defaultUidNamespaceID(), // Initialize UID data.
00137         defaultUidInstanceID(),
00138         defaultUidPower(defaultAdvPowerLevelsIn[params.txPowerMode]),
00139         uidIsSet(false),
00140         defaultUriDataLength(),
00141         defaultUriData(),
00142         defaultUrlPower(defaultAdvPowerLevelsIn[params.txPowerMode]),
00143         urlIsSet(false),
00144         tlmIsSet(false),
00145         lockedStateChar(UUID_LOCK_STATE_CHAR, &params.lockedState),
00146         lockChar(UUID_LOCK_CHAR, &params.lock),
00147         uriDataChar(UUID_URI_DATA_CHAR, params.uriData, 0, URI_DATA_MAX,
00148                     GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE),
00149         unlockChar(UUID_UNLOCK_CHAR, &params.lock),
00150         flagsChar(UUID_FLAGS_CHAR, &params.flags),
00151         advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, &params.advPowerLevels),
00152         txPowerModeChar(UUID_TX_POWER_MODE_CHAR, &params.txPowerMode),
00153         beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, &params.beaconPeriod),
00154         resetChar(UUID_RESET_CHAR, &resetFlag) {
00155         // Set Eddystone as not configured yet. Used to exit config before timeout if GATT services are written to.
00156         params.isConfigured = false;
00157 
00158         lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback);
00159         unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback);
00160         uriDataChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::uriDataWriteAuthorizationCallback);
00161         flagsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>);
00162         advPowerLevelsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<PowerLevels_t>);
00163         txPowerModeChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::powerModeAuthorizationCallback);
00164         beaconPeriodChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint16_t>);
00165         resetChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>);
00166 
00167         static GattCharacteristic *charTable[] = {
00168             &lockedStateChar, &lockChar, &unlockChar, &uriDataChar,
00169             &flagsChar, &advPowerLevelsChar, &txPowerModeChar, &beaconPeriodChar, &resetChar
00170         };
00171 
00172         GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));
00173 
00174         ble.addService(configService);
00175         ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback);
00176     }
00177 
00178     /**
00179      * @brief Start EddystoneConfig advertising. This function should be called
00180      * after the EddystoneConfig constructor and after all the frames have been added.
00181      *
00182      * @param[in]   resetToDefaultsFlag
00183      *                    Applies to the state of the 'paramsIn' parameter.
00184      *                    If true, it indicates that paramsIn is potentially
00185      *                    un-initialized, and default values should be used
00186      *                    instead. Otherwise, paramsIn overrides the defaults.
00187      */
00188     void start(bool resetToDefaultsFlag){
00189         INFO("reset to defaults flag = %d", resetToDefaultsFlag);
00190         if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) {
00191             INFO("Reset to Defaults triggered");
00192             resetToDefaultsFlag = true;
00193         }
00194 
00195         if (resetToDefaultsFlag) {
00196             resetToDefaults();
00197         } else {
00198             updateCharacteristicValues();
00199         }
00200 
00201         setupEddystoneConfigAdvertisements(); /* Set up advertising for the config service. */
00202         initSucceeded = true;
00203     }
00204 
00205     /*
00206     * Check if Eddystone initialized successfully.
00207     */
00208     bool initSuccessfully(void) const {
00209         return initSucceeded;
00210     }
00211 
00212     /*
00213     * @brief Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied.
00214     *
00215     * @param[in] tlmVersionIn     Version of the TLM frame being used.
00216     * @param[in] advPeriodInMin How long between TLM frames being advertised, measured in minutes.
00217     *
00218     */
00219     void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){
00220         DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f", tlmVersionIn, advPeriodInSec);
00221         defaultTlmVersion   = tlmVersionIn;
00222         TlmBatteryVoltage   = 0;
00223         TlmBeaconTemp       = 0x8000;
00224         TlmPduCount         = 0;
00225         TlmTimeSinceBoot    = 0;
00226         defaultTlmAdvPeriod = advPeriodInSec;
00227         tlmIsSet            = true; // Flag to add this to Eddystone service when config is done.
00228     }
00229 
00230     /*
00231     * @brief Function to update the default values for the URI frame. Only applied if Reset Defaults is applied.
00232     *
00233     * @param[in] uriIn      URL to advertise.
00234     * @param[in] advPeriod  How long to advertise the URL, measured in number of ADV frames.
00235     *
00236     */
00237     void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1){
00238         DBG("Setting Default URI Data");
00239         // Set URL Frame
00240         EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength);   // Encode URL to URL Formatting.
00241         if (defaultUriDataLength > URI_DATA_MAX) {
00242             return;
00243         }
00244         INFO("\t  URI input = %s : %d", uriIn, defaultUriDataLength);
00245         INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength );
00246         defaultUriAdvPeriod = advPeriod;
00247         urlIsSet            = true; // Flag to add this to Eddystone service when config is done.
00248     }
00249 
00250     /*
00251     * @brief Function to update the default values for the UID frame. Only applied if Reset Defaults is applied.
00252     *
00253     * @param[in] namespaceID 10Byte Namespace ID.
00254     * @param[in] instanceID  6Byte Instance ID.
00255     * @param[in] advPeriod   How long to advertise the URL, measured in the number of ADV frames.
00256     *
00257     */
00258     void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10){
00259         //Set UID frame
00260         DBG("Setting default UID Data");
00261         memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE);
00262         memcpy(defaultUidInstanceID,  instanceID,  UID_INSTANCEID_SIZE);
00263         defaultUidAdvPeriod = advPeriod;
00264         uidIsSet            = true; // Flag to add this to Eddystone service when config is done.
00265     }
00266 
00267     /* Start out by advertising the config service for a limited time after
00268      * startup, then switch to the normal non-connectible beacon functionality.
00269      */
00270     void setupEddystoneConfigAdvertisements() {
00271         const char DEVICE_NAME[] = "eddystone Config";
00272 
00273         ble.clearAdvertisingPayload();
00274 
00275         ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00276 
00277         // UUID is in a different order in the ADV frame (!)
00278         uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)];
00279         for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) {
00280             reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1];
00281         }
00282         ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID));
00283         ble.accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG);
00284         ble.accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast<const uint8_t *>(&DEVICE_NAME), sizeof(DEVICE_NAME));
00285         ble.accumulateScanResponse(
00286             GapAdvertisingData::TX_POWER_LEVEL,
00287             reinterpret_cast<uint8_t *>(&defaultAdvPowerLevels[EddystoneConfigService::TX_POWER_MODE_LOW]),
00288             sizeof(uint8_t));
00289 
00290         ble.setTxPower(radioPowerLevels[params.txPowerMode]);
00291         ble.setDeviceName(reinterpret_cast<const uint8_t *>(&DEVICE_NAME));
00292         ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00293         ble.setAdvertisingInterval(ADVERTISING_INTERVAL_MSEC);
00294     }
00295 
00296     /*
00297     *   This function actually impliments the Eddystone Beacon service. It can be called with the help of the wrapper function
00298     *   to load saved config params, or it can be called explicitly to reset the Eddystone beacon to hardcoded values on each reset.
00299     *
00300     */
00301     void setupEddystoneAdvertisements() {
00302         DBG("Switching Config -> adv");
00303         // Save params to storage.
00304         extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */
00305         saveURIBeaconConfigParams(&params);
00306         INFO("Saved Params to Memory.")
00307         // Set up Eddystone Service.
00308         static EddystoneService eddyServ(ble, params.beaconPeriod, radioPowerLevels[params.txPowerMode]);
00309         // Set configured frames (TLM, UID, URI and so on).
00310         if (params.tlmEnabled) {
00311             eddyServ.setTLMFrameData(params.tlmVersion, params.tlmBeaconPeriod);
00312         }
00313         if (params.uriEnabled) {
00314             eddyServ.setURLFrameEncodedData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriDataLength, params.uriBeaconPeriod);
00315         }
00316         if (params.uidEnabled) {
00317             eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode],
00318                                      (uint8_t *)params.uidNamespaceID,
00319                                      (uint8_t *)params.uidInstanceID,
00320                                      params.uidBeaconPeriod);
00321         }
00322         // Start advertising the Eddystone service.
00323         eddyServ.start();
00324     }
00325 
00326 private:
00327     /*
00328      * This callback is invoked when a GATT client attempts to modify any of the
00329      * characteristics of this service. Attempts to do so are also applied to
00330      * the internal state of this service object.
00331      */
00332     void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) {
00333         uint16_t handle = writeParams->handle;
00334 
00335         if (handle == lockChar.getValueHandle()) {
00336             // Validated earlier.
00337             memcpy(params.lock, writeParams->data, sizeof(Lock_t));
00338             // Set the state to be locked by the lock code (note: zeros are a valid lock).
00339             params.lockedState = true;
00340             INFO("Device Locked");
00341         } else if (handle == unlockChar.getValueHandle()) {
00342             // Validated earlier.
00343             params.lockedState = false;
00344             INFO("Device Unlocked");
00345         } else if (handle == uriDataChar.getValueHandle()) {
00346             params.uriDataLength = writeParams->len;
00347             memset(params.uriData, 0x00, URI_DATA_MAX);                      // Clear URI string.
00348             memcpy(params.uriData, writeParams->data, writeParams->len); // Set URI string.
00349             params.uriEnabled = true;
00350             INFO("URI = %s, URILen = %d", writeParams->data, writeParams->len);
00351         } else if (handle == flagsChar.getValueHandle()) {
00352             params.flags = *(writeParams->data);
00353             INFO("flagsChar = 0x%x", params.flags);
00354         } else if (handle == advPowerLevelsChar.getValueHandle()) {
00355             memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t));
00356             INFO("PowerLevelsChar = %4x", params.advPowerLevels);
00357         } else if (handle == txPowerModeChar.getValueHandle()) {
00358             params.txPowerMode = *(writeParams->data);
00359             INFO("TxPowerModeChar = %d", params.txPowerMode);
00360         } else if (handle == beaconPeriodChar.getValueHandle()) {
00361             params.beaconPeriod = *((uint16_t *)(writeParams->data));
00362             INFO("BeaconPeriod = %d", params.beaconPeriod);
00363 
00364             /* Re-map beaconPeriod to within permissible bounds if necessary. */
00365             if (params.beaconPeriod != 0) {
00366                 bool paramsUpdated = false;
00367                 if (params.beaconPeriod < ble.getMinAdvertisingInterval()) {
00368                     params.beaconPeriod = ble.getMinAdvertisingInterval();
00369                     paramsUpdated       = true;
00370                 } else if (params.beaconPeriod > ble.getMaxAdvertisingInterval()) {
00371                     params.beaconPeriod = ble.getMaxAdvertisingInterval();
00372                     paramsUpdated       = true;
00373                 }
00374                 if (paramsUpdated) {
00375                     ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast<uint8_t *>(&params.beaconPeriod), sizeof(uint16_t));
00376                 }
00377             }
00378         } else if (handle == resetChar.getValueHandle()) {
00379             INFO("Reset triggered from Config Service, resetting to defaults");
00380             resetToDefaults();
00381         }
00382         updateCharacteristicValues();
00383         params.isConfigured = true; // Some configuration data has been passed; on disconnect switch to advertising mode.
00384     }
00385 
00386     /*
00387      * Reset the default values.
00388      */
00389     void resetToDefaults(void) {
00390         INFO("Resetting to defaults");
00391         // General.
00392         params.lockedState = false;
00393         memset(params.lock, 0, sizeof(Lock_t));
00394         params.flags = 0x10;
00395         memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t));
00396         params.txPowerMode  = TX_POWER_MODE_LOW;
00397         params.beaconPeriod = (uint16_t) defaultUriAdvPeriod * 1000;
00398 
00399         // TLM Frame.
00400         params.tlmVersion      = defaultTlmVersion;
00401         params.tlmBeaconPeriod = defaultTlmAdvPeriod;
00402         params.tlmEnabled      = tlmIsSet;
00403 
00404         // URL Frame.
00405         memcpy(params.uriData, defaultUriData, URI_DATA_MAX);
00406         params.uriDataLength   = defaultUriDataLength;
00407         params.uriBeaconPeriod = defaultUriAdvPeriod;
00408         params.uriEnabled      = urlIsSet;
00409 
00410         // UID Frame.
00411         memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE);
00412         memcpy(params.uidInstanceID,  defaultUidInstanceID,  UID_INSTANCEID_SIZE);
00413         params.uidBeaconPeriod = defaultUidAdvPeriod;
00414         params.uidEnabled      = uidIsSet;
00415 
00416         updateCharacteristicValues();
00417     }
00418 
00419     /*
00420      * Internal helper function used to update the GATT database following any
00421      * change to the internal state of the service object.
00422      */
00423     void updateCharacteristicValues(void) {
00424         ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), &params.lockedState, 1);
00425         ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength);
00426         ble.updateCharacteristicValue(flagsChar.getValueHandle(), &params.flags, 1);
00427         ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(),
00428                                       reinterpret_cast<uint8_t *>(&params.beaconPeriod), sizeof(uint16_t));
00429         ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), &params.txPowerMode, 1);
00430         ble.updateCharacteristicValue(advPowerLevelsChar.getValueHandle(),
00431                                       reinterpret_cast<uint8_t *>(params.advPowerLevels), sizeof(PowerLevels_t));
00432     }
00433 
00434 private:
00435     void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00436         if (params.lockedState) {
00437             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00438         } else if (authParams->len != sizeof(Lock_t)) {
00439             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00440         } else if (authParams->offset != 0) {
00441             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00442         } else {
00443             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00444         }
00445     }
00446 
00447     void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00448         if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) {
00449             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00450         } else if (authParams->len != sizeof(Lock_t)) {
00451             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00452         } else if (authParams->offset != 0) {
00453             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00454         } else if (memcmp(authParams->data, params.lock, sizeof(Lock_t)) != 0) {
00455             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00456         } else {
00457             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00458         }
00459     }
00460 
00461     void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00462         if (params.lockedState) {
00463             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00464         } else if (authParams->offset != 0) {
00465             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00466         } else {
00467             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00468         }
00469     }
00470 
00471     void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00472         if (params.lockedState) {
00473             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00474         } else if (authParams->len != sizeof(uint8_t)) {
00475             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00476         } else if (authParams->offset != 0) {
00477             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00478         } else if (*((uint8_t *)authParams->data) >= NUM_POWER_MODES) {
00479             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED;
00480         } else {
00481             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00482         }
00483     }
00484 
00485     template <typename T>
00486     void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00487         if (params.lockedState) {
00488             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00489         } else if (authParams->len != sizeof(T)) {
00490             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00491         } else if (authParams->offset != 0) {
00492             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00493         } else {
00494             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00495         }
00496     }
00497 
00498     BLEDevice                                  &ble;
00499     Params_t                                   &params;
00500     Ticker                                     timeSinceBootTick;
00501     Timeout                                    switchFrame;
00502     // Default value that is restored on reset.
00503     PowerLevels_t                              &defaultAdvPowerLevels; // This goes into the advertising frames (radio power measured at 1m from device).
00504     PowerLevels_t                              &radioPowerLevels;      // This configures the power levels of the radio.
00505     uint8_t                                    lockedState;
00506     bool                                       initSucceeded;
00507     uint8_t                                    resetFlag;
00508     bool                                       switchFlag;
00509 
00510     //UID default value that is restored on reset.
00511     UIDNamespaceID_t                           defaultUidNamespaceID;
00512     UIDInstanceID_t                            defaultUidInstanceID;
00513     float                                      defaultUidAdvPeriod;
00514     int8_t                                     defaultUidPower;
00515     uint16_t                                   uidRFU;
00516     bool                                       uidIsSet;
00517 
00518     //URI default value that is restored on reset.
00519     uint8_t                                    defaultUriDataLength;
00520     UriData_t                                  defaultUriData;
00521     int8_t                                     defaultUrlPower;
00522     float                                      defaultUriAdvPeriod;
00523     bool                                       urlIsSet;
00524 
00525     //TLM default value that is restored on reset.
00526     uint8_t                                    defaultTlmVersion;
00527     float                                      defaultTlmAdvPeriod;
00528     volatile uint16_t                          TlmBatteryVoltage;
00529     volatile uint16_t                          TlmBeaconTemp;
00530     volatile uint32_t                          TlmPduCount;
00531     volatile uint32_t                          TlmTimeSinceBoot;
00532     bool                                       tlmIsSet;
00533 
00534     ReadOnlyGattCharacteristic<uint8_t>         lockedStateChar;
00535     WriteOnlyGattCharacteristic<Lock_t>         lockChar;
00536     GattCharacteristic                         uriDataChar;
00537     WriteOnlyGattCharacteristic<Lock_t>         unlockChar;
00538     ReadWriteGattCharacteristic<uint8_t>        flagsChar;
00539     ReadWriteGattCharacteristic<PowerLevels_t>  advPowerLevelsChar;
00540     ReadWriteGattCharacteristic<uint8_t>        txPowerModeChar;
00541     ReadWriteGattCharacteristic<uint16_t>       beaconPeriodChar;
00542     WriteOnlyGattCharacteristic<uint8_t>        resetChar;
00543 };
00544 
00545 #endif  // SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_