KEN OGAMI / microbit-dal-iBeacon

Dependencies:   BLE_API mbed-dev-bin nRF51822

Fork of microbit-dal by Ken Ogami

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MicroBitBLEManager.cpp Source File

MicroBitBLEManager.cpp

00001 /*
00002 The MIT License (MIT)
00003 
00004 Copyright (c) 2016 British Broadcasting Corporation.
00005 This software is provided by Lancaster University by arrangement with the BBC.
00006 
00007 Permission is hereby granted, free of charge, to any person obtaining a
00008 copy of this software and associated documentation files (the "Software"),
00009 to deal in the Software without restriction, including without limitation
00010 the rights to use, copy, modify, merge, publish, distribute, sublicense,
00011 and/or sell copies of the Software, and to permit persons to whom the
00012 Software is furnished to do so, subject to the following conditions:
00013 
00014 The above copyright notice and this permission notice shall be included in
00015 all copies or substantial portions of the Software.
00016 
00017 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00018 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00019 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
00020 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00021 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
00022 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
00023 DEALINGS IN THE SOFTWARE.
00024 */
00025 
00026 
00027 
00028 #include "MicroBitConfig.h"
00029 #include "MicroBitBLEManager.h"
00030 #include "MicroBitEddystone.h"
00031 #include "MicroBitStorage.h"
00032 #include "MicroBitFiber.h"
00033 #include "MicroBitSystemTimer.h"
00034 #include "MicroBitIBeacon.h"
00035 
00036 /* The underlying Nordic libraries that support BLE do not compile cleanly with the stringent GCC settings we employ.
00037  * If we're compiling under GCC, then we suppress any warnings generated from this code (but not the rest of the DAL)
00038  * The ARM cc compiler is more tolerant. We don't test __GNUC__ here to detect GCC as ARMCC also typically sets this
00039  * as a compatability option, but does not support the options used...
00040  */
00041 #if !defined(__arm)
00042 #pragma GCC diagnostic ignored "-Wunused-function"
00043 #pragma GCC diagnostic push
00044 #pragma GCC diagnostic ignored "-Wunused-parameter"
00045 #endif
00046 
00047 #include "ble.h"
00048 
00049 extern "C" {
00050 #include "device_manager.h"
00051 uint32_t btle_set_gatt_table_size(uint32_t size);
00052 }
00053 
00054 /*
00055  * Return to our predefined compiler settings.
00056  */
00057 #if !defined(__arm)
00058 #pragma GCC diagnostic pop
00059 #endif
00060 
00061 #define MICROBIT_PAIRING_FADE_SPEED 4
00062 
00063 // Some Black Magic to compare the definition of our security mode in MicroBitConfig with a given parameter.
00064 // Required as the MicroBitConfig option is actually an mbed enum, that is not normally comparable at compile time.
00065 //
00066 
00067 #define __CAT(a, ...) a##__VA_ARGS__
00068 
00069 
00070 const char *MICROBIT_BLE_MANUFACTURER = NULL;
00071 const char *MICROBIT_BLE_MODEL = "BBC micro:bit";
00072 const char *MICROBIT_BLE_HARDWARE_VERSION = NULL;
00073 const char *MICROBIT_BLE_FIRMWARE_VERSION = MICROBIT_DAL_VERSION;
00074 const char *MICROBIT_BLE_SOFTWARE_VERSION = NULL;
00075 const int8_t MICROBIT_BLE_POWER_LEVEL[] = {-30, -20, -16, -12, -8, -4, 0, 4};
00076 
00077 /*
00078  * Many of the mbed interfaces we need to use only support callbacks to plain C functions, rather than C++ methods.
00079  * So, we maintain a pointer to the MicroBitBLEManager that's in use. Ths way, we can still access resources on the micro:bit
00080  * whilst keeping the code modular.
00081  */
00082 MicroBitBLEManager *MicroBitBLEManager::manager = NULL; // Singleton reference to the BLE manager. many mbed BLE API callbacks still do not support member funcions yet. :-(
00083 
00084 
00085 
00086 /**
00087  * Constructor.
00088  * Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack.
00089  * @param _storage an instance of MicroBitStorage used to persist sys attribute information. (This is required for compatability with iOS).
00090  * @note The BLE stack *cannot*  be brought up in a static context (the software simply hangs or corrupts itself).
00091  * Hence, the init() member function should be used to initialise the BLE stack.
00092  */
00093 MicroBitBLEManager::MicroBitBLEManager(MicroBitStorage &_storage) : storage(&_storage)
00094 {
00095     manager = this;
00096     this->ble = NULL;
00097     this->pairingStatus = 0;
00098 }
00099 
00100 /**
00101  * Constructor.
00102  * Configure and manage the micro:bit's Bluetooth Low Energy (BLE) stack.
00103  * @note The BLE stack *cannot*  be brought up in a static context (the software simply hangs or corrupts itself).
00104  * Hence, the init() member function should be used to initialise the BLE stack.
00105  */
00106 MicroBitBLEManager::MicroBitBLEManager() : storage(NULL)
00107 {
00108     manager = this;
00109     this->ble = NULL;
00110     this->pairingStatus = 0;
00111 }
00112 
00113 /**
00114  * When called, the micro:bit will begin advertising for a predefined period,
00115  * MICROBIT_BLE_ADVERTISING_TIMEOUT seconds to bonded devices.
00116  */
00117 MicroBitBLEManager *MicroBitBLEManager::getInstance()
00118 {
00119     if (manager == 0)
00120     {
00121         manager = new MicroBitBLEManager;
00122     }
00123     return manager;
00124 }
00125 
00126 /**
00127  * When called, the micro:bit will begin advertising for a predefined period,
00128  * MICROBIT_BLE_ADVERTISING_TIMEOUT seconds to bonded devices.
00129  */
00130 void MicroBitBLEManager::advertise()
00131 {
00132     if (ble)
00133         ble->gap().startAdvertising();
00134 }
00135 
00136 /**
00137   * Post constructor initialisation method as the BLE stack cannot be brought
00138   * up in a static context.
00139   * @param deviceName The name used when advertising
00140   * @param serialNumber The serial number exposed by the device information service
00141   * @param messageBus An instance of an EventModel, used during pairing.
00142   * @param enableBonding If true, the security manager enabled bonding.
00143   * @code
00144   * bleManager.init(uBit.getName(), uBit.getSerial(), uBit.messageBus, true);
00145   * @endcode
00146   */
00147 void MicroBitBLEManager::init(ManagedString deviceName, ManagedString serialNumber, EventModel &messageBus, bool enableBonding)
00148 {
00149     ManagedString BLEName("BBC micro:bit");
00150     this->deviceName = deviceName;
00151 
00152 //wlw #if !(CONFIG_ENABLED(MICROBIT_BLE_WHITELIST))
00153     ManagedString namePrefix(" [");
00154     ManagedString namePostfix("]");
00155     BLEName = BLEName + namePrefix + deviceName + namePostfix;
00156 //wlw #endif
00157 
00158 // Start the BLE stack.
00159 #if CONFIG_ENABLED(MICROBIT_HEAP_REUSE_SD)
00160     btle_set_gatt_table_size(MICROBIT_SD_GATT_TABLE_SIZE);
00161 #endif
00162 
00163     ble = new BLEDevice();
00164     ble->init();
00165 
00166 
00167     // Configure the stack to hold onto the CPU during critical timing events.
00168     // mbed-classic performs __disable_irq() calls in its timers that can cause
00169     // MIC failures on secure BLE channels...
00170     ble_common_opt_radio_cpu_mutex_t opt;
00171     opt.enable = 1;
00172     sd_ble_opt_set(BLE_COMMON_OPT_RADIO_CPU_MUTEX, (const ble_opt_t *)&opt);
00173 
00174 
00175 
00176     // Configure the radio at our default power level
00177 //    setTransmitPower(MICROBIT_BLE_DEFAULT_TX_POWER);
00178     // use higher power setting for iOS nrf Connect
00179     setTransmitPower(6);
00180 
00181 // Bring up core BLE services.
00182 #if CONFIG_ENABLED(MICROBIT_BLE_DFU_SERVICE)
00183     new MicroBitDFUService(*ble);
00184 #endif
00185 
00186 #if CONFIG_ENABLED(MICROBIT_BLE_DEVICE_INFORMATION_SERVICE)
00187     DeviceInformationService ble_device_information_service(*ble, MICROBIT_BLE_MANUFACTURER, MICROBIT_BLE_MODEL, serialNumber.toCharArray(), MICROBIT_BLE_HARDWARE_VERSION, MICROBIT_BLE_FIRMWARE_VERSION, MICROBIT_BLE_SOFTWARE_VERSION);
00188 #else
00189     (void)serialNumber;
00190 #endif
00191 
00192 #if CONFIG_ENABLED(MICROBIT_BLE_EVENT_SERVICE)
00193     new MicroBitEventService(*ble, messageBus);
00194 #else
00195     (void)messageBus;
00196 #endif
00197 
00198 
00199 // Setup advertising.
00200 #if CONFIG_ENABLED(MICROBIT_BLE_WHITELIST)
00201     ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
00202 #else
00203     ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00204 #endif
00205 
00206     ble->accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)BLEName.toCharArray(), BLEName.length());
00207     ble->setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
00208     ble->setAdvertisingInterval(200);
00209 
00210 #if (MICROBIT_BLE_ADVERTISING_TIMEOUT > 0)
00211     ble->gap().setAdvertisingTimeout(MICROBIT_BLE_ADVERTISING_TIMEOUT);
00212 #endif
00213     ble->gap().startAdvertising();
00214 }
00215 
00216 
00217 /**
00218  * Change the output power level of the transmitter to the given value.
00219  * @param power a value in the range 0..7, where 0 is the lowest power and 7 is the highest.
00220  * @return MICROBIT_OK on success, or MICROBIT_INVALID_PARAMETER if the value is out of range.
00221  * @code
00222  * // maximum transmission power.
00223  * bleManager.setTransmitPower(7);
00224  * @endcode
00225  */
00226 int MicroBitBLEManager::setTransmitPower(int power)
00227 {
00228     if (power < 0 || power >= MICROBIT_BLE_POWER_LEVELS)
00229         return MICROBIT_INVALID_PARAMETER;
00230 
00231     if (ble->gap().setTxPower(MICROBIT_BLE_POWER_LEVEL[power]) != NRF_SUCCESS)
00232         return MICROBIT_NOT_SUPPORTED;
00233 
00234     return MICROBIT_OK;
00235 }
00236 
00237 
00238 
00239 
00240 /**
00241  * Periodic callback in thread context.
00242  * We use this here purely to safely issue a disconnect operation after a pairing operation is complete.
00243  */
00244 void MicroBitBLEManager::idleTick()
00245 {
00246 
00247 }  
00248 
00249 
00250 /**
00251 * Stops any currently running BLE advertisements
00252 */
00253 void MicroBitBLEManager::stopAdvertising()
00254 {
00255     ble->gap().stopAdvertising();
00256 }
00257 
00258 #if CONFIG_ENABLED(MICROBIT_BLE_EDDYSTONE_URL)
00259 /**
00260   * Set the content of Eddystone URL frames
00261   * @param url The url to broadcast
00262   * @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
00263   * @param connectable true to keep bluetooth connectable for other services, false otherwise. (Defaults to true)
00264   * @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
00265   * @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
00266   * More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
00267   */
00268 int MicroBitBLEManager::advertiseEddystoneUrl(const char* url, int8_t calibratedPower, bool connectable, uint16_t interval)
00269 {
00270     ble->gap().stopAdvertising();
00271     ble->clearAdvertisingPayload();
00272 
00273     ble->setAdvertisingType(connectable ? GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED : GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED);
00274     ble->setAdvertisingInterval(interval);
00275 
00276     ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00277 
00278     int ret = MicroBitEddystone::getInstance()->setURL(ble, url, calibratedPower);
00279 
00280 #if (MICROBIT_BLE_ADVERTISING_TIMEOUT > 0)
00281     ble->gap().setAdvertisingTimeout(MICROBIT_BLE_ADVERTISING_TIMEOUT);
00282 #endif
00283     ble->gap().startAdvertising();
00284     
00285     return ret;
00286 }
00287 
00288 /**
00289   * Set the content of Eddystone URL frames, but accepts a ManagedString as a url.
00290   * @param url The url to broadcast
00291   * @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
00292   * @param connectable true to keep bluetooth connectable for other services, false otherwise. (Defaults to true)
00293   * @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
00294   * @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
00295   * More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
00296   */
00297 int MicroBitBLEManager::advertiseEddystoneUrl(ManagedString url, int8_t calibratedPower, bool connectable, uint16_t interval)
00298 {
00299     return advertiseEddystoneUrl((char *)url.toCharArray(), calibratedPower, connectable, interval);
00300 }
00301 #endif
00302 
00303 /**
00304   * Set the content of Eddystone URL frames
00305   *
00306   * @param proximityUUID 16-byte proximity UUID
00307   *
00308   * @param major 2-byte major value
00309   *
00310   * @param minor 2-byte minor value
00311   *
00312   * @param calibratedPower the transmission range of the beacon (Defaults to: 0xF0 ~10m).
00313   *
00314   * @param interval the rate at which the micro:bit will advertise url frames. (Defaults to MICROBIT_BLE_EDDYSTONE_ADV_INTERVAL)
00315   *
00316   * @note The calibratedPower value ranges from -100 to +20 to a resolution of 1. The calibrated power should be binary encoded.
00317   * More information can be found at https://github.com/google/eddystone/tree/master/eddystone-uid#tx-power
00318   */
00319 int MicroBitBLEManager::advertiseIBeacon(const UUID &proximityUUID, int16_t major, int16_t minor, int8_t calibratedPower, uint16_t interval)
00320 {
00321     int retVal = MICROBIT_OK;
00322 
00323     ble->gap().stopAdvertising();
00324     ble->clearAdvertisingPayload();
00325 
00326     ble->setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED);
00327     ble->setAdvertisingInterval(interval);
00328 
00329     ble->accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
00330 
00331     retVal = MicroBitIBeacon::getInstance()->setParams(ble, proximityUUID, major, minor, calibratedPower);
00332 
00333 #if (MICROBIT_BLE_ADVERTISING_TIMEOUT > 0)
00334     ble->gap().setAdvertisingTimeout(MICROBIT_BLE_ADVERTISING_TIMEOUT);
00335 #endif
00336     ble->gap().startAdvertising();
00337 
00338     return retVal;
00339 }
00340 
00341  void MicroBitBLEManager::pairingMode(MicroBitDisplay &display, MicroBitButton &authorisationButton)
00342  {
00343 
00344  
00345 }  
00346 
00347