adaptation for book and plug demo

Dependents:   BookAndPlug

Fork of BLE_API by Bluetooth Low Energy

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[ref]    ble
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     EddystoneConfigService (BLEDevice     &bleIn,
00124                            Params_t      &paramsIn,
00125                            PowerLevels_t &defaultAdvPowerLevelsIn,
00126                            PowerLevels_t &radioPowerLevelsIn) :
00127         ble(bleIn),
00128         params(paramsIn),       // Initialize URL data.
00129         defaultAdvPowerLevels(defaultAdvPowerLevelsIn),
00130         radioPowerLevels(radioPowerLevelsIn),
00131         initSucceeded(false),
00132         resetFlag(),
00133         defaultUidNamespaceID(), // Initialize UID data.
00134         defaultUidInstanceID(),
00135         defaultUidPower(defaultAdvPowerLevelsIn[params.txPowerMode]),
00136         uidIsSet(false),
00137         defaultUriDataLength(),
00138         defaultUriData(),
00139         defaultUrlPower(defaultAdvPowerLevelsIn[params.txPowerMode]),
00140         urlIsSet(false),
00141         tlmIsSet(false),
00142         lockedStateChar(UUID_LOCK_STATE_CHAR, &params.lockedState),
00143         lockChar(UUID_LOCK_CHAR, &params.lock),
00144         uriDataChar(UUID_URI_DATA_CHAR, params.uriData, 0, URI_DATA_MAX,
00145                     GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE),
00146         unlockChar(UUID_UNLOCK_CHAR, &params.lock),
00147         flagsChar(UUID_FLAGS_CHAR, &params.flags),
00148         advPowerLevelsChar(UUID_ADV_POWER_LEVELS_CHAR, &params.advPowerLevels),
00149         txPowerModeChar(UUID_TX_POWER_MODE_CHAR, &params.txPowerMode),
00150         beaconPeriodChar(UUID_BEACON_PERIOD_CHAR, &params.beaconPeriod),
00151         resetChar(UUID_RESET_CHAR, &resetFlag) {
00152         // Set Eddystone as not configured yet. Used to exit config before timeout if GATT services are written to.
00153         params.isConfigured = false;
00154 
00155         lockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::lockAuthorizationCallback);
00156         unlockChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::unlockAuthorizationCallback);
00157         uriDataChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::uriDataWriteAuthorizationCallback);
00158         flagsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>);
00159         advPowerLevelsChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<PowerLevels_t>);
00160         txPowerModeChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::powerModeAuthorizationCallback);
00161         beaconPeriodChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint16_t>);
00162         resetChar.setWriteAuthorizationCallback(this, &EddystoneConfigService::basicAuthorizationCallback<uint8_t>);
00163 
00164         static GattCharacteristic *charTable[] = {
00165             &lockedStateChar, &lockChar, &unlockChar, &uriDataChar,
00166             &flagsChar, &advPowerLevelsChar, &txPowerModeChar, &beaconPeriodChar, &resetChar
00167         };
00168 
00169         GattService configService(UUID_URI_BEACON_SERVICE, charTable, sizeof(charTable) / sizeof(GattCharacteristic *));
00170 
00171         ble.addService(configService);
00172         ble.onDataWritten(this, &EddystoneConfigService::onDataWrittenCallback);
00173     }
00174 
00175     /**
00176      * @brief Start EddystoneConfig advertising. This function should be called
00177      * after the EddystoneConfig constructor and after all the frames have been added.
00178      *
00179      * @paramsP[in]   resetToDefaultsFlag
00180      *                    Applies to the state of the 'paramsIn' parameter.
00181      *                    If true, it indicates that paramsIn is potentially
00182      *                    un-initialized, and default values should be used
00183      *                    instead. Otherwise, paramsIn overrides the defaults.
00184      */
00185     void start(bool resetToDefaultsFlag){
00186         INFO("reset to defaults flag = %d", resetToDefaultsFlag);
00187         if (!resetToDefaultsFlag && (params.uriDataLength > URI_DATA_MAX)) {
00188             INFO("Reset to Defaults triggered");
00189             resetToDefaultsFlag = true;
00190         }
00191 
00192         if (resetToDefaultsFlag) {
00193             resetToDefaults();
00194         } else {
00195             updateCharacteristicValues();
00196         }
00197 
00198         setupEddystoneConfigAdvertisements(); /* Set up advertising for the config service. */
00199         initSucceeded = true;
00200     }
00201 
00202     /*
00203     * Check if Eddystone initialized successfully.
00204     */
00205     bool initSuccessfully(void) const {
00206         return initSucceeded;
00207     }
00208 
00209     /*
00210     * @brief Function to update the default values for the TLM frame. Only applied if Reset Defaults is applied.
00211     *
00212     * @param[in] tlmVersionIn     Version of the TLM frame being used.
00213     * @param[in] advPeriodInMin How long between TLM frames being advertised, measured in minutes.
00214     *
00215     */
00216     void setDefaultTLMFrameData(uint8_t tlmVersionIn = 0, float advPeriodInSec = 60){
00217         DBG("Setting Default TLM Data, version = %d, advPeriodInMind= %f", tlmVersionIn, advPeriodInSec);
00218         defaultTlmVersion   = tlmVersionIn;
00219         TlmBatteryVoltage   = 0;
00220         TlmBeaconTemp       = 0x8000;
00221         TlmPduCount         = 0;
00222         TlmTimeSinceBoot    = 0;
00223         defaultTlmAdvPeriod = advPeriodInSec;
00224         tlmIsSet            = true; // Flag to add this to Eddystone service when config is done.
00225     }
00226 
00227     /*
00228     * @brief Function to update the default values for the URI frame. Only applied if Reset Defaults is applied.
00229     *
00230     * @param[in] uriIn      URL to advertise.
00231     * @param[in] advPeriod  How long to advertise the URL, measured in number of ADV frames.
00232     *
00233     */
00234     void setDefaultURIFrameData(const char *uriIn, float advPeriod = 1){
00235         DBG("Setting Default URI Data");
00236         // Set URL Frame
00237         EddystoneService::encodeURL(uriIn, defaultUriData, defaultUriDataLength);   // Encode URL to URL Formatting.
00238         if (defaultUriDataLength > URI_DATA_MAX) {
00239             return;
00240         }
00241         INFO("\t  URI input = %s : %d", uriIn, defaultUriDataLength);
00242         INFO("\t default URI = %s : %d ", defaultUriData, defaultUriDataLength );
00243         defaultUriAdvPeriod = advPeriod;
00244         urlIsSet            = true; // Flag to add this to Eddystone service when config is done.
00245     }
00246 
00247     /*
00248     * @brief Function to update the default values for the UID frame. Only applied if Reset Defaults is applied.
00249     *
00250     * @param[in] namespaceID 10Byte Namespace ID.
00251     * @param[in] instanceID  6Byte Instance ID.
00252     * @param[in] advPeriod   How long to advertise the URL, measured in the number of ADV frames.
00253     *
00254     */
00255     void setDefaultUIDFrameData(UIDNamespaceID_t *namespaceID, UIDInstanceID_t *instanceID, float advPeriod = 10){
00256         //Set UID frame
00257         DBG("Setting default UID Data");
00258         memcpy(defaultUidNamespaceID, namespaceID, UID_NAMESPACEID_SIZE);
00259         memcpy(defaultUidInstanceID,  instanceID,  UID_INSTANCEID_SIZE);
00260         defaultUidAdvPeriod = advPeriod;
00261         uidIsSet            = true; // Flag to add this to Eddystone service when config is done.
00262     }
00263 
00264     /* Start out by advertising the config service for a limited time after
00265      * startup, then switch to the normal non-connectible beacon functionality.
00266      */
00267     void setupEddystoneConfigAdvertisements() {
00268         const char DEVICE_NAME[] = "eddystone Config";
00269 
00270         ble.clearAdvertisingPayload();
00271 
00272         ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00273 
00274         // UUID is in a different order in the ADV frame (!)
00275         uint8_t reversedServiceUUID[sizeof(UUID_URI_BEACON_SERVICE)];
00276         for (unsigned int i = 0; i < sizeof(UUID_URI_BEACON_SERVICE); i++) {
00277             reversedServiceUUID[i] = UUID_URI_BEACON_SERVICE[sizeof(UUID_URI_BEACON_SERVICE) - i - 1];
00278         }
00279         ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, reversedServiceUUID, sizeof(reversedServiceUUID));
00280         ble.accumulateAdvertisingPayload(GapAdvertisingData::GENERIC_TAG);
00281         ble.accumulateScanResponse(GapAdvertisingData::COMPLETE_LOCAL_NAME, reinterpret_cast<const uint8_t *>(&DEVICE_NAME), sizeof(DEVICE_NAME));
00282         ble.accumulateScanResponse(
00283             GapAdvertisingData::TX_POWER_LEVEL,
00284             reinterpret_cast<uint8_t *>(&defaultAdvPowerLevels[EddystoneConfigService::TX_POWER_MODE_LOW]),
00285             sizeof(uint8_t));
00286 
00287         ble.setTxPower(radioPowerLevels[params.txPowerMode]);
00288         ble.setDeviceName(reinterpret_cast<const uint8_t *>(&DEVICE_NAME));
00289         ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00290         ble.setAdvertisingInterval (ADVERTISING_INTERVAL_MSEC);
00291     }
00292 
00293     /*
00294     *   This function actually impliments the Eddystone Beacon service. It can be called with the help of the wrapper function
00295     *   to load saved config params, or it can be called explicitly to reset the Eddystone beacon to hardcoded values on each reset.
00296     *
00297     */
00298     void setupEddystoneAdvertisements() {
00299         DBG("Switching Config -> adv");
00300         // Save params to storage.
00301         extern void saveURIBeaconConfigParams(const Params_t *paramsP); /* forward declaration; necessary to avoid a circular dependency. */
00302         saveURIBeaconConfigParams(&params);
00303         INFO("Saved Params to Memory.")
00304         // Set up Eddystone Service.
00305         static EddystoneService eddyServ(ble, params.beaconPeriod, radioPowerLevels[params.txPowerMode]);
00306         // Set configured frames (TLM, UID, URI and so on).
00307         if (params.tlmEnabled) {
00308             eddyServ.setTLMFrameData(params.tlmVersion, params.tlmBeaconPeriod);
00309         }
00310         if (params.uriEnabled) {
00311             eddyServ.setURLFrameEncodedData(params.advPowerLevels[params.txPowerMode], (const char *) params.uriData, params.uriDataLength, params.uriBeaconPeriod);
00312         }
00313         if (params.uidEnabled) {
00314             eddyServ.setUIDFrameData(params.advPowerLevels[params.txPowerMode],
00315                                      (uint8_t *)params.uidNamespaceID,
00316                                      (uint8_t *)params.uidInstanceID,
00317                                      params.uidBeaconPeriod);
00318         }
00319         // Start advertising the Eddystone service.
00320         eddyServ.start();
00321     }
00322 
00323 private:
00324     /*
00325      * This callback is invoked when a GATT client attempts to modify any of the
00326      * characteristics of this service. Attempts to do so are also applied to
00327      * the internal state of this service object.
00328      */
00329     void onDataWrittenCallback(const GattWriteCallbackParams *writeParams) {
00330         uint16_t handle = writeParams->handle;
00331 
00332         if (handle == lockChar.getValueHandle()) {
00333             // Validated earlier.
00334             memcpy(params.lock, writeParams->data, sizeof(Lock_t));
00335             // Set the state to be locked by the lock code (note: zeros are a valid lock).
00336             params.lockedState = true;
00337             INFO("Device Locked");
00338         } else if (handle == unlockChar.getValueHandle()) {
00339             // Validated earlier.
00340             params.lockedState = false;
00341             INFO("Device Unlocked");
00342         } else if (handle == uriDataChar.getValueHandle()) {
00343             params.uriDataLength = writeParams->len;
00344             memset(params.uriData, 0x00, URI_DATA_MAX);                      // Clear URI string.
00345             memcpy(params.uriData, writeParams->data, writeParams->len); // Set URI string.
00346             params.uriEnabled = true;
00347             INFO("URI = %s, URILen = %d", writeParams->data, writeParams->len);
00348         } else if (handle == flagsChar.getValueHandle()) {
00349             params.flags = *(writeParams->data);
00350             INFO("flagsChar = 0x%x", params.flags);
00351         } else if (handle == advPowerLevelsChar.getValueHandle()) {
00352             memcpy(params.advPowerLevels, writeParams->data, sizeof(PowerLevels_t));
00353             INFO("PowerLevelsChar = %4x", params.advPowerLevels);
00354         } else if (handle == txPowerModeChar.getValueHandle()) {
00355             params.txPowerMode = *(writeParams->data);
00356             INFO("TxPowerModeChar = %d", params.txPowerMode);
00357         } else if (handle == beaconPeriodChar.getValueHandle()) {
00358             params.beaconPeriod = *((uint16_t *)(writeParams->data));
00359             INFO("BeaconPeriod = %d", params.beaconPeriod);
00360 
00361             /* Re-map beaconPeriod to within permissible bounds if necessary. */
00362             if (params.beaconPeriod != 0) {
00363                 bool paramsUpdated = false;
00364                 if (params.beaconPeriod < ble.getMinAdvertisingInterval()) {
00365                     params.beaconPeriod = ble.getMinAdvertisingInterval();
00366                     paramsUpdated       = true;
00367                 } else if (params.beaconPeriod > ble.getMaxAdvertisingInterval()) {
00368                     params.beaconPeriod = ble.getMaxAdvertisingInterval();
00369                     paramsUpdated       = true;
00370                 }
00371                 if (paramsUpdated) {
00372                     ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(), reinterpret_cast<uint8_t *>(&params.beaconPeriod), sizeof(uint16_t));
00373                 }
00374             }
00375         } else if (handle == resetChar.getValueHandle()) {
00376             INFO("Reset triggered from Config Service, resetting to defaults");
00377             resetToDefaults();
00378         }
00379         updateCharacteristicValues();
00380         params.isConfigured = true; // Some configuration data has been passed; on disconnect switch to advertising mode.
00381     }
00382 
00383     /*
00384      * Reset the default values.
00385      */
00386     void resetToDefaults(void) {
00387         INFO("Resetting to defaults");
00388         // General.
00389         params.lockedState = false;
00390         memset(params.lock, 0, sizeof(Lock_t));
00391         params.flags = 0x10;
00392         memcpy(params.advPowerLevels, defaultAdvPowerLevels, sizeof(PowerLevels_t));
00393         params.txPowerMode  = TX_POWER_MODE_LOW;
00394         params.beaconPeriod = (uint16_t) defaultUriAdvPeriod * 1000;
00395 
00396         // TLM Frame.
00397         params.tlmVersion      = defaultTlmVersion;
00398         params.tlmBeaconPeriod = defaultTlmAdvPeriod;
00399         params.tlmEnabled      = tlmIsSet;
00400 
00401         // URL Frame.
00402         memcpy(params.uriData, defaultUriData, URI_DATA_MAX);
00403         params.uriDataLength   = defaultUriDataLength;
00404         params.uriBeaconPeriod = defaultUriAdvPeriod;
00405         params.uriEnabled      = urlIsSet;
00406 
00407         // UID Frame.
00408         memcpy(params.uidNamespaceID, defaultUidNamespaceID, UID_NAMESPACEID_SIZE);
00409         memcpy(params.uidInstanceID,  defaultUidInstanceID,  UID_INSTANCEID_SIZE);
00410         params.uidBeaconPeriod = defaultUidAdvPeriod;
00411         params.uidEnabled      = uidIsSet;
00412 
00413         updateCharacteristicValues();
00414     }
00415 
00416     /*
00417      * Internal helper function used to update the GATT database following any
00418      * change to the internal state of the service object.
00419      */
00420     void updateCharacteristicValues(void) {
00421         ble.updateCharacteristicValue(lockedStateChar.getValueHandle(), &params.lockedState, 1);
00422         ble.updateCharacteristicValue(uriDataChar.getValueHandle(), params.uriData, params.uriDataLength);
00423         ble.updateCharacteristicValue(flagsChar.getValueHandle(), &params.flags, 1);
00424         ble.updateCharacteristicValue(beaconPeriodChar.getValueHandle(),
00425                                       reinterpret_cast<uint8_t *>(&params.beaconPeriod), sizeof(uint16_t));
00426         ble.updateCharacteristicValue(txPowerModeChar.getValueHandle(), &params.txPowerMode, 1);
00427         ble.updateCharacteristicValue(advPowerLevelsChar.getValueHandle(),
00428                                       reinterpret_cast<uint8_t *>(params.advPowerLevels), sizeof(PowerLevels_t));
00429     }
00430 
00431 private:
00432     void lockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00433         if (params.lockedState) {
00434             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00435         } else if (authParams->len != sizeof(Lock_t)) {
00436             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00437         } else if (authParams->offset != 0) {
00438             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00439         } else {
00440             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00441         }
00442     }
00443 
00444     void unlockAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00445         if ((!params.lockedState) && (authParams->len == sizeof(Lock_t))) {
00446             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00447         } else if (authParams->len != sizeof(Lock_t)) {
00448             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00449         } else if (authParams->offset != 0) {
00450             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00451         } else if (memcmp(authParams->data, params.lock, sizeof(Lock_t)) != 0) {
00452             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00453         } else {
00454             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00455         }
00456     }
00457 
00458     void uriDataWriteAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00459         if (params.lockedState) {
00460             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00461         } else if (authParams->offset != 0) {
00462             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00463         } else {
00464             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00465         }
00466     }
00467 
00468     void powerModeAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00469         if (params.lockedState) {
00470             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00471         } else if (authParams->len != sizeof(uint8_t)) {
00472             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00473         } else if (authParams->offset != 0) {
00474             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00475         } else if (*((uint8_t *)authParams->data) >= NUM_POWER_MODES) {
00476             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED;
00477         } else {
00478             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00479         }
00480     }
00481 
00482     template <typename T>
00483     void basicAuthorizationCallback(GattWriteAuthCallbackParams *authParams) {
00484         if (params.lockedState) {
00485             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INSUF_AUTHORIZATION;
00486         } else if (authParams->len != sizeof(T)) {
00487             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
00488         } else if (authParams->offset != 0) {
00489             authParams->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
00490         } else {
00491             authParams->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
00492         }
00493     }
00494 
00495     BLEDevice                                  &ble;
00496     Params_t                                   &params;
00497     Ticker                                     timeSinceBootTick;
00498     Timeout                                    switchFrame;
00499     // Default value that is restored on reset.
00500     PowerLevels_t                              &defaultAdvPowerLevels; // This goes into the advertising frames (radio power measured at 1m from device).
00501     PowerLevels_t                              &radioPowerLevels;      // This configures the power levels of the radio.
00502     uint8_t                                    lockedState;
00503     bool                                       initSucceeded;
00504     uint8_t                                    resetFlag;
00505     bool                                       switchFlag;
00506 
00507     //UID default value that is restored on reset.
00508     UIDNamespaceID_t                           defaultUidNamespaceID;
00509     UIDInstanceID_t                            defaultUidInstanceID;
00510     float                                      defaultUidAdvPeriod;
00511     int8_t                                     defaultUidPower;
00512     uint16_t                                   uidRFU;
00513     bool                                       uidIsSet;
00514 
00515     //URI default value that is restored on reset.
00516     uint8_t                                    defaultUriDataLength;
00517     UriData_t                                  defaultUriData;
00518     int8_t                                     defaultUrlPower;
00519     float                                      defaultUriAdvPeriod;
00520     bool                                       urlIsSet;
00521 
00522     //TLM default value that is restored on reset.
00523     uint8_t                                    defaultTlmVersion;
00524     float                                      defaultTlmAdvPeriod;
00525     volatile uint16_t                          TlmBatteryVoltage;
00526     volatile uint16_t                          TlmBeaconTemp;
00527     volatile uint32_t                          TlmPduCount;
00528     volatile uint32_t                          TlmTimeSinceBoot;
00529     bool                                       tlmIsSet;
00530 
00531     ReadOnlyGattCharacteristic<uint8_t>         lockedStateChar;
00532     WriteOnlyGattCharacteristic<Lock_t>         lockChar;
00533     GattCharacteristic                         uriDataChar;
00534     WriteOnlyGattCharacteristic<Lock_t>         unlockChar;
00535     ReadWriteGattCharacteristic<uint8_t>        flagsChar;
00536     ReadWriteGattCharacteristic<PowerLevels_t>  advPowerLevelsChar;
00537     ReadWriteGattCharacteristic<uint8_t>        txPowerModeChar;
00538     ReadWriteGattCharacteristic<uint16_t>       beaconPeriodChar;
00539     WriteOnlyGattCharacteristic<uint8_t>        resetChar;
00540 };
00541 
00542 #endif  // SERVICES_EDDYSTONE_BEACON_CONFIG_SERVICE_H_