diff --git a/libraries/BluefruitLib/LICENSE b/libraries/BluefruitLib/LICENSE new file mode 100644 index 00000000..19a9cd85 --- /dev/null +++ b/libraries/BluefruitLib/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Adafruit Industries + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/libraries/BluefruitLib/README.md b/libraries/BluefruitLib/README.md new file mode 100644 index 00000000..af90e05c --- /dev/null +++ b/libraries/BluefruitLib/README.md @@ -0,0 +1,2 @@ +# Adafruit_nRF52_Arduino_Helpers +Helper libraries and classes for the Adafruit_nRF52_Arduino repository diff --git a/libraries/BluefruitLib/examples/bleuart/bleuart.ino b/libraries/BluefruitLib/examples/bleuart/bleuart.ino new file mode 100644 index 00000000..0b4ad2d8 --- /dev/null +++ b/libraries/BluefruitLib/examples/bleuart/bleuart.ino @@ -0,0 +1,109 @@ +/**************************************************************************/ +/*! + @file bleuart.ino + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include + +BLEDis bledis; +BLEUart bleuart; +BLEBas blebas; + +void setup() +{ + pinMode(LED_BUILTIN, OUTPUT); + Serial.begin(115200); + + Serial.println("BLEUART Example"); + + Bluefruit.begin(); + Bluefruit.setName("Bluefruit"); + + // Configure and Start Device Information Service + bledis.setManufacturer("Adafruit Industries"); + bledis.setModel("Bluefruit Feather 52"); + bledis.setHardwareRev("Rev E"); + bledis.setFirmwareRev("0.1.0"); + bledis.start(); + + // Configure and Start BLE Uart Service + bleuart.start(); + + // Start BLE Battery Service + blebas.start(); + blebas.update(100); + + // Set up Advertising Packet + setupAdv(); + + // Start Advertising + Bluefruit.startAdvertising(); +} + +void setupAdv(void) +{ + //Bluefruit.addAdvTxPower(); + Bluefruit.addAdvFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.addAdvTxPower(); + + // Include bleuart 128-bit uuid + Bluefruit.addAdvService(bleuart); + + // There is no room for Name in Advertising packet + // Use Scan response for Name + Bluefruit.addScanName(); +} + +void loop() +{ + // forward from Serial to BLEUART + if (Serial.available()) + { + // delay to get enough inputs, since we have limited number of transmission buffer + delay(2); + + uint8_t buf[64]; + int count = Serial.readBytes(buf, sizeof(buf)); + bleuart.write( buf, count ); + } + + // forward from BLEUART to Serial + if ( bleuart.available() ) + { + uint8_t ch; + ch = (uint8_t) bleuart.read(); + Serial.write(ch); + } +} + diff --git a/libraries/BluefruitLib/examples/blinky_ota/blinky_ota.ino b/libraries/BluefruitLib/examples/blinky_ota/blinky_ota.ino new file mode 100644 index 00000000..f44f4df3 --- /dev/null +++ b/libraries/BluefruitLib/examples/blinky_ota/blinky_ota.ino @@ -0,0 +1,84 @@ +/**************************************************************************/ +/*! + @file bleuart.ino + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include + +uint32_t ms = 0; + +void setup() +{ + pinMode(LED_BUILTIN, OUTPUT); + Serial.begin(115200); + + Serial.println("Blinky Example"); + + Bluefruit.begin(); + Bluefruit.setName("Blinky"); + + // Set up Advertising Packet + setupAdv(); + + // Start Advertising + Bluefruit.startAdvertising(); +} + +void setupAdv(void) +{ + //Bluefruit.addAdvTxPower(); + Bluefruit.addAdvFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.addAdvTxPower(); + + // There is no room for Name in Advertising packet + // Use Scan response for Name + Bluefruit.addScanName(); +} + +void loop() +{ + Bluefruit.poll(); + + // Toggle both LEDs every 1 second + if ( millis() - ms >= 1000 ) + { + static int state = LOW; + digitalWrite(LED_BUILTIN, state); + digitalWrite(LED_CONN, state); + + state = 1 - state; + ms += 1000; + } +} + diff --git a/libraries/BluefruitLib/examples/controller/controller.ino b/libraries/BluefruitLib/examples/controller/controller.ino new file mode 100644 index 00000000..180f4cc9 --- /dev/null +++ b/libraries/BluefruitLib/examples/controller/controller.ino @@ -0,0 +1,172 @@ +/********************************************************************* + This is an example for our nRF51822 based Bluefruit LE modules + + Pick one up today in the adafruit shop! + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + MIT license, check LICENSE for more information + All text above, and the splash screen below must be included in + any redistribution +*********************************************************************/ + +#include + +BLEUart bleuart; + +// function prototypes over in packetparser.cpp +uint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout); +float parsefloat(uint8_t *buffer); +void printHex(const uint8_t * data, const uint32_t numBytes); + +// the packet buffer +extern uint8_t packetbuffer[]; + + +/**************************************************************************/ +/*! + @brief Sets up the HW an the BLE module (this function is called + automatically on startup) +*/ +/**************************************************************************/ +void setup(void) +{ + Serial.begin(115200); + Serial.println(F("Adafruit Bluefruit App Controller Example")); + Serial.println(F("-----------------------------------------")); + + Bluefruit.begin(); + Bluefruit.setName("Bluefruit"); + + // Configure and Start BLE Uart Service + bleuart.start(); + + // Set up Advertising Packet + setupAdv(); + + // Start Advertising + Bluefruit.startAdvertising(); +} + +void setupAdv(void) +{ + //Bluefruit.addAdvTxPower(); + Bluefruit.addAdvFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.addAdvTxPower(); + + // Include bleuart 128-bit uuid + Bluefruit.addAdvService(bleuart); + + // There is no room for Name in Advertising packet + // Use Scan response for Name + Bluefruit.addScanName(); +} + +/**************************************************************************/ +/*! + @brief Constantly poll for new command or response data +*/ +/**************************************************************************/ +void loop(void) +{ + Bluefruit.poll(); + + /* Wait for new data to arrive */ + uint8_t len = readPacket(&ble, BLE_READPACKET_TIMEOUT); + if (len == 0) return; + + /* Got a packet! */ + // printHex(packetbuffer, len); + + // Color + if (packetbuffer[1] == 'C') { + uint8_t red = packetbuffer[2]; + uint8_t green = packetbuffer[3]; + uint8_t blue = packetbuffer[4]; + Serial.print ("RGB #"); + if (red < 0x10) Serial.print("0"); + Serial.print(red, HEX); + if (green < 0x10) Serial.print("0"); + Serial.print(green, HEX); + if (blue < 0x10) Serial.print("0"); + Serial.println(blue, HEX); + } + + // Buttons + if (packetbuffer[1] == 'B') { + uint8_t buttnum = packetbuffer[2] - '0'; + boolean pressed = packetbuffer[3] - '0'; + Serial.print ("Button "); Serial.print(buttnum); + if (pressed) { + Serial.println(" pressed"); + } else { + Serial.println(" released"); + } + } + + // GPS Location + if (packetbuffer[1] == 'L') { + float lat, lon, alt; + lat = parsefloat(packetbuffer+2); + lon = parsefloat(packetbuffer+6); + alt = parsefloat(packetbuffer+10); + Serial.print("GPS Location\t"); + Serial.print("Lat: "); Serial.print(lat, 4); // 4 digits of precision! + Serial.print('\t'); + Serial.print("Lon: "); Serial.print(lon, 4); // 4 digits of precision! + Serial.print('\t'); + Serial.print(alt, 4); Serial.println(" meters"); + } + + // Accelerometer + if (packetbuffer[1] == 'A') { + float x, y, z; + x = parsefloat(packetbuffer+2); + y = parsefloat(packetbuffer+6); + z = parsefloat(packetbuffer+10); + Serial.print("Accel\t"); + Serial.print(x); Serial.print('\t'); + Serial.print(y); Serial.print('\t'); + Serial.print(z); Serial.println(); + } + + // Magnetometer + if (packetbuffer[1] == 'M') { + float x, y, z; + x = parsefloat(packetbuffer+2); + y = parsefloat(packetbuffer+6); + z = parsefloat(packetbuffer+10); + Serial.print("Mag\t"); + Serial.print(x); Serial.print('\t'); + Serial.print(y); Serial.print('\t'); + Serial.print(z); Serial.println(); + } + + // Gyroscope + if (packetbuffer[1] == 'G') { + float x, y, z; + x = parsefloat(packetbuffer+2); + y = parsefloat(packetbuffer+6); + z = parsefloat(packetbuffer+10); + Serial.print("Gyro\t"); + Serial.print(x); Serial.print('\t'); + Serial.print(y); Serial.print('\t'); + Serial.print(z); Serial.println(); + } + + // Quaternions + if (packetbuffer[1] == 'Q') { + float x, y, z, w; + x = parsefloat(packetbuffer+2); + y = parsefloat(packetbuffer+6); + z = parsefloat(packetbuffer+10); + w = parsefloat(packetbuffer+14); + Serial.print("Quat\t"); + Serial.print(x); Serial.print('\t'); + Serial.print(y); Serial.print('\t'); + Serial.print(z); Serial.print('\t'); + Serial.print(w); Serial.println(); + } +} diff --git a/libraries/BluefruitLib/examples/controller/packetParser.cpp b/libraries/BluefruitLib/examples/controller/packetParser.cpp new file mode 100644 index 00000000..ee4f4784 --- /dev/null +++ b/libraries/BluefruitLib/examples/controller/packetParser.cpp @@ -0,0 +1,141 @@ +#include +#include +#include +#if not defined (_VARIANT_ARDUINO_DUE_X_) && not defined (_VARIANT_ARDUINO_ZERO_) + #include +#endif + +#include "Adafruit_BLE.h" +#include "Adafruit_BluefruitLE_SPI.h" +#include "Adafruit_BluefruitLE_UART.h" + + +#define PACKET_ACC_LEN (15) +#define PACKET_GYRO_LEN (15) +#define PACKET_MAG_LEN (15) +#define PACKET_QUAT_LEN (19) +#define PACKET_BUTTON_LEN (5) +#define PACKET_COLOR_LEN (6) +#define PACKET_LOCATION_LEN (15) + +// READ_BUFSIZE Size of the read buffer for incoming packets +#define READ_BUFSIZE (20) + + +/* Buffer to hold incoming characters */ +uint8_t packetbuffer[READ_BUFSIZE+1]; + +/**************************************************************************/ +/*! + @brief Casts the four bytes at the specified address to a float +*/ +/**************************************************************************/ +float parsefloat(uint8_t *buffer) +{ + float f; + memcpy(&f, buffer, 4); + return f; +} + +/**************************************************************************/ +/*! + @brief Prints a hexadecimal value in plain characters + @param data Pointer to the byte data + @param numBytes Data length in bytes +*/ +/**************************************************************************/ +void printHex(const uint8_t * data, const uint32_t numBytes) +{ + uint32_t szPos; + for (szPos=0; szPos < numBytes; szPos++) + { + Serial.print(F("0x")); + // Append leading 0 for small values + if (data[szPos] <= 0xF) + { + Serial.print(F("0")); + Serial.print(data[szPos] & 0xf, HEX); + } + else + { + Serial.print(data[szPos] & 0xff, HEX); + } + // Add a trailing space if appropriate + if ((numBytes > 1) && (szPos != numBytes - 1)) + { + Serial.print(F(" ")); + } + } + Serial.println(); +} + +/**************************************************************************/ +/*! + @brief Waits for incoming data and parses it +*/ +/**************************************************************************/ +uint8_t readPacket(Adafruit_BLE *ble, uint16_t timeout) +{ + uint16_t origtimeout = timeout, replyidx = 0; + + memset(packetbuffer, 0, READ_BUFSIZE); + + while (timeout--) { + if (replyidx >= 20) break; + if ((packetbuffer[1] == 'A') && (replyidx == PACKET_ACC_LEN)) + break; + if ((packetbuffer[1] == 'G') && (replyidx == PACKET_GYRO_LEN)) + break; + if ((packetbuffer[1] == 'M') && (replyidx == PACKET_MAG_LEN)) + break; + if ((packetbuffer[1] == 'Q') && (replyidx == PACKET_QUAT_LEN)) + break; + if ((packetbuffer[1] == 'B') && (replyidx == PACKET_BUTTON_LEN)) + break; + if ((packetbuffer[1] == 'C') && (replyidx == PACKET_COLOR_LEN)) + break; + if ((packetbuffer[1] == 'L') && (replyidx == PACKET_LOCATION_LEN)) + break; + + while (ble->available()) { + char c = ble->read(); + if (c == '!') { + replyidx = 0; + } + packetbuffer[replyidx] = c; + replyidx++; + timeout = origtimeout; + } + + if (timeout == 0) break; + delay(1); + } + + packetbuffer[replyidx] = 0; // null term + + if (!replyidx) // no data or timeout + return 0; + if (packetbuffer[0] != '!') // doesn't start with '!' packet beginning + return 0; + + // check checksum! + uint8_t xsum = 0; + uint8_t checksum = packetbuffer[replyidx-1]; + + for (uint8_t i=0; i +sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules +paragraph=Arduino library for nRF52-based Adafruit Bluefruit LE modules +category=Communication +url=https://github.com/adafruit/Adafruit_nRF52_Arduino_Helpers +architectures=* +includes=bluefruit.h diff --git a/libraries/BluefruitLib/src/BLECharacteristic.cpp b/libraries/BluefruitLib/src/BLECharacteristic.cpp new file mode 100644 index 00000000..fd414e99 --- /dev/null +++ b/libraries/BluefruitLib/src/BLECharacteristic.cpp @@ -0,0 +1,393 @@ +/**************************************************************************/ +/*! + @file BLECharacteristic.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "bluefruit.h" + +void BLECharacteristic::init(void) +{ + varclr(&_properties); + _descriptor = NULL; + _max_len = BLE_GATTS_VAR_ATTR_LEN_MAX; + + _service = BLEService::lastService; + + _handles.value_handle = BLE_GATT_HANDLE_INVALID; + _handles.user_desc_handle = BLE_GATT_HANDLE_INVALID; + _handles.sccd_handle = BLE_GATT_HANDLE_INVALID; + _handles.cccd_handle = BLE_GATT_HANDLE_INVALID; + + varclr(&_attr_meta); + _attr_meta.read_perm = _attr_meta.write_perm = (ble_gap_conn_sec_mode_t){ .sm = 1, .lv = 1 }; + _attr_meta.vlen = 1; + _attr_meta.vloc = BLE_GATTS_VLOC_STACK; + + _rd_authorize_cb = NULL; + _wr_authorize_cb = NULL; + _wr_cb = NULL; +} + +BLECharacteristic::BLECharacteristic(void) + : uuid() +{ + init(); +} + +BLECharacteristic::BLECharacteristic(uint16_t uuid16) + : uuid(uuid16) +{ + init(); +} + +BLECharacteristic::BLECharacteristic(uint8_t const uuid128[]) + : uuid(uuid128) +{ + init(); +} + +void BLECharacteristic::setUuid(uint16_t uuid16) +{ + uuid.set(uuid16); +} + +void BLECharacteristic::setUuid(uint8_t const uuid128[]) +{ + uuid.set(uuid128); +} + +void BLECharacteristic::setProperties(uint8_t prop) +{ + memcpy(&_properties, &prop, 1); +} + +void BLECharacteristic::setMaxLen(uint16_t max_len) +{ + _max_len = max_len; +} + +void BLECharacteristic::setFixedLen(uint16_t fixed_len) +{ + if ( fixed_len ) + { + _max_len = fixed_len; + _attr_meta.vlen = 0; + }else + { + _attr_meta.vlen = 1; + } +} + +void BLECharacteristic::setPermission(BleSecurityMode read_perm, BleSecurityMode write_perm) +{ + memcpy(&_attr_meta.read_perm , &read_perm, 1); + memcpy(&_attr_meta.write_perm, &write_perm, 1); +} + +void BLECharacteristic::setWriteCallback(write_cb_t fp) +{ + _wr_cb = fp; +} + +void BLECharacteristic::setReadAuthorizeCallback(read_authorize_cb_t fp) +{ + _attr_meta.rd_auth = (fp ? 1 : 0); + _rd_authorize_cb = fp; +} + +void BLECharacteristic::setWriteAuthorizeCallbak(write_authorize_cb_t fp) +{ + _attr_meta.wr_auth = (fp ? 1 : 0); + _wr_authorize_cb = fp; +} + +void BLECharacteristic::setDescriptor(const char* descriptor) +{ + _descriptor = descriptor; +} + +ble_gatts_char_handles_t BLECharacteristic::handles(void) +{ + return _handles; +} + +err_t BLECharacteristic::start(void) +{ + // Add UUID128 if needed + uuid.add(); + + // Permission is OPEN if passkey is disabled. +// if (!nvm_data.core.passkey_enable) BLE_GAP_CONN_SEC_MODE_SET_OPEN(&p_char_def->permission); + + /* CCCD attribute metadata */ + /* https://devzone.nordicsemi.com/documentation/nrf51/5.2.0/html/a00269.html */ + ble_gatts_attr_md_t cccd_md; + + if ( _properties.notify || _properties.indicate ) + { + /* Notification & Indication require CCCD */ + memclr( &cccd_md, sizeof(ble_gatts_attr_md_t) ); + cccd_md.vloc = BLE_GATTS_VLOC_STACK; + + cccd_md.read_perm = BLE_SECMODE_OPEN; + + // TODO enable encryption when bonding is enabled +// cccd_md.write_perm = BLE_SECMODE_ENC_NO_MITM; + cccd_md.write_perm = BLE_SECMODE_OPEN; + } + + /* Characteristic metadata */ + /* https://devzone.nordicsemi.com/documentation/nrf51/5.2.0/html/a00272.html */ + ble_gatts_char_md_t char_md; + varclr(&char_md); + + char_md.char_props = _properties; + char_md.p_cccd_md = (_properties.notify || _properties.indicate) ? &cccd_md : NULL; + + /* Characteristic extended properties (used for the user description) */ + /* https://devzone.nordicsemi.com/documentation/nrf51/5.2.0/html/a00248.html */ + ble_gatts_attr_md_t desc_md = + { + .read_perm = { .sm = 1, .lv = 1 }, // open + .write_perm = { .sm = 0, .lv = 0 }, // no access + .vlen = 0, + .vloc = BLE_GATTS_VLOC_STACK, + }; + + if (_descriptor != NULL && _descriptor[0] != 0) + { + char_md.p_char_user_desc = (uint8_t*) _descriptor; + char_md.char_user_desc_size = char_md.char_user_desc_max_size = strlen(_descriptor); + char_md.p_user_desc_md = &desc_md; + //char_md.char_ext_props = ext_props, + } + + /* Presentation format + * https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml + */ +// if ( p_char_def->presentation.format ) +// { +// char_md.p_char_pf = &p_char_def->presentation; +// } + + if ( !(_properties.read || _properties.notify || _properties.indicate ) ) + { + _attr_meta.read_perm = BLE_SECMODE_NO_ACCESS; + } + + if ( !(_properties.write || _properties.write_wo_resp ) ) + { + _attr_meta.write_perm = BLE_SECMODE_NO_ACCESS; + } + + /* GATT attribute declaration */ + /* https://devzone.nordicsemi.com/documentation/nrf51/5.2.0/html/a00270.html */ + ble_gatts_attr_t attr_char_value = + { + .p_uuid = &uuid._uuid, + .p_attr_md = &_attr_meta, + .init_len = (_attr_meta.vlen == 1) ? (uint16_t) 0 : _max_len, + .init_offs = 0, + .max_len = _max_len, + .p_value = NULL + }; + + VERIFY_STATUS( sd_ble_gatts_characteristic_add(BLE_GATT_HANDLE_INVALID, &char_md, &attr_char_value, &_handles) ); + + // Only register to Bluefruit when having callback support + // The Characteristic must not be temporary memory aka local variable + if (_rd_authorize_cb || _wr_authorize_cb || _wr_cb) + { + (void) Bluefruit._registerCharacteristic(this); + } + + return NRF_SUCCESS; +} + +/** + * Call by Bluefruit event poll() + * @param event + */ +void BLECharacteristic::eventHandler(ble_evt_t* event) +{ + switch(event->header.evt_id) + { + case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: + { + ble_gatts_evt_rw_authorize_request_t * authorize_request = &event->evt.gatts_evt.params.authorize_request; + + ble_uuid_t request_uuid = (authorize_request->type == BLE_GATTS_AUTHORIZE_TYPE_WRITE) ? + authorize_request->request.write.uuid : authorize_request->request.read.uuid; + + // skip if not our event + if ( uuid == request_uuid ) + { + if ( (authorize_request->type == BLE_GATTS_AUTHORIZE_TYPE_WRITE) && (_wr_authorize_cb != NULL)) + { + this->_wr_authorize_cb(*this, &authorize_request->request.write); + } + + if ( (authorize_request->type == BLE_GATTS_AUTHORIZE_TYPE_READ) && (_rd_authorize_cb != NULL)) + { + _rd_authorize_cb(*this, &authorize_request->request.read); + } + } + } + break; + + case BLE_GATTS_EVT_WRITE: + { + ble_gatts_evt_write_t* request = (ble_gatts_evt_write_t*) &event->evt.gatts_evt.params.write; + + if ( _wr_cb && (uuid == request->uuid)) + { + _wr_cb(*this, &event->evt.gatts_evt.params.write); + } + } + break; + + default: break; + } +} + +err_t BLECharacteristic::write(const uint8_t* data, int len) +{ + return write(data, len, 0); +} + +err_t BLECharacteristic::write(const char * str) +{ + return write((const uint8_t*) str, strlen(str)); +} + +err_t BLECharacteristic::write(const uint8_t* data, int len, uint16_t offset) +{ + ble_gatts_value_t value = + { + .len = (uint16_t) len, + .offset = offset, + .p_value = (uint8_t*) data + }; + + // conn handle only needed for system attribute + return sd_ble_gatts_value_set(BLE_CONN_HANDLE_INVALID, _handles.value_handle, &value); +} + +err_t BLECharacteristic::write(int num) +{ + return write( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::write(uint32_t num) +{ + return write( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::write(uint16_t num) +{ + return write( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::write(uint8_t num) +{ + return write( (uint8_t*) &num, sizeof(num)); +} + +bool BLECharacteristic::notifyEnabled(void) +{ + VERIFY( _properties.notify ); + uint16_t cccd; + ble_gatts_value_t value = + { + .len = 2, + .offset = 0, + .p_value = (uint8_t*) &cccd + }; + + VERIFY_STATUS( sd_ble_gatts_value_get(Bluefruit.connHandle(), _handles.cccd_handle, &value), false ); + + return (cccd & BLE_GATT_HVX_NOTIFICATION); +} + +err_t BLECharacteristic::notify(const uint8_t* data, int len, uint16_t offset) +{ + if ( !_properties.notify ) return NRF_ERROR_INVALID_PARAM; + + uint16_t len16 = (uint16_t) len; + + ble_gatts_hvx_params_t hvx_params = + { + .handle = _handles.value_handle, + .type = BLE_GATT_HVX_NOTIFICATION, + .offset = offset, + .p_len = &len16, + .p_data = (uint8_t*) data, + }; + + VERIFY_STATUS( sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params) ); + + Bluefruit.txbuf_decrease(); + + return NRF_SUCCESS; +} + +err_t BLECharacteristic::notify(const uint8_t* data, int len) +{ + return notify(data, len, 0); +} + +err_t BLECharacteristic::notify(const char * str) +{ + return notify( (const uint8_t*) str, strlen(str) ); +} + +err_t BLECharacteristic::notify(int num) +{ + return notify( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::notify(uint32_t num) +{ + return notify( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::notify(uint16_t num) +{ + return notify( (uint8_t*) &num, sizeof(num)); +} + +err_t BLECharacteristic::notify(uint8_t num) +{ + return notify( (uint8_t*) &num, sizeof(num)); +} diff --git a/libraries/BluefruitLib/src/BLECharacteristic.h b/libraries/BluefruitLib/src/BLECharacteristic.h new file mode 100644 index 00000000..2d8168c8 --- /dev/null +++ b/libraries/BluefruitLib/src/BLECharacteristic.h @@ -0,0 +1,164 @@ +/**************************************************************************/ +/*! + @file BLECharacteristic.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLECHARACTERISTIC_H_ +#define BLECHARACTERISTIC_H_ + +#include "utility/common_inc.h" +#include "BLEUuid.h" + +class AdafruitBluefruit; +class BLEService; + +enum BleSecurityMode +{ + SECMODE_NO_ACCESS = 0x00, + SECMODE_OPEN = 0x11, + SECMODE_ENC_NO_MITM = 0x21, + SECMODE_ENC_WITH_MITM = 0x31, + SECMODE_SIGNED_NO_MITM = 0x12, + SECMODE_SIGNED_WITH_MITM = 0x22 +}; + +#define BLE_SECMODE_NO_ACCESS ((ble_gap_conn_sec_mode_t) { .sm = 0, .lv = 0 }) +#define BLE_SECMODE_OPEN ((ble_gap_conn_sec_mode_t) { .sm = 1, .lv = 1 }) +#define BLE_SECMODE_ENC_NO_MITM ((ble_gap_conn_sec_mode_t) { .sm = 1, .lv = 2 }) +#define BLE_SECMODE_ENC_WITH_MITM ((ble_gap_conn_sec_mode_t) { .sm = 1, .lv = 3 }) +#define BLE_SECMODE_SIGNED_NO_MITM ((ble_gap_conn_sec_mode_t) { .sm = 2, .lv = 1 }) +#define BLE_SECMODE_SIGNED_WITH_MITM ((ble_gap_conn_sec_mode_t) { .sm = 2, .lv = 2 }) + +enum CharsProperties +{ + CHR_PROPS_BROADCAST = bit(0), + CHR_PROPS_READ = bit(1), + CHR_PROPS_WRITE_WO_RESP = bit(2), + CHR_PROPS_WRITE = bit(3), + CHR_PROPS_NOTIFY = bit(4), + CHR_PROPS_INDICATE = bit(5) +}; + +class BLECharacteristic +{ + public: + typedef void (*read_authorize_cb_t) (BLECharacteristic& chr, ble_gatts_evt_read_t * request); + typedef void (*write_authorize_cb_t) (BLECharacteristic& chr, ble_gatts_evt_write_t* request); + typedef void (*write_cb_t) (BLECharacteristic& chr, ble_gatts_evt_write_t* request); + + protected: + ble_gatt_char_props_t _properties; + const char* _descriptor; + uint16_t _max_len; + + /* Characteristic attribute metadata */ + /* https://devzone.nordicsemi.com/documentation/nrf51/5.2.0/html/a00269.html */ + ble_gatts_attr_md_t _attr_meta; + + ble_gatts_char_handles_t _handles; + + BLEService* _service; + + // Callback pointer + read_authorize_cb_t _rd_authorize_cb; + write_authorize_cb_t _wr_authorize_cb; + write_cb_t _wr_cb; + + void init(void); + void eventHandler(ble_evt_t* event); + + public: + BLEUuid uuid; + + typedef void (*chars_cb_t) (void); + + BLECharacteristic(void); + BLECharacteristic(uint16_t uuid16); + BLECharacteristic(uint8_t const uuid128[]); + + BLEService& parentService() + { + return *_service; + } + + + void setUuid(uint16_t uuid16); + void setUuid(uint8_t const uuid128[]); + + // Configure + void setProperties(uint8_t prop); + void setPermission(BleSecurityMode read_perm, BleSecurityMode write_perm); + void setDescriptor(const char* descriptor); + + void setMaxLen(uint16_t max_len); + void setFixedLen(uint16_t fixed_len); + + // Callback + void setWriteCallback(write_cb_t fp); + void setReadAuthorizeCallback(read_authorize_cb_t fp); + void setWriteAuthorizeCallbak(write_authorize_cb_t fp); + + err_t start(void); + + ble_gatts_char_handles_t handles(void); + + // Write + err_t write(const uint8_t* data, int len, uint16_t offset); + err_t write(const uint8_t* data, int len); + err_t write(const char * str); + + err_t write(int num); + err_t write(uint32_t num); + err_t write(uint16_t num); + err_t write(uint8_t num); + + // Notify + bool notifyEnabled(void); + + err_t notify(const uint8_t* data, int len, uint16_t offset); + err_t notify(const uint8_t* data, int len); + err_t notify(const char * str); + + err_t notify(int num); + err_t notify(uint32_t num); + err_t notify(uint16_t num); + err_t notify(uint8_t num); + + + + friend class AdafruitBluefruit; +}; + + + +#endif /* BLECHARACTERISTIC_H_ */ diff --git a/libraries/BluefruitLib/src/BLEService.cpp b/libraries/BluefruitLib/src/BLEService.cpp new file mode 100644 index 00000000..6208ff21 --- /dev/null +++ b/libraries/BluefruitLib/src/BLEService.cpp @@ -0,0 +1,85 @@ +/**************************************************************************/ +/*! + @file BLEService.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include +#include "BLEService.h" + +BLEService* BLEService::lastService = NULL; + +void BLEService::_init(void) +{ + _handle = BLE_GATT_HANDLE_INVALID; + + lastService = this; +} + +BLEService::BLEService(void) + : uuid() +{ + _init(); +} + +BLEService::BLEService(uint16_t uuid16) + : uuid(uuid16) +{ + _init(); +} + +BLEService::BLEService(uint8_t const uuid128[]) + : uuid(uuid128) +{ + _init(); +} + +void BLEService::setUuid(uint16_t uuid16) +{ + uuid.set(uuid16); +} + +void BLEService::setUuid(uint8_t const uuid128[]) +{ + uuid.set(uuid128); +} + +err_t BLEService::addToGatt(void) +{ + // Add UUID128 if needed + uuid.add(); + + uint16_t handle; + return sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &uuid._uuid, &handle); +} + diff --git a/libraries/BluefruitLib/src/BLEService.h b/libraries/BluefruitLib/src/BLEService.h new file mode 100644 index 00000000..959d0c5a --- /dev/null +++ b/libraries/BluefruitLib/src/BLEService.h @@ -0,0 +1,66 @@ +/**************************************************************************/ +/*! + @file BLEService.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLESERVICE_H_ +#define BLESERVICE_H_ + +#include "utility/common_inc.h" +#include "BLEUuid.h" + +class BLEService +{ + protected: + uint16_t _handle; + + err_t addToGatt(void); + void _init(void); + + public: + BLEUuid uuid; + + static BLEService* lastService; + + BLEService(void); + BLEService(uint16_t uuid16); + BLEService(uint8_t const uuid128[]); + + void setUuid(uint16_t uuid16); + void setUuid(uint8_t const uuid128[]); + + // Abstract Class + virtual err_t start(void) = 0; +}; + +#endif /* BLESERVICE_H_ */ diff --git a/libraries/BluefruitLib/src/BLEUuid.h b/libraries/BluefruitLib/src/BLEUuid.h new file mode 100644 index 00000000..b17593e2 --- /dev/null +++ b/libraries/BluefruitLib/src/BLEUuid.h @@ -0,0 +1,213 @@ +/**************************************************************************/ +/*! + @file BLEUuid.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLEUUID_H_ +#define BLEUUID_H_ + +#include "utility/common_inc.h" + +class BLEUuid +{ + public: + ble_uuid_t _uuid; + uint8_t const* _uuid128; + + // Constructors + BLEUuid(void ) { _uuid.type = BLE_UUID_TYPE_UNKNOWN; _uuid.uuid = 0; } + BLEUuid(uint16_t uuid16 ) { set(uuid16); } + BLEUuid(uint8_t const uuid128[16] ) { set(uuid128); } + + void set(uint16_t uuid16) + { + _uuid.type = BLE_UUID_TYPE_BLE; + _uuid.uuid = uuid16; + } + + void set(uint8_t const uuid128[16]) + { + _uuid.type = BLE_UUID_TYPE_UNKNOWN; _uuid.uuid = 0; + _uuid128 = uuid128; + } + + // Add UUID128 if any, in case of UUID16, no ations is required + // Application should call it anyway to be safe and consistent + void add(void) + { + /* Add base uuid and decode to get uuid16 + * This should cover the already added base uuid128 previously + */ + if (_uuid.type == BLE_UUID_TYPE_UNKNOWN && _uuid128 != NULL ) + { + (void) sd_ble_uuid_vs_add( (ble_uuid128_t const*) _uuid128, &_uuid.type ); + (void) sd_ble_uuid_decode(16, _uuid128, &_uuid); + } + } + + bool operator==(const BLEUuid& uuid) const + { + return (this->_uuid.type == uuid._uuid.type) && (this->_uuid.uuid == uuid._uuid.uuid); + } + + bool operator!=(const BLEUuid& uuid) const + { + return !(*this == uuid); + } + + bool operator==(const ble_uuid_t uuid) const + { + return (this->_uuid.type == uuid.type) && (this->_uuid.uuid == uuid.uuid); + } + + bool operator!=(const ble_uuid_t uuid) const + { + return !(*this == uuid); + } +}; + +// Service UUID +#define UUID16_SVC_ALERT_NOTIFICATION 0x1811 +#define UUID16_SVC_BATTERY 0x180F +#define UUID16_SVC_BLOOD_PRESSURE 0x1810 +#define UUID16_SVC_CURRENT_TIME 0x1805 +#define UUID16_SVC_CYCLING_SPEED_AND_CADENCE 0x1816 +#define UUID16_SVC_LOCATION_AND_NAVIGATION 0x1819 +#define UUID16_SVC_DEVICE_INFORMATION 0x180A +#define UUID16_SVC_GLUCOSE 0x1808 +#define UUID16_SVC_HEALTH_THERMOMETER 0x1809 +#define UUID16_SVC_HEART_RATE 0x180D +#define UUID16_SVC_HUMAN_INTERFACE_DEVICE 0x1812 +#define UUID16_SVC_IMMEDIATE_ALERT 0x1802 +#define UUID16_SVC_LINK_LOSS 0x1803 +#define UUID16_SVC_NEXT_DST_CHANGE 0x1807 +#define UUID16_SVC_PHONE_ALERT_STATUS 0x180E +#define UUID16_SVC_REFERENCE_TIME_UPDATE 0x1806 +#define UUID16_SVC_RUNNING_SPEED_AND_CADENCE 0x1814 +#define UUID16_SVC_SCAN_PARAMETERS 0x1813 +#define UUID16_SVC_TX_POWER 0x1804 +#define UUID16_SVC_IPSP 0x1820 +#define UUID16_SVC_BMS 0x181E +#define UUID16_SVC_CGM 0x181F +#define UUID16_SVC_PLX 0x1822 + +// Characteristic UUID +#define UUID16_CHR_REMOVABLE 0x2A3A +#define UUID16_CHR_SERVICE_REQUIRED 0x2A3B +#define UUID16_CHR_ALERT_CATEGORY_ID 0x2A43 +#define UUID16_CHR_ALERT_CATEGORY_ID_BIT_MASK 0x2A42 +#define UUID16_CHR_ALERT_LEVEL 0x2A06 +#define UUID16_CHR_ALERT_NOTIFICATION_CONTROL_POINT 0x2A44 +#define UUID16_CHR_ALERT_STATUS 0x2A3F +#define UUID16_CHR_BATTERY_LEVEL 0x2A19 +#define UUID16_CHR_BLOOD_PRESSURE_FEATURE 0x2A49 +#define UUID16_CHR_BLOOD_PRESSURE_MEASUREMENT 0x2A35 +#define UUID16_CHR_BODY_SENSOR_LOCATION 0x2A38 +#define UUID16_CHR_BOOT_KEYBOARD_INPUT_REPORT 0x2A22 +#define UUID16_CHR_BOOT_KEYBOARD_OUTPUT_REPORT 0x2A32 +#define UUID16_CHR_BOOT_MOUSE_INPUT_REPORT 0x2A33 +#define UUID16_CHR_CURRENT_TIME 0x2A2B +#define UUID16_CHR_DATE_TIME 0x2A08 +#define UUID16_CHR_DAY_DATE_TIME 0x2A0A +#define UUID16_CHR_DAY_OF_WEEK 0x2A09 +#define UUID16_CHR_DST_OFFSET 0x2A0D +#define UUID16_CHR_EXACT_TIME_256 0x2A0C +#define UUID16_CHR_FIRMWARE_REVISION_STRING 0x2A26 +#define UUID16_CHR_GLUCOSE_FEATURE 0x2A51 +#define UUID16_CHR_GLUCOSE_MEASUREMENT 0x2A18 +#define UUID16_CHR_GLUCOSE_MEASUREMENT_CONTEXT 0x2A34 +#define UUID16_CHR_HARDWARE_REVISION_STRING 0x2A27 +#define UUID16_CHR_HEART_RATE_CONTROL_POINT 0x2A39 +#define UUID16_CHR_HEART_RATE_MEASUREMENT 0x2A37 +#define UUID16_CHR_HID_CONTROL_POINT 0x2A4C +#define UUID16_CHR_HID_INFORMATION 0x2A4A +#define UUID16_CHR_IEEE_REGULATORY_CERTIFICATION_DATA_LIST 0x2A2A +#define UUID16_CHR_INTERMEDIATE_CUFF_PRESSURE 0x2A36 +#define UUID16_CHR_INTERMEDIATE_TEMPERATURE 0x2A1E +#define UUID16_CHR_LOCAL_TIME_INFORMATION 0x2A0F +#define UUID16_CHR_MANUFACTURER_NAME_STRING 0x2A29 +#define UUID16_CHR_MEASUREMENT_INTERVAL 0x2A21 +#define UUID16_CHR_MODEL_NUMBER_STRING 0x2A24 +#define UUID16_CHR_UNREAD_ALERT 0x2A45 +#define UUID16_CHR_NEW_ALERT 0x2A46 +#define UUID16_CHR_PNP_ID 0x2A50 +#define UUID16_CHR_PROTOCOL_MODE 0x2A4E +#define UUID16_CHR_RECORD_ACCESS_CONTROL_POINT 0x2A52 +#define UUID16_CHR_REFERENCE_TIME_INFORMATION 0x2A14 +#define UUID16_CHR_REPORT 0x2A4D +#define UUID16_CHR_REPORT_MAP 0x2A4B +#define UUID16_CHR_RINGER_CONTROL_POINT 0x2A40 +#define UUID16_CHR_RINGER_SETTING 0x2A41 +#define UUID16_CHR_SCAN_INTERVAL_WINDOW 0x2A4F +#define UUID16_CHR_SCAN_REFRESH 0x2A31 +#define UUID16_CHR_SERIAL_NUMBER_STRING 0x2A25 +#define UUID16_CHR_SOFTWARE_REVISION_STRING 0x2A28 +#define UUID16_CHR_SUPPORTED_NEW_ALERT_CATEGORY 0x2A47 +#define UUID16_CHR_SUPPORTED_UNREAD_ALERT_CATEGORY 0x2A48 +#define UUID16_CHR_SYSTEM_ID 0x2A23 +#define UUID16_CHR_TEMPERATURE_MEASUREMENT 0x2A1C +#define UUID16_CHR_TEMPERATURE_TYPE 0x2A1D +#define UUID16_CHR_TIME_ACCURACY 0x2A12 +#define UUID16_CHR_TIME_SOURCE 0x2A13 +#define UUID16_CHR_TIME_UPDATE_CONTROL_POINT 0x2A16 +#define UUID16_CHR_TIME_UPDATE_STATE 0x2A17 +#define UUID16_CHR_TIME_WITH_DST 0x2A11 +#define UUID16_CHR_TIME_ZONE 0x2A0E +#define UUID16_CHR_TX_POWER_LEVEL 0x2A07 +#define UUID16_CHR_CSC_FEATURE 0x2A5C +#define UUID16_CHR_CSC_MEASUREMENT 0x2A5B +#define UUID16_CHR_RSC_FEATURE 0x2A54 +#define UUID16_CHR_SC_CTRLPT 0x2A55 +#define UUID16_CHR_RSC_MEASUREMENT 0x2A53 +#define UUID16_CHR_SENSOR_LOCATION 0x2A5D +#define UUID16_EXTERNAL_REPORT_REF_DESCR 0x2907 +#define UUID16_REPORT_REF_DESCR 0x2908 +#define UUID16_CHR_LN_FEATURE 0x2A6A +#define UUID16_CHR_LN_POSITION_QUALITY 0x2A69 +#define UUID16_CHR_LN_LOCATION_AND_SPEED 0x2A67 +#define UUID16_CHR_LN_NAVIGATION 0x2A68 +#define UUID16_CHR_LN_CONTROL_POINT 0x2A6B +#define UUID16_BMS_CTRLPT 0x2AA4 +#define UUID16_BMS_FEATURE 0x2AA5 +#define UUID16_CGM_MEASUREMENT 0x2AA7 +#define UUID16_CGM_FEATURE 0x2AA8 +#define UUID16_CGM_STATUS 0x2AA9 +#define UUID16_CGM_SESSION_START_TIME 0x2AAA +#define UUID16_CGM_SESSION_RUN_TIME 0x2AAB +#define UUID16_CGM_SPECIFIC_OPS_CTRLPT 0x2AAC +#define UUID16_PLX_SPOT_CHECK_MEAS 0x2A5E +#define UUID16_PLX_CONTINUOUS_MEAS 0x2A5F +#define UUID16_PLX_FEATURES 0x2A60 + + +#endif /* BLEUUID_H_ */ diff --git a/libraries/BluefruitLib/src/bluefruit.cpp b/libraries/BluefruitLib/src/bluefruit.cpp new file mode 100644 index 00000000..3b2cc55d --- /dev/null +++ b/libraries/BluefruitLib/src/bluefruit.cpp @@ -0,0 +1,535 @@ +/**************************************************************************/ +/*! + @file bluefruit.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "bluefruit.h" + +#define BLE_VENDOR_UUID_MAX 10 +#define BLE_PRPH_MAX_CONN 1 +#define BLE_CENTRAL_MAX_CONN 0 +#define BLE_CENTRAL_MAX_SECURE_CONN 0 + +#define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS 3000 +#define CFG_GAP_CONNECTION_SLAVE_LATENCY 0 +#define CFG_GAP_ADV_INTERVAL_MS 20 +#define CFG_GAP_ADV_TIMEOUT_S 30 + +#define CFG_BLE_TX_POWER_LEVEL 0 +#define CFG_DEFAULT_NAME "Bluefruit" + +// Converts an integer of 1.25ms units to msecs +#define MS100TO125(ms100) (((ms100)*4)/5) + +// Converts an integer of 1.25ms units to msecs +#define MS125TO100(ms125) (((ms125)*5)/4) + +// Converts msec to 0.625 unit +#define MS1000TO625(ms1000) (((ms1000)*8)/5) + +// Converts an integer of 625ms units to msecs +#define MS625TO1000(u625) ( ((u625)*5) / 8 ) + +// To change this value, an adjustment for SRAM is required in linker script +#define BLE_GATTS_ATTR_TABLE_SIZE 0x1000 + +#define BLUEFRUIT_TASK_STACKSIZE (1024*4) + + +static void adafruit_bluefruit_task(void* arg); + +AdafruitBluefruit Bluefruit; + +AdafruitBluefruit::AdafruitBluefruit(void) +{ + varclr(&_adv); + varclr(&_scan_resp); + + _tx_power = 0; + + strcpy(_name, CFG_DEFAULT_NAME); + _txbuf_left = _txbuf_max = 0; + + _conn_hdl = BLE_GATT_HANDLE_INVALID; + + _chars_count = 0; + for(uint8_t i=0; i BLE_GAP_ADV_MAX_SIZE) + { + type = BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME; + len = BLE_GAP_ADV_MAX_SIZE - (_adv.count+2); + } + + return addAdvData(type, _name, len); +} + +// tx power is set by setTxPower +bool AdafruitBluefruit::addAdvTxPower(void) +{ + return addAdvData(BLE_GAP_AD_TYPE_TX_POWER_LEVEL, &_tx_power, 1); +} + +bool AdafruitBluefruit::addAdvFlags(uint8_t flags) +{ + return addAdvData(BLE_GAP_AD_TYPE_FLAGS, &flags, 1); +} + +uint8_t AdafruitBluefruit::getAdvLen(void) +{ + return _adv.count; +} + +uint8_t AdafruitBluefruit::getAdvData(uint8_t* buffer) +{ + memcpy(buffer, _adv.data, _adv.count); + return _adv.count; +} + +bool AdafruitBluefruit::setAdvData(uint8_t const * data, uint8_t count) +{ + VERIFY( data && count <= BLE_GAP_ADV_MAX_SIZE); + + memcpy(_adv.data, data, count); + _adv.count = count; + + return true; +} + +void AdafruitBluefruit::clearAdvData(void) +{ + varclr(&_adv); +} + +/*------------------------------------------------------------------*/ +/* Scan Response + *------------------------------------------------------------------*/ +bool AdafruitBluefruit::addScanData(uint8_t type, const void* data, uint8_t len) +{ + return _addToAdv(true, type, data, len); +} + +bool AdafruitBluefruit::addScanUuid(uint16_t uuid16) +{ + return addScanData(BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, &uuid16, 2); +} + +bool AdafruitBluefruit::addScanUuid(uint8_t const uuid128[]) +{ + return addScanData(BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, uuid128, 16); +} + +bool AdafruitBluefruit::addScanName(void) +{ + uint8_t type = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME; + uint8_t len = strlen(_name); + + // not enough for full name, chop it + if (_scan_resp.count + len + 2 > BLE_GAP_ADV_MAX_SIZE) + { + type = BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME; + len = BLE_GAP_ADV_MAX_SIZE - (_scan_resp.count+2); + } + + return addScanData(type, _name, len); +} + +uint8_t AdafruitBluefruit::getScanLen(void) +{ + return _scan_resp.count; +} + +uint8_t AdafruitBluefruit::getScanData(uint8_t* buffer) +{ + memcpy(buffer, _scan_resp.data, _scan_resp.count); + return _scan_resp.count; +} + +bool AdafruitBluefruit::setScanData(uint8_t const* data, uint8_t count) +{ + VERIFY (data && count <= BLE_GAP_ADV_MAX_SIZE); + + memcpy(_scan_resp.data, data, count); + _scan_resp.count = count; + + return true; +} + +void AdafruitBluefruit::clearScanData(void) +{ + varclr(&_scan_resp); +} + +err_t AdafruitBluefruit::startAdvertising(void) +{ + VERIFY_STATUS( sd_ble_gap_adv_data_set(_adv.data, _adv.count, _scan_resp.data, _scan_resp.count) ); + + // ADV Params + ble_gap_adv_params_t adv_para = + { + .type = BLE_GAP_ADV_TYPE_ADV_IND, + .p_peer_addr = NULL , // Undirected advertisement + .fp = BLE_GAP_ADV_FP_ANY , + .p_whitelist = NULL , + .interval = MS1000TO625(CFG_GAP_ADV_INTERVAL_MS), // advertising interval (in units of 0.625 ms) + .timeout = CFG_GAP_ADV_TIMEOUT_S + }; + + VERIFY_STATUS( sd_ble_gap_adv_start(&adv_para) ); + + return NRF_SUCCESS; +} + +void AdafruitBluefruit::stopAdvertising(void) +{ + sd_ble_gap_adv_stop(); +} + +err_t AdafruitBluefruit::addService(uint16_t uuid16) +{ + BLEUuid uuid(uuid16); + + uint16_t svc_handle; + return sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &uuid._uuid, &svc_handle); +} + +err_t AdafruitBluefruit::addService(uint8_t const uuid128[]) +{ + BLEUuid uuid; + uuid.set(uuid128); + + uint16_t svc_handle; + return sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &uuid._uuid, &svc_handle); +} + +err_t AdafruitBluefruit::_registerCharacteristic(BLECharacteristic* chars) +{ + if ( _chars_count == BLE_MAX_CHARS ) return NRF_ERROR_NO_MEM; + _chars_list[ _chars_count++ ] = chars; + + return NRF_SUCCESS; +} + +uint16_t AdafruitBluefruit::connHandle(void) +{ + return _conn_hdl; +} + +ble_gap_addr_t AdafruitBluefruit::peerAddr(void) +{ + return _peer_addr; +} + +bool AdafruitBluefruit::txbuf_available(void) +{ + return _txbuf_left > 0; +} + +void AdafruitBluefruit::txbuf_decrease(void) +{ + _txbuf_left--; +} + +/** + * + */ + +enum { + SEC_PARAM_TIMEOUT = 30 , /**< Timeout for Pairing Request or Security Request (in seconds). */ + SEC_PARAM_BOND = 1 , /**< Perform bonding. */ + SEC_PARAM_OOB = 0 , /**< Out Of Band data not available. */ + SEC_PARAM_MIN_KEY_SIZE = 7 , /**< Minimum encryption key size. */ + SEC_PARAM_MAX_KEY_SIZE = 16 +}; + +static void adafruit_bluefruit_task(void* arg) +{ + (void) arg; + + while (1) + { + Bluefruit.poll(); + + vTaskDelay(1); + //sd_app_evt_wait(); + } +} + +void AdafruitBluefruit::poll(void) +{ + enum { BLE_STACK_EVT_MSG_BUF_SIZE = (sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT)) }; + + uint32_t ev_buf[BLE_STACK_EVT_MSG_BUF_SIZE/4 + 4]; + uint16_t ev_len = sizeof(ev_buf); + ble_evt_t* evt = (ble_evt_t*) ev_buf; + + if( NRF_SUCCESS == sd_ble_evt_get((uint8_t*)ev_buf, &ev_len)) + { + switch ( evt->header.evt_id ) + { + case BLE_GAP_EVT_CONNECTED: + digitalWrite(LED_CONN, HIGH); + + _conn_hdl = evt->evt.gap_evt.conn_handle; + _peer_addr = evt->evt.gap_evt.params.connected.peer_addr; + + (void) sd_ble_tx_packet_count_get(_conn_hdl, &_txbuf_max); + _txbuf_left = _txbuf_max; + break; + + case BLE_GAP_EVT_DISCONNECTED: + _conn_hdl = BLE_GATT_HANDLE_INVALID; + digitalWrite(LED_CONN, LOW); + startAdvertising(); + break; + + case BLE_GAP_EVT_TIMEOUT: + if (evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISING) + { + // Restart Advertising + startAdvertising(); + } + break; + + case BLE_EVT_TX_COMPLETE: + _txbuf_left += evt->evt.common_evt.params.tx_complete.count; + break; + +#if 0 + case BLE_GAP_EVT_SEC_INFO_REQUEST: + if (_enc_key.master_id.ediv == evt->evt.gap_evt.params.sec_info_request.master_id.ediv) + { + sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_enc_key.enc_info, NULL, NULL); + } else + { + sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL); + } + break; + + case BLE_GAP_EVT_SEC_PARAMS_REQUEST: + { + ble_gap_sec_params_t sec_para = + { + .bond = SEC_PARAM_BOND , + .mitm = 0, //CFG_PIN_ENABLED ? nvm_data.core.passkey_enable : 0, + .lesc = 0, + .keypress = 0, + .io_caps = BLE_GAP_IO_CAPS_NONE, // (CFG_PIN_ENABLED && nvm_data.core.passkey_enable) ? BLE_GAP_IO_CAPS_DISPLAY_ONLY : BLE_GAP_IO_CAPS_NONE , + .oob = SEC_PARAM_OOB , + .min_key_size = SEC_PARAM_MIN_KEY_SIZE , + .max_key_size = SEC_PARAM_MAX_KEY_SIZE + }; + + ble_gap_sec_keyset_t keyset = + { + .keys_own = { + .p_enc_key = &_enc_key, + .p_id_key = NULL, + .p_sign_key = NULL, + .p_pk = NULL + }, + + .keys_peer = { NULL, NULL, NULL, NULL } + }; + + VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &sec_para, &keyset), + RETURN_VOID); + } + break; + + case BLE_GAP_EVT_AUTH_STATUS: + // Bonding succeeded --> save encryption keys + if (BLE_GAP_SEC_STATUS_SUCCESS == evt->evt.gap_evt.params.auth_status.auth_status) + { + + } + break; + + case BLE_GATTS_EVT_SYS_ATTR_MISSING: + sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); + break; +#endif + + case BLE_GAP_EVT_CONN_SEC_UPDATE: + break; + + default: break; + } + + // GATTs characteristics event handler + for(int i=0; i<_chars_count; i++) + { + _chars_list[i]->eventHandler(evt); + } + } +} diff --git a/libraries/BluefruitLib/src/bluefruit.h b/libraries/BluefruitLib/src/bluefruit.h new file mode 100644 index 00000000..f0600bc0 --- /dev/null +++ b/libraries/BluefruitLib/src/bluefruit.h @@ -0,0 +1,143 @@ +/**************************************************************************/ +/*! + @file bluefruit.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include +#include "utility/common_inc.h" + +#include "BLEUuid.h" +#include "BLECharacteristic.h" +#include "BLEService.h" + +// Services +#include "utility/services/BLEDis.h" +#include "utility/services/BLEDfu.h" +#include "utility/services/BLEUart.h" +#include "utility/services/BLEBas.h" + +#define BLE_MAX_CHARS 50 + +#define BLE_MAX_DATA_PER_MTU (GATT_MTU_SIZE_DEFAULT - 3) + +class AdafruitBluefruit +{ + public: + // Constructor + AdafruitBluefruit(void); + + err_t begin(void); + + void setName(const char* str); +// bool setTxPower(int8_t power); + + // Advertising Packet + uint8_t getAdvLen(void); + uint8_t getAdvData(uint8_t* buffer); + bool setAdvData(const uint8_t* data, uint8_t count); + void clearAdvData(void); + + bool addAdvData(uint8_t type, const void* data, uint8_t len); + bool addAdvFlags(uint8_t flags); + bool addAdvTxPower(void); + bool addAdvName(void); + bool addAdvUuid(uint16_t uuid16); + bool addAdvUuid(uint8_t const uuid128[]); + bool addAdvService(BLEService& service); + + // Scan Response Data (less helper than Adv packet) + uint8_t getScanLen(void); + uint8_t getScanData(uint8_t* buffer); + bool setScanData(const uint8_t* data, uint8_t count); + void clearScanData(void); + + bool addScanData(uint8_t type, const void* data, uint8_t len); + bool addScanName(void); + bool addScanUuid(uint16_t uuid16); + bool addScanUuid(uint8_t const uuid128[]); + + err_t startAdvertising(void); + void stopAdvertising(void); + + void poll(void); + + // Add service without using BLEService instance + err_t addService(uint16_t uuid16); + err_t addService(uint8_t const uuid128[]); + + uint16_t connHandle(void); + ble_gap_addr_t peerAddr(void); + + void txbuf_decrease(void); + bool txbuf_available(void); + + void disconnect(void); + bool connected(void); + + // internal usage only + err_t _registerCharacteristic(BLECharacteristic* chars); + + private: + BLEDfu _dfu_svc; + + // ADV Data + struct { + uint8_t data[BLE_GAP_ADV_MAX_SIZE]; + uint8_t count; + } _adv, _scan_resp; + + int8_t _tx_power; + + char _name[32+1]; // 32 including null terminator + + BLECharacteristic* _chars_list[BLE_MAX_CHARS]; + uint8_t _chars_count; + + uint16_t _conn_hdl; + + // TODO move to bonding place + ble_gap_enc_key_t _enc_key; + ble_gap_addr_t _peer_addr; + + // Transmission Buffer Count for HVX notification, max is seen at 7 + uint8_t _txbuf_max; + uint8_t _txbuf_left; + + bool _addToAdv(bool scan_resp, uint8_t type, const void* data, uint8_t len); +}; + +extern AdafruitBluefruit Bluefruit; + + + diff --git a/libraries/BluefruitLib/src/utility/TimeoutTimer.h b/libraries/BluefruitLib/src/utility/TimeoutTimer.h new file mode 100644 index 00000000..22629028 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/TimeoutTimer.h @@ -0,0 +1,56 @@ +/**************************************************************************/ +/*! + @file TimeoutTimer.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2014, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#ifndef _TIMEOUT_TIMER_H_ +#define _TIMEOUT_TIMER_H_ + +class TimeoutTimer +{ + private: + uint32_t start; + uint32_t interval; + + public: + TimeoutTimer() { start = millis(); interval = 0; } + TimeoutTimer(uint32_t msec) { set(msec); } + + void set(uint32_t msec) { start = millis(); interval = msec; } + bool expired(void) const { return (millis() - start) >= interval; } + void restart(void) { start = millis(); } + void reset(void) { start += interval; } // used for periodic invoke to prevent drift +}; + +#endif /* _TIMEOUT_TIMER_H_ */ diff --git a/libraries/BluefruitLib/src/utility/adafruit_fifo.cpp b/libraries/BluefruitLib/src/utility/adafruit_fifo.cpp new file mode 100644 index 00000000..ed51c88e --- /dev/null +++ b/libraries/BluefruitLib/src/utility/adafruit_fifo.cpp @@ -0,0 +1,220 @@ +/**************************************************************************/ +/*! + @file adafruit_fifo.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2015, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "adafruit_fifo.h" +#include + +/******************************************************************************/ +/*! + @brief Constructor + + @param[in] buffer + Memory location to store data + @param[in] depth + Maximum number of items can be hold in buffer + @param[in] item_size + Number of bytes of each item + @param[in] overwrite + Should the buffer is overwitten to the first item when it is full +*/ +/******************************************************************************/ +Adafruit_FIFO::Adafruit_FIFO(void* buffer, uint16_t depth, uint8_t item_size, bool overwrite) + : _buffer( (uint8_t*) buffer), _depth(depth), _item_size(item_size), _overwritable(overwrite) +{ + _count = _wr_idx = _rd_idx = 0; +} + +/******************************************************************************/ +/*! + @brief Clear the FIFO +*/ +/******************************************************************************/ +void Adafruit_FIFO::clear(void) +{ + _rd_idx = _wr_idx = _count = 0; +} + +/******************************************************************************/ +/*! + @brief Write an item to the FIFO + + @param[in] item + Memory address of the item +*/ +/******************************************************************************/ +bool Adafruit_FIFO::write(void const* item) +{ + if ( full() && !_overwritable ) return false; + + memcpy( _buffer + (_wr_idx * _item_size), + item, + _item_size); + + _wr_idx = (_wr_idx + 1) % _depth; + + if ( full() ) + { + _rd_idx = _wr_idx; // keep the full state (rd == wr && len = size) + } + else + { + _count++; + } + + return true; +} + +/******************************************************************************/ +/*! + @brief Write array of items to the FIFO + + @param[in] data + Memory address of the item's array + @param[in] n + Number of items to write + + @return Number of written items +*/ +/******************************************************************************/ +uint16_t Adafruit_FIFO::write_n(void const * data, uint16_t n) +{ + if ( n == 0 ) return 0; + + uint8_t* buf = (uint8_t*) data; + + uint16_t len = 0; + while( (len < n) && write(buf) ) + { + len++; + buf += _item_size; + } + + return len; +} + +/******************************************************************************/ +/*! + @brief Read an item from FIFO + + @param[in] buffer + Memory address to store item +*/ +/******************************************************************************/ +bool Adafruit_FIFO::read(void* buffer) +{ + if( empty() ) return false; + + memcpy(buffer, + _buffer + (_rd_idx * _item_size), + _item_size); + _rd_idx = (_rd_idx + 1) % _depth; + _count--; + + return true; +} + +/******************************************************************************/ +/*! + @brief Read multiple items to an array + + @param[in] buffer + Memory address of the item's array + @param[in] n + Number of items to read + + @return Number of read items +*/ +/******************************************************************************/ + +uint16_t Adafruit_FIFO::read_n (void * buffer, uint16_t n) +{ + if( n == 0 ) return 0; + + uint8_t* buf = (uint8_t*) buffer; + + uint16_t len = 0; + while( (len < n) && read(buf) ) + { + len++; + buf += _item_size; + } + + return len; +} + +/******************************************************************************/ +/*! + @brief Read an item without removing it from the FIFO + + @param[in] buffer + Memory address to store item +*/ +/******************************************************************************/ +bool Adafruit_FIFO::peek(void* buffer) +{ + if( empty() ) return false; + + memcpy(buffer, + _buffer + (_rd_idx * _item_size), + _item_size); + + return true; +} + + +/******************************************************************************/ +/*! + @brief Read an item without removing it from the FIFO at the specific index + + @param[in] position + Position to read from in the FIFO buffer + + @param[in] buffer + Memory address to store item +*/ +/******************************************************************************/ +bool Adafruit_FIFO::peekAt(uint16_t position, void * p_buffer) +{ + if( empty() || (position >= _count) ) return false; + + uint16_t index = (_rd_idx + position) % _depth; // rd_idx is position=0 + memcpy(p_buffer, + _buffer + (index * _item_size), + _item_size); + + return true; +} + diff --git a/libraries/BluefruitLib/src/utility/adafruit_fifo.h b/libraries/BluefruitLib/src/utility/adafruit_fifo.h new file mode 100644 index 00000000..685efe43 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/adafruit_fifo.h @@ -0,0 +1,74 @@ +/**************************************************************************/ +/*! + @file adafruit_fifo.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2015, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#ifndef _Adafruit_FIFO_H_ +#define _Adafruit_FIFO_H_ + +#include +#include + +class Adafruit_FIFO +{ + private: + uint8_t* _buffer ; ///< buffer pointer + const uint16_t _depth ; ///< max items + const uint8_t _item_size ; ///< size of each item + const bool _overwritable ; ///< Overwrite when full + volatile uint16_t _count ; ///< number of items in queue + volatile uint16_t _wr_idx ; ///< write pointer + volatile uint16_t _rd_idx ; ///< read pointer + + public: + // Constructor + Adafruit_FIFO(void* buffer, uint16_t depth, uint8_t item_size, bool overwrite); + + void clear(void); + bool peek(void* buffer); + bool peekAt(uint16_t position, void * p_buffer); + + bool write(void const* item); + uint16_t write_n(void const * data, uint16_t n); + + bool read(void* buffer); + uint16_t read_n (void * buffer, uint16_t n); + + inline bool empty(void) { return _count == 0; } + inline bool full(void) { return _count == _depth; } + inline uint16_t count(void) { return _count; } + inline uint16_t remaining(void) { return _depth - _count; } +}; + +#endif /* _Adafruit_FIFO_H_ */ diff --git a/libraries/BluefruitLib/src/utility/common_func.h b/libraries/BluefruitLib/src/utility/common_func.h new file mode 100644 index 00000000..1b3209bd --- /dev/null +++ b/libraries/BluefruitLib/src/utility/common_func.h @@ -0,0 +1,219 @@ +/**************************************************************************/ +/*! + @file common_func.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#ifndef _COMMON_FUNC_H_ +#define _COMMON_FUNC_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define memclr(buffer, size) memset(buffer, 0, size) +#define varclr(_var) memclr(_var, sizeof(*(_var))) +#define arrcount(_arr) ( sizeof(_arr) / sizeof(_arr[0]) ) + +#define __swap32(x) __REV(x) ///< built-in function to swap Endian of 32-bit number +#define __swap16(u16) ((uint16_t) __REV16(u16)) ///< built-in function to swap Endian of 16-bit number + +#define maxof(a,b) \ + ({ typeof (a) _a = (a); \ + typeof (b) _b = (b); \ + _a > _b ? _a : _b; }) + +#define minof(a,b) \ + ({ typeof (a) _a = (a); \ + typeof (b) _b = (b); \ + _a < _b ? _a : _b; }) + +//--------------------------------------------------------------------+ +// MACROS +//--------------------------------------------------------------------+ +#define U16_HIGH(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) +#define U16_LOW(u16) ((uint8_t) ((u16) & 0x00ff)) +#define U16_BYTES_BE(u16) U16_HIGH(u16), U16_LOW(u16) +#define U16_BYTES_LE(u16) U16_LOW(u16), U16_HIGH(u16) + +#define U32_BYTE1(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB +#define U32_BYTE2(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff)) +#define U32_BYTE3(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff)) +#define U32_BYTE4(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB + +#define U32_FROM_U8(b1, b2, b3, b4) ((uint32_t) (((b1) << 24) + ((b2) << 16) + ((b3) << 8) + (b4))) +#define U32_FROM_U16(high, low) ((uint32_t) (((high) << 16) | (low))) +#define U16_FROM_U8(high, low) ((uint32_t) (((high) << 8) | (low))) + +#define U32_BYTES_BE(u32) U32_BYTE1(u32), U32_BYTE2(u32), U32_BYTE3(u32), U32_BYTE4(u32) +#define U32_BYTES_LE(u32) U32_BYTE4(u32), U32_BYTE3(u32), U32_BYTE2(u32), U32_BYTE1(u32) + +#define SWAP16(x) ((uint16_t)(((x) << 8) | (((x) & 0xff00) >> 8))) + +//--------------------------------------------------------------------+ +// DEBUG HELPER +//--------------------------------------------------------------------+ +#if CFG_DEBUG == 3 + #define malloc_named( name, size ) ({ printf("[malloc] %s : %d\r\n", name, size); malloc(size); }) +#else + #define malloc_named( name, size ) malloc ( size ) +#endif + +#define PRINT_LOCATION() Serial.printf("%s: %d:\n", __PRETTY_FUNCTION__, __LINE__) +#define PRTNT_HEAP() if (CFG_DEBUG == 3) Serial.printf("\n%s: %d: Heap free: %d\n", __PRETTY_FUNCTION__, __LINE__, util_heap_get_free_size()) +#define PRINT_INT(x) Serial.printf("%s: %d: " #x " = %ld\n" , __PRETTY_FUNCTION__, __LINE__, (uint32_t) (x) ) +#define PRINT_HEX(x) Serial.printf("%s: %d: " #x " = %08lx\n", __PRETTY_FUNCTION__, __LINE__, (uint32_t) (x) ) +#define PRINT_STR(x) Serial.printf("%s: %d: " #x " = %s\n" , __PRETTY_FUNCTION__, __LINE__, (char*)(x) ) +#define PRINT_BUFFER(buf, n) \ + do {\ + uint8_t const* p8 = (uint8_t const*) (buf);\ + Serial.print(#buf ": ");\ + for(uint32_t i=0; i<(n); i++) Serial.printf("%02x ", p8[i]);\ + Serial.println();\ + }while(0) + +//--------------------------------------------------------------------+ +// INLINE FUNCTION +//--------------------------------------------------------------------+ +/// Checks is all values in the supplied array are zero +static inline bool mem_test_zero(void const* buffer, uint32_t size) +{ + uint8_t const* p_mem = (uint8_t const*) buffer; + for(uint32_t i=0; i y) ? x : y; } +static inline uint16_t max16(uint16_t x, uint16_t y) { return (x > y) ? x : y; } +static inline uint32_t max32(uint32_t x, uint32_t y) { return (x > y) ? x : y; } + +//------------- Conversion -------------// +/// form an uint32_t from 4 x uint8_t +static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) +{ + return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4; +} + +static inline uint16_t u32_high_u16(uint32_t u32) +{ + return (uint16_t) ((u32 >> 16) & 0xffff); +} + +static inline uint16_t u32_low_u16(uint32_t u32) +{ + return (uint16_t) (u32 & 0xffff); +} + +static inline uint16_t u16_from_u8(uint8_t b1, uint8_t b2) +{ + return (b1 << 8) + b2; +} + +static inline uint8_t u16_high_u8(uint16_t u16) +{ + return (uint8_t) ((u16 >> 8) & 0x00ff); +} + +static inline uint8_t u16_low_u8(uint16_t u16) +{ + return (uint8_t) (u16 & 0x00ff); +} + +//------------- Align -------------// +static inline uint32_t align32 (uint32_t value) +{ + return (value & 0xFFFFFFE0UL); +} + +static inline uint32_t align16 (uint32_t value) +{ + return (value & 0xFFFFFFF0UL); +} + +static inline uint32_t align_n (uint32_t alignment, uint32_t value) +{ + return value & (~(alignment-1)); +} + +static inline uint32_t align4k (uint32_t value) +{ + return (value & 0xFFFFF000UL); +} + +static inline uint32_t offset4k(uint32_t value) +{ + return (value & 0xFFFUL); +} + +//------------- Mathematics -------------// +static inline bool is_within(uint32_t lower, uint32_t value, uint32_t upper) +{ + return (lower <= value) && (value <= upper); +} + +static inline uint8_t log2_of(uint32_t value) +{ + uint8_t result = 0; // log2 of a value is its MSB's position + while (value >>= 1) result++; + + return result; +} + +// return the number of set bits in value +static inline uint8_t cardinality_of(uint32_t value) +{ + // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only + // the high bit set, then it will only go once through the loop + // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) + // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method + // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and + // published in 1964 in a book edited by Beckenbach.)" + uint8_t count; + for (count = 0; value; count++) + { + value &= value - 1; // clear the least significant bit set + } + + return count; +} + +#ifdef __cplusplus + } +#endif + +#endif /* _COMMON_FUNC_H_ */ diff --git a/libraries/BluefruitLib/src/utility/common_inc.h b/libraries/BluefruitLib/src/utility/common_inc.h new file mode 100644 index 00000000..ea16e8c2 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/common_inc.h @@ -0,0 +1,50 @@ +/**************************************************************************/ +/*! + @file common_inc.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef COMMON_INC_H_ +#define COMMON_INC_H_ + +#include +#include "ble.h" +#include "ble_hci.h" +#include "nrf_sdm.h" + +typedef uint32_t err_t; + +#include "utility/compiler_macro.h" +#include "utility/verify.h" +#include "utility/common_func.h" + +#endif /* COMMON_INC_H_ */ diff --git a/libraries/BluefruitLib/src/utility/compiler_macro.h b/libraries/BluefruitLib/src/utility/compiler_macro.h new file mode 100644 index 00000000..e3e1baca --- /dev/null +++ b/libraries/BluefruitLib/src/utility/compiler_macro.h @@ -0,0 +1,137 @@ +/******************************************************************************/ +/*! + @file compiler_macro.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, K. Townsend (microBuilder.eu) + Copyright (c) 2014, Adafruit Industries (adafruit.com) + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/******************************************************************************/ + +/** \ingroup Group_Compiler + * \defgroup Group_GCC GNU GCC + * @{ + */ + +#ifndef _COMPILER_MACRO_H_ +#define _COMPILER_MACRO_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#define STRING_(x) #x // stringify without expand +#define XSTRING_(x) STRING_(x) // expand then stringify +#define STRING_CONCAT_(a, b) a##b // concat without expand +#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) // expand then concat + +#define ALIGN_OF(x) __alignof__(x) + +/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section +#define ATTR_SECTION(section) __attribute__ ((#section)) + +/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking +#define ATTR_ERROR(Message) __attribute__ ((error(Message))) + +/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking +#define ATTR_WARNING(Message) __attribute__ ((warning(Message))) + +/** + * \defgroup Group_VariableAttr Variable Attributes + * @{ + */ + +/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes +#define ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) + +/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute +#define ATTR_PACKED __attribute__ ((packed)) + +#define ATTR_PREPACKED + +#define ATTR_PACKED_STRUCT(x) x __attribute__ ((packed)) +/** @} */ + +/** + * \defgroup Group_FuncAttr Function Attributes + * @{ + */ + +/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified +#define ATTR_ALWAYS_INLINE __attribute__ ((always_inline)) + +/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null +#define ATTR_NON_NULL __attribute__ ((nonull)) + +#define ATTR_NO_RETURN __attribute__ ((noreturn)) + +/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure +#define ATTR_PURE __attribute__ ((pure)) + +/// Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory. +/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void +#define ATTR_CONST __attribute__ ((const)) + +/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses +#define ATTR_DEPRECATED __attribute__ ((deprecated)) + +/// Same as the deprecated attribute with optional message in the warning +#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess))) + +/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code +#define ATTR_WEAK __attribute__ ((weak)) + +/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified +#define ATTR_ALIAS(func) __attribute__ ((alias(#func))) + +/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static +#define ATTR_WEAKREF(func) __attribute__ ((weakref(#func))) + +/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug +#define ATTR_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result)) + +/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly. +#define ATTR_USED __attribute__ ((used)) + +/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function. +#define ATTR_UNUSED __attribute__ ((unused)) + +#define ATTR_OPTIMIZE(n) __attribute__ ((optimize(XSTRING_(O##n)))) + +/** @} */ + +#ifdef __cplusplus + } +#endif + +#endif /* _COMPILER_MACRO_H_ */ + +/// @} diff --git a/libraries/BluefruitLib/src/utility/services/BLEBas.cpp b/libraries/BluefruitLib/src/utility/services/BLEBas.cpp new file mode 100644 index 00000000..a04dd334 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEBas.cpp @@ -0,0 +1,65 @@ +/**************************************************************************/ +/*! + @file BLEBas.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2017, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "bluefruit.h" + +BLEBas::BLEBas(void) : + BLEService(UUID16_SVC_BATTERY), _battery(UUID16_CHR_BATTERY_LEVEL) +{ + +} + +err_t BLEBas::start(void) +{ + VERIFY_STATUS( this->addToGatt() ); + + _battery.setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY); // could support notify + _battery.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); + _battery.setFixedLen(1); + VERIFY_STATUS( _battery.start() ); + + return NRF_SUCCESS; +} + +void BLEBas::update(uint8_t level) +{ + _battery.write(level); +} + +void BLEBas::notify(uint8_t level) +{ + _battery.notify(level); +} diff --git a/libraries/BluefruitLib/src/utility/services/BLEBas.h b/libraries/BluefruitLib/src/utility/services/BLEBas.h new file mode 100644 index 00000000..aaa25d0a --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEBas.h @@ -0,0 +1,60 @@ +/**************************************************************************/ +/*! + @file BLEBas.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2017, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLEBAS_H_ +#define BLEBAS_H_ + +#include "utility/common_inc.h" + +#include "BLECharacteristic.h" +#include "BLEService.h" + +class BLEBas : public BLEService +{ + protected: + BLECharacteristic _battery; + + public: + BLEBas(void); + + virtual err_t start(void); + + void update(uint8_t level); + void notify(uint8_t level); +}; + + + +#endif /* BLEBAS_H_ */ diff --git a/libraries/BluefruitLib/src/utility/services/BLEDfu.cpp b/libraries/BluefruitLib/src/utility/services/BLEDfu.cpp new file mode 100644 index 00000000..8080b0e1 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEDfu.cpp @@ -0,0 +1,180 @@ +/**************************************************************************/ +/*! + @file BLEDfu.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "bluefruit.h" + +#define DFU_REV_APPMODE 0x0001 + +/* DFU Serivce : 00001530-1212-EFDE-1523-785FEABCD123 + * DFU Control : 00001531-1212-EFDE-1523-785FEABCD123 + * DFU Packet : 00001532-1212-EFDE-1523-785FEABCD123 + * DFU Revision: 00001534-1212-EFDE-1523-785FEABCD123 + */ + +const uint8_t UUID128_SVC_DFU_OTA[16] = +{ + 0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15, + 0xDE, 0xEF, 0x12, 0x12, 0x30, 0x15, 0x00, 0x00 +}; + + +const uint8_t UUID128_CHR_DFU_CONTROL[16] = +{ + 0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15, + 0xDE, 0xEF, 0x12, 0x12, 0x31, 0x15, 0x00, 0x00 +}; + +const uint8_t UUID128_CHR_DFU_PACKET[16] = +{ + 0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15, + 0xDE, 0xEF, 0x12, 0x12, 0x32, 0x15, 0x00, 0x00 +}; + +const uint8_t UUID128_CHR_DFU_REVISON[16] = +{ + 0x23, 0xD1, 0xBC, 0xEA, 0x5F, 0x78, 0x23, 0x15, + 0xDE, 0xEF, 0x12, 0x12, 0x34, 0x15, 0x00, 0x00 +}; + +extern "C" void bootloader_util_app_start(uint32_t start_addr); + +static uint16_t crc16(const uint8_t* data_p, uint8_t length) +{ + uint8_t x; + uint16_t crc = 0xFFFF; + + while ( length-- ) + { + x = crc >> 8 ^ *data_p++; + x ^= x >> 4; + crc = (crc << 8) ^ ((uint16_t) (x << 12)) ^ ((uint16_t) (x << 5)) ^ ((uint16_t) x); + } + return crc; +} + +static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request) +{ + if ( (request->handle == chr.handles().value_handle) && + (request->op != BLE_GATTS_OP_PREP_WRITE_REQ) && + (request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) && + (request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL)) + { + ble_gatts_rw_authorize_reply_params_t reply = { .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE }; + + if ( !chr.notifyEnabled() ) + { + reply.params.write.gatt_status = BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR; + sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply); + return; + } + + reply.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS; + sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply); + + enum { START_DFU = 1 }; + if ( request->data[0] == START_DFU ) + { + // Peer data information so that bootloader could re-connect after reboot + typedef struct { + ble_gap_addr_t addr; + ble_gap_irk_t irk; + ble_gap_enc_key_t enc_key; + uint8_t sys_attr[8]; + uint16_t crc16; + }peer_data_t; + + // Peer data address is defined in bootloader linker @0x20007F80 + peer_data_t* peer_data = (peer_data_t*) (0x20007F80UL); + varclr(peer_data); + + uint16_t sysattr_len = sizeof(peer_data->sys_attr); + sd_ble_gatts_sys_attr_get(Bluefruit.connHandle(), peer_data->sys_attr, &sysattr_len, BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS); + + // Received Start DFU command, init the reboot sequence into DFU OTA mode + Bluefruit.disconnect(); + Bluefruit.stopAdvertising(); + + // Set GPReset to DFU OTA + enum { DFU_OTA_MAGIC = 0xB1 }; + VERIFY_STATUS( sd_power_gpregret_set(DFU_OTA_MAGIC), RETURN_VOID); + VERIFY_STATUS( sd_softdevice_disable(), RETURN_VOID ); + VERIFY_STATUS( sd_softdevice_vector_table_base_set(NRF_UICR->NRFFW[0]), RETURN_VOID); + + // Save Peer data (currently only support non-bonded peer) + peer_data->addr = Bluefruit.peerAddr(); + peer_data->crc16 = crc16((uint8_t*) peer_data, offsetof(peer_data_t, crc16)); + + NVIC_ClearPendingIRQ(SWI2_IRQn); + + // Disable all interrupts + for(int i=0; iNRFFW[0]); + } + } +} + +BLEDfu::BLEDfu(void) : BLEService(UUID128_SVC_DFU_OTA), _chr_control(UUID128_CHR_DFU_CONTROL) +{ + +} + +err_t BLEDfu::start(void) +{ + VERIFY_STATUS( this->addToGatt() ); + + // No need to keep packet & revision characteristics + BLECharacteristic chr_packet(UUID128_CHR_DFU_PACKET); + chr_packet.setProperties(CHR_PROPS_WRITE_WO_RESP); + chr_packet.setMaxLen(20); + VERIFY_STATUS( chr_packet.start() ); + + _chr_control.setProperties(CHR_PROPS_WRITE | CHR_PROPS_NOTIFY); + _chr_control.setMaxLen(23); + _chr_control.setWriteAuthorizeCallbak(bledfu_control_wr_authorize_cb); + VERIFY_STATUS( _chr_control.start() ); + + BLECharacteristic chr_revision(UUID128_CHR_DFU_REVISON); + chr_revision.setProperties(CHR_PROPS_READ); + chr_revision.setFixedLen(2); + VERIFY_STATUS( chr_revision.start()); + chr_revision.write( (uint16_t) DFU_REV_APPMODE); + + return NRF_SUCCESS; +} diff --git a/libraries/BluefruitLib/src/utility/services/BLEDfu.h b/libraries/BluefruitLib/src/utility/services/BLEDfu.h new file mode 100644 index 00000000..6f373b3d --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEDfu.h @@ -0,0 +1,55 @@ +/**************************************************************************/ +/*! + @file BLEDfu.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLEDFU_H_ +#define BLEDFU_H_ + +#include "utility/common_inc.h" + +#include "BLECharacteristic.h" +#include "BLEService.h" + +class BLEDfu : public BLEService +{ + protected: + BLECharacteristic _chr_control; + + public: + BLEDfu(void); + + virtual err_t start(void); +}; + +#endif /* BLEDFU_H_ */ diff --git a/libraries/BluefruitLib/src/utility/services/BLEDis.cpp b/libraries/BluefruitLib/src/utility/services/BLEDis.cpp new file mode 100644 index 00000000..69106b1a --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEDis.cpp @@ -0,0 +1,110 @@ +/**************************************************************************/ +/*! + @file BLEDis.cpp + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ + +#include "bluefruit.h" + +BLEDis::BLEDis(void) : BLEService(UUID16_SVC_DEVICE_INFORMATION) +{ + _model = NULL; + _serial = NULL; + _firmware_rev = NULL; + _hardware_rev = NULL; + _software_rev = NULL; + _manufacturer = NULL; +} + +BLEDis::BLEDis(const char * model, const char * serial, const char * firmware_rev, + const char * hardware_rev, const char * software_rev, const char * manufacturer) + : BLEService(UUID16_SVC_DEVICE_INFORMATION) +{ + _model = model; + _serial = serial; + _firmware_rev = firmware_rev; + _hardware_rev = hardware_rev; + _software_rev = software_rev; + _manufacturer = manufacturer; +} + +void BLEDis::setModel(const char* model) +{ + _model = model; +} + +void BLEDis::setSerial(const char* serial) +{ + _serial = serial; +} + +void BLEDis::setFirmwareRev(const char* fw_rev) +{ + _firmware_rev = fw_rev; +} + +void BLEDis::setHardwareRev(const char* hw_rev) +{ + _hardware_rev = hw_rev; +} + +void BLEDis::setSoftwareRev(const char* sw_rev) +{ + _software_rev = sw_rev; +} + +void BLEDis::setManufacturer(const char* manufacturer) +{ + _manufacturer = manufacturer; +} + +err_t BLEDis::start(void) +{ + VERIFY_STATUS( this->addToGatt() ); + + for(uint8_t i=0; idata, request->len); +} + +err_t BLEUart::start(void) +{ + VERIFY_STATUS( this->addToGatt() ); + + // Add TXD Characteristic + _txd.setProperties(CHR_PROPS_NOTIFY); +// _txd.setMaxLen(BLE_MAX_DATA_PER_MTU); + + // TODO enable encryption when bonding is enabled +// _txd.setPermission(SECMODE_ENC_NO_MITM, SECMODE_NO_ACCESS); + _txd.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); + + _txd.setDescriptor("TXD"); + VERIFY_STATUS( _txd.start() ); + + // Add RXD Characteristic + _rxd.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP); + _rxd.setWriteCallback(bleuart_rxd_cb); + + // TODO enable encryption when bonding is enabled +// _rxd.setPermission(SECMODE_NO_ACCESS, SECMODE_ENC_NO_MITM); + _rxd.setPermission(SECMODE_NO_ACCESS, SECMODE_OPEN); + + _rxd.setDescriptor("RXD"); + VERIFY_STATUS(_rxd.start()); + + + return NRF_SUCCESS; +} + +int BLEUart::read (void) +{ + uint8_t ch; + return read(&ch, 1) ? (int) ch : EOF; +} + +int BLEUart::read (uint8_t * buf, size_t size) +{ + return _rxd_fifo.read_n(buf, size); +} + +size_t BLEUart::write (uint8_t b) +{ + return write(&b, 1); +} + +size_t BLEUart::write (const uint8_t *content, size_t len) +{ +#if 0 // need rtos for timeout waiting + TimeoutTimer tt(100); + + while ( !Bluefruit.txbuf_available() && !tt.expired() ) + { + delay(1); + } + + if ( tt.expired() ) return 0; +#endif + + if ( !Bluefruit.txbuf_available() ) return 0; + + _txd.notify(content, len); + + return len; +} + +int BLEUart::available (void) +{ + return _rxd_fifo.count(); +} + +int BLEUart::peek (void) +{ + uint8_t ch; + return _rxd_fifo.peek(&ch) ? (int) ch : EOF; +} + +void BLEUart::flush (void) +{ + _rxd_fifo.clear(); +} + + diff --git a/libraries/BluefruitLib/src/utility/services/BLEUart.h b/libraries/BluefruitLib/src/utility/services/BLEUart.h new file mode 100644 index 00000000..5e17b93e --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/BLEUart.h @@ -0,0 +1,75 @@ +/**************************************************************************/ +/*! + @file BLEUart.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2016, Adafruit Industries (adafruit.com) + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/**************************************************************************/ +#ifndef BLEUART_H_ +#define BLEUART_H_ + +#include "utility/common_inc.h" +#include "utility/adafruit_fifo.h" + +#include "BLECharacteristic.h" +#include "BLEService.h" + +#define BLE_UART_FIFO_LEN 64 + +class BLEUart : public BLEService, public Stream +{ + protected: + BLECharacteristic _txd; + BLECharacteristic _rxd; + + uint8_t _rxd_buf[BLE_UART_FIFO_LEN]; + Adafruit_FIFO _rxd_fifo; + + public: + BLEUart(void); + + virtual err_t start(void); + + // Stream API + virtual int read ( void ); + virtual int read ( uint8_t * buf, size_t size ); + virtual size_t write ( uint8_t b ); + virtual size_t write ( const uint8_t *content, size_t len ); + virtual int available ( void ); + virtual int peek ( void ); + virtual void flush ( void ); + + friend void bleuart_rxd_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request); +}; + + + +#endif /* BLEUART_H_ */ diff --git a/libraries/BluefruitLib/src/utility/services/bootloader_util.c b/libraries/BluefruitLib/src/utility/services/bootloader_util.c new file mode 100644 index 00000000..88a172f8 --- /dev/null +++ b/libraries/BluefruitLib/src/utility/services/bootloader_util.c @@ -0,0 +1,74 @@ +/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. + * + * The information contained herein is property of Nordic Semiconductor ASA. + * Terms and conditions of usage are described in detail in NORDIC + * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. + * + * Licensees are granted free, non-transferable use of the information. NO + * WARRANTY of ANY KIND is provided. This heading must NOT be removed from + * the file. + * + */ + +#include +#include + + +/** + * @brief Function for aborting current application/bootloader jump to to other app/bootloader. + * + * @details This functions will use the address provide to swap the stack pointer and then load + * the address of the reset handler to be executed. It will check current system mode + * (thread/handler) and if in thread mode it will reset into other application. + * If in handler mode \ref isr_abort will be executed to ensure correct exit of handler + * mode and jump into reset handler of other application. + * + * @param[in] start_addr Start address of other application. This address must point to the + initial stack pointer of the application. + * + * @note This function will never return but issue a reset into provided application. + */ +static inline void bootloader_util_reset(uint32_t start_addr) +{ + __asm volatile( + "ldr r0, [%0]\t\n" // Get App initial MSP for bootloader. + "msr msp, r0\t\n" // Set the main stack pointer to the applications MSP. + "ldr r0, [%0, #0x04]\t\n" // Load Reset handler into R0. + + "movs r4, #0xFF\t\n" // Move ones to R4. + "sxtb r4, r4\t\n" // Sign extend R4 to obtain 0xFFFFFFFF instead of 0xFF. + + "mrs r5, IPSR\t\n" // Load IPSR to R5 to check for handler or thread mode. + "cmp r5, #0x00\t\n" // Compare, if 0 then we are in thread mode and can continue to reset handler of bootloader. + "bne isr_abort\t\n" // If not zero we need to exit current ISR and jump to reset handler of bootloader. + + "mov lr, r4\t\n" // Clear the link register and set to ones to ensure no return. + "bx r0\t\n" // Branch to reset handler of bootloader. + + "isr_abort: \t\n" + + "mov r5, r4\t\n" // Fill with ones before jumping to reset handling. Will be popped as LR when exiting ISR. Ensures no return to application. + "mov r6, r0\t\n" // Move address of reset handler to R6. Will be popped as PC when exiting ISR. Ensures the reset handler will be executed when exist ISR. + "movs r7, #0x21\t\n" // Move MSB reset value of xPSR to R7. Will be popped as xPSR when exiting ISR. xPSR is 0x21000000 thus MSB is 0x21. + "rev r7, r7\t\n" // Reverse byte order to put 0x21 as MSB. + "push {r4-r7}\t\n" // Push everything to new stack to allow interrupt handler to fetch it on exiting the ISR. + + "movs r4, #0x00\t\n" // Fill with zeros before jumping to reset handling. We be popped as R0 when exiting ISR (Cleaning up of the registers). + "movs r5, #0x00\t\n" // Fill with zeros before jumping to reset handling. We be popped as R1 when exiting ISR (Cleaning up of the registers). + "movs r6, #0x00\t\n" // Fill with zeros before jumping to reset handling. We be popped as R2 when exiting ISR (Cleaning up of the registers). + "movs r7, #0x00\t\n" // Fill with zeros before jumping to reset handling. We be popped as R3 when exiting ISR (Cleaning up of the registers). + "push {r4-r7}\t\n" // Push zeros (R4-R7) to stack to prepare for exiting the interrupt routine. + + "movs r0, #0xF9\t\n" // Move the execution return command into register, 0xFFFFFFF9. + "sxtb r0, r0\t\n" // Sign extend R0 to obtain 0xFFFFFFF9 instead of 0xF9. + "bx r0\t\n" // No return - Handler mode will be exited. Stack will be popped and execution will continue in reset handler initializing other application. + ".align\t\n" + :: "r" (start_addr) // Argument list for the gcc assembly. start_addr is %0. + : "r0", "r4", "r5", "r6", "r7" // List of register maintained manually. + ); +} + +void bootloader_util_app_start(uint32_t start_addr) +{ + bootloader_util_reset(start_addr); +} diff --git a/libraries/BluefruitLib/src/utility/verify.h b/libraries/BluefruitLib/src/utility/verify.h new file mode 100644 index 00000000..8e9c51ca --- /dev/null +++ b/libraries/BluefruitLib/src/utility/verify.h @@ -0,0 +1,131 @@ +/******************************************************************************/ +/*! + @file verify.h + @author hathach + + @section LICENSE + + Software License Agreement (BSD License) + + Copyright (c) 2013, K. Townsend (microBuilder.eu) + Copyright (c) 2015, Adafruit Industries (adafruit.com) + Copyright (c) 2016, hathach (tinyusb.org) + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holders nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +/******************************************************************************/ + +#ifndef _VERIFY_H_ +#define _VERIFY_H_ + +#include "compiler_macro.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define CFG_DEBUG 1 + +#define RETURN_VOID + +//--------------------------------------------------------------------+ +// Compile-time Assert +//--------------------------------------------------------------------+ +#if defined __COUNTER__ && __COUNTER__ != __COUNTER__ + #define _VERIFY_COUNTER __COUNTER__ +#else + #define _VERIFY_COUNTER __LINE__ +#endif + +#define VERIFY_STATIC(const_expr, message) enum { XSTRING_CONCAT_(static_verify_, _VERIFY_COUNTER) = 1/(!!(const_expr)) } + +//--------------------------------------------------------------------+ +// VERIFY Helper +//--------------------------------------------------------------------+ +#if CFG_DEBUG >= 1 +// #define VERIFY_MESS(format, ...) printf("[%08ld] %s: %d: verify failed\n", get_millis(), __func__, __LINE__) + #define VERIFY_MESS(_status) Serial.printf("%s: %d: verify failed, status = 0x%04X\n", __PRETTY_FUNCTION__, __LINE__, _status); +#else + #define VERIFY_MESS(_status) +#endif + + +#define VERIFY_DEFINE(_status, _error) \ + if ( 0 != _status ) { \ + VERIFY_MESS(_status) \ + return _error; \ + } + +/** + * Helper to implement optional parameter for VERIFY Macro family + */ +#define VERIFY_GETARGS(arg1, arg2, arg3, ...) arg3 + +/*------------------------------------------------------------------*/ +/* VERIFY STATUS + * - VERIFY_STS_1ARGS : return status of condition if failed + * - VERIFY_STS_2ARGS : return provided status code if failed + *------------------------------------------------------------------*/ +#define VERIFY_STS_1ARGS(sts) \ + do { \ + err_t _status = (err_t)(sts); \ + VERIFY_DEFINE(_status, _status);\ + } while(0) + +#define VERIFY_STS_2ARGS(sts, _error) \ + do { \ + err_t _status = (err_t)(sts); \ + VERIFY_DEFINE(_status, _error);\ + } while(0) + +/** + * Check if status is success (zero), otherwise return + * - status value if called with 1 parameter e.g VERIFY_STATUS(status) + * - 2 parameter if called with 2 parameters e.g VERIFY_STATUS(status, errorcode) + */ +#define VERIFY_STATUS(...) VERIFY_GETARGS(__VA_ARGS__, VERIFY_STS_2ARGS, VERIFY_STS_1ARGS)(__VA_ARGS__) + + +/*------------------------------------------------------------------*/ +/* VERIFY + * - VERIFY_1ARGS : return condition if failed (false) + * - VERIFY_2ARGS : return provided value if failed + *------------------------------------------------------------------*/ +#define VERIFY_1ARGS(cond) if (!(cond)) return false; +#define VERIFY_2ARGS(cond, _error) if (!(cond)) return _error; + +/** + * Check if condition is success (true), otherwise return + * - false value if called with 1 parameter e.g VERIFY(condition) + * - 2 parameter if called with 2 parameters e.g VERIFY(condition, errorcode) + */ +#define VERIFY(...) VERIFY_GETARGS(__VA_ARGS__, VERIFY_2ARGS, VERIFY_1ARGS)(__VA_ARGS__) + +#ifdef __cplusplus +} +#endif + +#endif /* _VERIFY_H_ */