Merge branch '0.8.x' into develop

This commit is contained in:
hathach committed 2018-04-03 17:15:33 +07:00
commit bba9ae1d12
45 files changed
+2294 -607

No files matched your search

+22
View File
@@ -2,6 +2,28 @@
## 0.9.0
## 0.8.3
- Enhanced indicate API() to wait for confirm or timeout from peer.
- Added BLEScanner filterService() for BLEService and BLEClientService
- Enhanced bonding management to support central bond and re-connection
- Added BLEClientHidAdafruit implementation for client HID
- Added Central HID example
- Enhanced BLEHidGeneric/BLEHidAdafruit to support boot protocol mode.
- Fixed I2C lock-up when endTransmission() is called with empty txBuffer.
## 0.8.2
- Fixed burning bootloader issue with MacOS
- Added gpstest_swuart example sketch
- Added indicate API for BLECharacteristic
- Added custom_htm as usage example for indicate API.
- BLEClientCharacteristic
- Added setIndicateCallback(), issue #113
- Added useAdaCallback option to setNotifyCallback(), setIndicateCallback()
- Change notify callback signature from
notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) to notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
## 0.8.1
- Prevent sketch compiled with S132 v2 upload to device running S132 v5 and vice versa.
+1
View File
@@ -36,6 +36,7 @@ void init( void )
// Retrieve bootloader version
bootloaderVersion = BOOTLOADER_VERSION_REGISTER;
// Select Clock Source : XTAL or RC
#if defined( USE_LFXO )
// 32Khz XTAL
NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk);
@@ -554,14 +554,6 @@ void HAPCharacteristic::_eventHandler(ble_evt_t* event)
memcpy(&value, request->data, 2);
_cccd_wr_cb(*this, value);
}
// TODO could move later
// Save CCCD if bonded to file whenever changed
extern void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle);
if ( Bluefruit.connPaired() )
{
ada_callback(NULL, _adafruit_save_bond_cccd_dfr, conn_hdl);
}
}
}
@@ -175,12 +175,12 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
/**
* Hooked callback that triggered when a measurement value is sent from peripheral
* @param chr Reference to client characteristic that even occurred,
* @param chr Pointer client characteristic that even occurred,
* in this example it should be hrmc
* @param data Pointer to received data
* @param len Length of received data
*/
void hrm_notify_callback(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len)
void hrm_notify_callback(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml
// Measurement contains of control byte0 and measurement (8 or 16 bit) + optional field
@@ -0,0 +1,223 @@
/*********************************************************************
This is an example for our nRF52 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
*********************************************************************/
/*
* This sketch demonstrate the central API(). A additional bluefruit
* that has bleuart as peripheral is required for the demo.
*/
#include <bluefruit.h>
// Polling or callback implementation
#define POLLING 1
BLEClientHidAdafruit hid;
// Last checked report, to detect if there is changes between reports
hid_keyboard_report_t last_kbd_report = { 0 };
hid_mouse_report_t last_mse_report = { 0 };
void setup()
{
Serial.begin(115200);
Serial.println("Bluefruit52 Central HID (Keyboard + Mouse) Example");
Serial.println("--------------------------------------------------\n");
// Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
// SRAM usage required by SoftDevice will increase dramatically with number of connections
Bluefruit.begin(0, 1);
Bluefruit.setName("Bluefruit52 Central");
// Init BLE Central Uart Serivce
hid.begin();
#if POLLING == 0
hid.setKeyboardReportCallback(keyboard_report_callback);
#endif
// Increase Blink rate to different from PrPh advertising mode
Bluefruit.setConnLedInterval(250);
// Callbacks for Central
Bluefruit.Central.setConnectCallback(connect_callback);
Bluefruit.Central.setDisconnectCallback(disconnect_callback);
/* Start Central Scanning
* - Enable auto scan if disconnected
* - Interval = 100 ms, window = 80 ms
* - Don't use active scan
* - Start(timeout) with timeout = 0 will scan forever (until connected)
*/
Bluefruit.Scanner.setRxCallback(scan_callback);
Bluefruit.Scanner.restartOnDisconnect(true);
Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms
Bluefruit.Scanner.useActiveScan(false);
Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after n seconds
Bluefruit.Scanner.filterService(hid); // only report HID service
}
/**
* Callback invoked when scanner pick up an advertising data
* @param report Structural advertising data
*/
void scan_callback(ble_gap_evt_adv_report_t* report)
{
// Connect to device
Bluefruit.Central.connect(report);
}
/**
* Callback invoked when an connection is established
* @param conn_handle
*/
void connect_callback(uint16_t conn_handle)
{
Serial.println("Connected");
Serial.print("Discovering HID Service ... ");
if ( hid.discover(conn_handle) )
{
Serial.println("Found it");
// HID device mostly require pairing/bonding
if ( !Bluefruit.Gap.requestPairing(conn_handle) )
{
Serial.print("Failed to paired");
return;
}
// https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.hid_information.xml
uint8_t hidInfo[4];
hid.getHidInfo(hidInfo);
Serial.printf("HID version: %d.%d\n", hidInfo[0], hidInfo[1]);
Serial.print("Country code: "); Serial.println(hidInfo[2]);
Serial.printf("HID Flags : 0x%02X\n", hidInfo[3]);
// BLEClientHidAdafruit currently only suports Boot Protocol Mode
// for Keyboard and Mouse. Let's set the protocol mode on prph to Boot Mode
hid.setProtocolMode(HID_PROTOCOL_MODE_BOOT);
// Enable Keyboard report notification if present on prph
if ( hid.keyboardPresent() ) hid.enableKeyboard();
// Enable Mouse report notification if present on prph
if ( hid.mousePresent() ) hid.enableMouse();
Serial.println("Ready to receive from peripheral");
}else
{
Serial.println("Found NONE");
// disconect since we couldn't find bleuart service
Bluefruit.Central.disconnect(conn_handle);
}
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
}
void loop()
{
#if POLLING == 1
// nothing to do if hid not discovered
if ( !hid.discovered() ) return;
/*------------- Polling Keyboard -------------*/
hid_keyboard_report_t kbd_report;
// Get latest report
hid.getKeyboardReport(&kbd_report);
processKeyboardReport(&kbd_report);
// polling interval is 5 ms
delay(5);
#endif
}
void keyboard_report_callback(hid_keyboard_report_t* report)
{
processKeyboardReport(report);
}
void processKeyboardReport(hid_keyboard_report_t* report)
{
// Check with last report to see if there is any changes
if ( memcmp(&last_kbd_report, report, sizeof(hid_keyboard_report_t)) )
{
bool shifted = false;
if ( report->modifier )
{
if ( report->modifier & (KEYBOARD_MODIFIER_LEFTCTRL | KEYBOARD_MODIFIER_RIGHTCTRL) )
{
Serial.print("Ctrl ");
}
if ( report->modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT) )
{
Serial.print("Shift ");
shifted = true;
}
if ( report->modifier & (KEYBOARD_MODIFIER_LEFTALT | KEYBOARD_MODIFIER_RIGHTALT) )
{
Serial.print("Alt ");
}
}
for(uint8_t i=0; i<6; i++)
{
uint8_t kc = report->keycode[i];
char ch = 0;
if ( kc < 128 )
{
ch = shifted ? HID_KEYCODE_TO_ASCII[kc].shifted : HID_KEYCODE_TO_ASCII[kc].ascii;
}else
{
// non-US keyboard !!??
}
// Printable
if (ch)
{
Serial.print(ch);
}
}
}
// update last report
memcpy(&last_kbd_report, report, sizeof(hid_keyboard_report_t));
}
@@ -0,0 +1,55 @@
/*********************************************************************
This is an example for our nRF52 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
*********************************************************************/
/* This example show how to use Software Serial on Bluefruit nRF52
* to interact with GPS FeatherWing https://www.adafruit.com/product/3133
*
* Hardware Set up
* - Connect 3V and GND to GPS wing
* -
*/
#include <SoftwareSerial.h>
#define SW_RXD A0
#define SW_TXD A1
// Declare an Software Serial instance
SoftwareSerial mySerial(SW_RXD, SW_TXD);
void setup() {
// Init hardware UART <-> Serial Monitor
Serial.begin(115200);
Serial.println("GPS echo test");
// Init Software Uart <-> GPS FeatherWing
mySerial.begin(9600); // default NMEA GPS baud
}
void loop() {
// Pass data from Serial (HW uart) to GPS Wing (SW Uart)
if (Serial.available()) {
char c = Serial.read();
mySerial.write(c);
}
// Pass data from GPS Wing (SW Uart) to Serial (HW uart)
if (mySerial.available()) {
char c = mySerial.read();
Serial.write(c);
}
}
@@ -18,6 +18,7 @@
#include <bluefruit.h>
#include <Nffs.h>
#include <utility/bonding.h>
void setup()
{
@@ -29,13 +30,17 @@ void setup()
Serial.println();
Serial.println("----- Before -----\n");
printDir("/adafruit/bond");
bond_print_list(BLE_GAP_ROLE_PERIPH);
bond_print_list(BLE_GAP_ROLE_CENTRAL);
Bluefruit.clearBonds();
Bluefruit.Central.clearBonds();
Serial.println();
Serial.println("----- After -----\n");
printDir("/adafruit/bond");
bond_print_list(BLE_GAP_ROLE_PERIPH);
bond_print_list(BLE_GAP_ROLE_CENTRAL);
}
void loop()
@@ -46,54 +51,3 @@ void loop()
delay(1000);
}
void printDir(const char* cwd)
{
// Open the input folder
NffsDir dir(cwd);
Serial.println(cwd);
// File Entry Information which hold file attribute and name
NffsDirEntry dirEntry;
// Loop through the directory
while( dir.read(&dirEntry) )
{
// Indentation
Serial.print("|_ ");
char eName[64];
dirEntry.getName(eName, sizeof(eName));
char fullpath[256];
strcpy(fullpath, cwd);
strcat(fullpath, "/");
strcat(fullpath, eName);
Serial.print( eName );
if ( dirEntry.isDirectory() )
{
Serial.println("/");
}else
{
// Print file size starting from position 50
int pos = 3 + strlen(eName);
// Print padding
for (int i=pos; i<50; i++) Serial.print(' ');
// Print at least one extra space in case current position > 50
Serial.print(' ');
NffsFile file(fullpath);
Serial.print( file.size() );
Serial.println( " Bytes");
file.close();
}
}
dir.close();
}
@@ -121,7 +121,7 @@ void setupHRM(void)
// Configure the Heart Rate Measurement characteristic
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml
// Permission = Notify
// Properties = Notify
// Min Len = 1
// Max Len = 8
// B0 = UINT8 - Flag (MANDATORY)
@@ -144,7 +144,7 @@ void setupHRM(void)
// Configure the Body Sensor Location characteristic
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.body_sensor_location.xml
// Permission = Read
// Properties = Read
// Min Len = 1
// Max Len = 1
// B0 = UINT8 - Body Sensor Location
@@ -0,0 +1,106 @@
/**************************************************************************/
/*!
@file IEEE11073float.h
*/
/**************************************************************************/
/**
* \file bytelib.c
* \brief Byte manipulation module implementation.
* Copyright (C) 2010 Signove Tecnologia Corporation.
* All rights reserved.
* Contact: Signove Tecnologia Corporation (contact@signove.com)
*
* $LICENSE_TEXT:BEGIN$
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation and appearing
* in the file LICENSE included in the packaging of this file; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* $LICENSE_TEXT:END$
*
* \author Walter Guerra, Mateus Lima
* \date Jun 14, 2010
*/
#include <Arduino.h>
#include "IEEE11073float.h"
uint32_t float2IEEE11073(double data, uint8_t output[4])
{
uint32_t result = MDER_NaN;
if (isnan(data)) {
goto finally;
}/* else if (data > MDER_FLOAT_MAX) {
result = MDER_POSITIVE_INFINITY;
goto finally;
} else if (data < MDER_FLOAT_MIN) {
result = MDER_NEGATIVE_INFINITY;
goto finally;
} else if (data >= -MDER_FLOAT_EPSILON &&
data <= MDER_FLOAT_EPSILON) {
result = 0;
goto finally;
}*/
double sgn; sgn = data > 0 ? +1 : -1;
double mantissa; mantissa = fabs(data);
int32_t exponent; exponent = 0; // Note: 10**x exponent, not 2**x
// scale up if number is too big
while (mantissa > MDER_FLOAT_MANTISSA_MAX) {
mantissa /= 10.0;
++exponent;
if (exponent > MDER_FLOAT_EXPONENT_MAX) {
// argh, should not happen
if (sgn > 0) {
result = MDER_POSITIVE_INFINITY;
} else {
result = MDER_NEGATIVE_INFINITY;
}
goto finally;
}
}
// scale down if number is too small
while (mantissa < 1) {
mantissa *= 10;
--exponent;
if (exponent < MDER_FLOAT_EXPONENT_MIN) {
// argh, should not happen
result = 0;
goto finally;
}
}
// scale down if number needs more precision
double smantissa; smantissa = round(mantissa * MDER_FLOAT_PRECISION);
double rmantissa; rmantissa = round(mantissa) * MDER_FLOAT_PRECISION;
double mdiff; mdiff = abs(smantissa - rmantissa);
while (mdiff > 0.5 && exponent > MDER_FLOAT_EXPONENT_MIN &&
(mantissa * 10) <= MDER_FLOAT_MANTISSA_MAX) {
mantissa *= 10;
--exponent;
smantissa = round(mantissa * MDER_FLOAT_PRECISION);
rmantissa = round(mantissa) * MDER_FLOAT_PRECISION;
mdiff = abs(smantissa - rmantissa);
}
uint32_t int_mantissa; int_mantissa = (int) round(sgn * mantissa);
result = (exponent << 24) | (int_mantissa & 0xFFFFFF);
finally:
if ( output ) memcpy(output, &result, 4);
return result;
}
@@ -0,0 +1,89 @@
/**************************************************************************/
/*!
@file IEEE11073float.h
*/
/**************************************************************************/
/**
* \file bytelib.c
* \brief Byte manipulation module implementation.
* Copyright (C) 2010 Signove Tecnologia Corporation.
* All rights reserved.
* Contact: Signove Tecnologia Corporation (contact@signove.com)
*
* $LICENSE_TEXT:BEGIN$
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation and appearing
* in the file LICENSE included in the packaging of this file; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* $LICENSE_TEXT:END$
*
* \author Walter Guerra, Mateus Lima
* \date Jun 14, 2010
*/
#ifndef _IEEE11073FLOAT_H_
#define _IEEE11073FLOAT_H_
#include <stdint.h>
typedef enum {
MDER_POSITIVE_INFINITY = 0x007FFFFE,
MDER_NaN = 0x007FFFFF,
MDER_NRes = 0x00800000,
MDER_RESERVED_VALUE = 0x00800001,
MDER_NEGATIVE_INFINITY = 0x00800002
} ReservedFloatValues;
static const int32_t FIRST_RESERVED_VALUE = MDER_POSITIVE_INFINITY;
// (2 ** 23 - 3)
#define MDER_FLOAT_MANTISSA_MAX 0x007FFFFD
// 2 ** 7 - 1
#define MDER_FLOAT_EXPONENT_MAX 127
#define MDER_FLOAT_EXPONENT_MIN -128
// (2 ** 23 - 3) * 10 ** 127
#define MDER_FLOAT_MAX 8.388604999999999e+133
// -(2 ** 23 - 3) * 10 ** 127
#define MDER_FLOAT_MIN (-MDER_FLOAT_MAX)
// 10 ** -128
#define MDER_FLOAT_EPSILON 1e-128
// 10 ** upper(23 * log(2) / log(10))
// precision for a number 1.0000xxx
#define MDER_FLOAT_PRECISION 10000000
typedef enum {
MDER_S_POSITIVE_INFINITY = 0x07FE,
MDER_S_NaN = 0x07FF,
MDER_S_NRes = 0x0800,
MDER_S_RESERVED_VALUE = 0x0801,
MDER_S_NEGATIVE_INFINITY = 0x0802
} ReservedSFloatValues;
static const uint32_t FIRST_S_RESERVED_VALUE = MDER_S_POSITIVE_INFINITY;
// (2 ** 11 - 3)
#define MDER_SFLOAT_MANTISSA_MAX 0x07FD
// 2 ** 3 - 1
#define MDER_SFLOAT_EXPONENT_MAX 7
#define MDER_SFLOAT_EXPONENT_MIN -8
// (2 ** 11 - 3) * 10 ** 7
#define MDER_SFLOAT_MAX 20450000000.0
// -(2 ** 11 - 3) * 10 ** 7
#define MDER_SFLOAT_MIN (-MDER_SFLOAT_MAX)
// 10 ** -8
#define MDER_SFLOAT_EPSILON 1e-8
// 10 ** upper(11 * log(2) / log(10))
#define MDER_SFLOAT_PRECISION 10000
uint32_t float2IEEE11073(double data, uint8_t output[4]);
#endif /* _IEEE11073FLOAT_H_ */
@@ -0,0 +1,211 @@
/*********************************************************************
This is an example for our nRF52 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 <bluefruit.h>
#include "IEEE11073float.h"
/* Health Thermometer Service Definitions
* Health Thermometer Service: 0x1809
* Temperature Measurement Char: 0x2A1C
*/
BLEService htms = BLEService(UUID16_SVC_HEALTH_THERMOMETER);
BLECharacteristic htmc = BLECharacteristic(UUID16_CHR_TEMPERATURE_MEASUREMENT);
BLEDis bledis; // DIS (Device Information Service) helper class instance
double tempvalue = 0;
// Advanced function prototypes
void startAdv(void);
void setupHTM(void);
void connect_callback(uint16_t conn_handle);
void disconnect_callback(uint16_t conn_handle, uint8_t reason);
void setup()
{
Serial.begin(115200);
Serial.println("Bluefruit52 Heath Thermometer Example");
Serial.println("-------------------------------------\n");
// Initialise the Bluefruit module
Serial.println("Initialise the Bluefruit nRF52 module");
Bluefruit.begin();
Bluefruit.setName("Bluefruit52");
// Set the connect/disconnect callback handlers
Bluefruit.setConnectCallback(connect_callback);
Bluefruit.setDisconnectCallback(disconnect_callback);
// Configure and Start the Device Information Service
Serial.println("Configuring the Device Information Service");
bledis.setManufacturer("Adafruit Industries");
bledis.setModel("Bluefruit Feather52");
bledis.begin();;
// Setup the Heath Thermometer service using
// BLEService and BLECharacteristic classes
Serial.println("Configuring the Heath Thermometer Service");
setupHTM();
// Setup the advertising packet(s)
Serial.println("Setting up the advertising payload(s)");
startAdv();
Serial.println("Ready Player One!!!");
Serial.println("\nAdvertising");
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include HTM Service UUID
Bluefruit.Advertising.addService(htms);
// Include Name
Bluefruit.Advertising.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
void setupHTM(void)
{
// Configure the Health Thermometer service
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.service.health_thermometer.xml
// Supported Characteristics:
// Name UUID Requirement Properties
// ---------------------------- ------ ----------- ----------
// Temperature Measurement 0x2A1C Mandatory Indicate
//
// Temperature Type 0x2A1D Optional Read <-- Not used here
// Intermediate Temperature 0x2A1E Optional Read, Notify <-- Not used here
// Measurement Interval 0x2A21 Optional Read, Write, Indicate <-- Not used here
htms.begin();
// Note: You must call .begin() on the BLEService before calling .begin() on
// any characteristic(s) within that service definition.. Calling .begin() on
// a BLECharacteristic will cause it to be added to the last BLEService that
// was 'begin()'ed!
// Configure the Temperature Measurement characteristic
// See:https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_measurement.xml
// Properties = Indicte
// Min Len = 6
// Max Len = 6
// B0 = UINT8 - Flag (MANDATORY)
// b3:7 = Reserved
// b2 = Temperature Type Flag (0 = Not present, 1 = Present)
// b1 = Timestamp Flag (0 = Not present, 1 = Present)
// b0 = Unit Flag (0 = Celsius, 1 = Fahrenheit)
// B4:1 = FLOAT - IEEE-11073 32-bit FLOAT measurement value
// B5 = Temperature Type
htmc.setProperties(CHR_PROPS_INDICATE);
htmc.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS);
htmc.setFixedLen(6);
htmc.setCccdWriteCallback(cccd_callback); // Optionally capture CCCD updates
htmc.begin();
uint8_t htmdata[6] = { 0b00000101, 0, 0 ,0 ,0, 2 }; // Set the characteristic to use Fahrenheit, with type (body) but no timestamp field
htmc.write(htmdata, sizeof(htmdata)); // Use .write for init data
// Temperature Type Value
// See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_type.xml
// B0 = UINT8 - Temperature Type
// 0 = Reserved
// 1 = Armpit
// 2 = Body (general)
// 3 = Ear (usually ear lobe)
// 4 = Finger
// 5 = Gastro-intestinal Tract
// 6 = Mouth
// 7 = Rectum
// 8 = Toe
// 9 = Tympanum (ear drum)
// 10:255 = Reserved
}
void connect_callback(uint16_t conn_handle)
{
char central_name[32] = { 0 };
Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
}
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.println("Advertising!");
}
void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value)
{
// Display the raw request packet
Serial.print("CCCD Updated: ");
//Serial.printBuffer(request->data, request->len);
Serial.print(cccd_value);
Serial.println("");
// Check the characteristic this CCCD update is associated with in case
// this handler is used for multiple CCCD records.
if (chr.uuid == htmc.uuid) {
if (chr.indicateEnabled()) {
Serial.println("Temperature Measurement 'Indicate' enabled");
} else {
Serial.println("Temperature Measurement 'Indicate' disabled");
}
}
}
void loop()
{
digitalToggle(LED_RED);
if ( Bluefruit.connected() ) {
uint8_t htmdata[6] = { 0b00000101, 0,0,0,0, 2 }; // Fahrenheit unit, temperature type = body (2)
float2IEEE11073(tempvalue, &htmdata[1]);
// Note: We use .indicate instead of .write!
// If it is connected but CCCD is not enabled
// The characteristic's value is still updated although notification is not sent
if ( htmc.indicate(htmdata, sizeof(htmdata)) ){
Serial.print("Temperature Measurement updated to: "); Serial.println(tempvalue);
}else{
Serial.println("ERROR: Indicate not set in the CCCD or not connected!");
}
tempvalue += 0.5F;
}
// Only send update once per second
delay(1000);
}
+36 -2
View File
@@ -154,12 +154,17 @@ handles KEYWORD2
write KEYWORD2
notifyEnabled KEYWORD2
notify KEYWORD2
notify8 KEYWORD2
notify16 KEYWORD2
notify32 KEYWORD2
indicateEnabled KEYWORD2
indicate KEYWORD2
indicate8 KEYWORD2
indicate16 KEYWORD2
indicate32 KEYWORD2
#######################################
# BLEClientService Methods (KEYWORD2)
@@ -201,7 +206,7 @@ enableIndicate KEYWORD2
disableIndicate KEYWORD2
setNotifyCallback KEYWORD2
useAdaCallback KEYWORD2
setIndicateCallback KEYWORD2
#######################################
# BLEScanner Methods (KEYWORD2)
@@ -465,6 +470,35 @@ SECMODE_ENC_WITH_MITM LITERAL1
SECMODE_SIGNED_NO_MITM LITERAL1
SECMODE_SIGNED_WITH_MITM LITERAL1
#######################################
# HID Constants
#######################################
HID_PROTOCOL_MODE_BOOT LITERAL1
HID_PROTOCOL_MODE_REPORT LITERAL1
MOUSE_BUTTON_LEFT LITERAL1
MOUSE_BUTTON_RIGHT LITERAL1
MOUSE_BUTTON_MIDDLE LITERAL1
MOUSE_BUTTON_BACKWARD LITERAL1
MOUSE_BUTTON_FORWARD LITERAL1
KEYBOARD_MODIFIER_LEFTCTRL LITERAL1
KEYBOARD_MODIFIER_LEFTSHIFT LITERAL1
KEYBOARD_MODIFIER_LEFTALT LITERAL1
KEYBOARD_MODIFIER_LEFTGUI LITERAL1
KEYBOARD_MODIFIER_RIGHTCTRL LITERAL1
KEYBOARD_MODIFIER_RIGHTSHIFT LITERAL1
KEYBOARD_MODIFIER_RIGHTALT LITERAL1
KEYBOARD_MODIFIER_RIGHTGUI LITERAL1
KEYBOARD_LED_NUMLOCK LITERAL1
KEYBOARD_LED_CAPSLOCK LITERAL1
KEYBOARD_LED_SCROLLLOCK LITERAL1
KEYBOARD_LED_COMPOSE LITERAL1
KEYBOARD_LED_KANA LITERAL1
#######################################
# ANCS Constants
#######################################
@@ -35,6 +35,7 @@
/**************************************************************************/
#include "bluefruit.h"
#include "utility/bonding.h"
/**
* Constructor
@@ -134,6 +135,11 @@ void BLECentral::setDisconnectCallback( BLEGap::disconnect_callback_t fp)
_disconnect_cb = fp;
}
void BLECentral::clearBonds(void)
{
bond_clear_cntr();
}
/**
* Event is forwarded from Bluefruit Poll() method
* @param event
@@ -71,6 +71,8 @@ class BLECentral
bool connected (uint16_t conn_handle); // If connected to a specific peripheral
bool connected (void); // If connected to any peripherals
void clearBonds (void);
/*------------- Callbacks -------------*/
void setConnectCallback ( BLEGap::connect_callback_t fp);
void setDisconnectCallback( BLEGap::disconnect_callback_t fp);
@@ -394,14 +394,6 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event)
memcpy(&value, request->data, 2);
_cccd_wr_cb(*this, value);
}
// TODO could move later
// Save CCCD if bonded to file whenever changed
extern void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle);
if ( Bluefruit.connPaired() )
{
ada_callback(NULL, _adafruit_save_bond_cccd_dfr, event->evt.common_evt.conn_handle);
}
}
}
break;
@@ -496,12 +488,10 @@ uint32_t BLECharacteristic::read32(void)
return read(&num, sizeof(num)) ? num : 0;
}
/*------------------------------------------------------------------*/
/* NOTIFY
*------------------------------------------------------------------*/
bool BLECharacteristic::notifyEnabled(void)
uint16_t BLECharacteristic::getCccd(void)
{
VERIFY( _properties.notify && Bluefruit.connected() );
VERIFY( Bluefruit.connected() && (_handles.cccd_handle != BLE_GATT_HANDLE_INVALID), 0 );
uint16_t cccd;
ble_gatts_value_t value =
@@ -522,7 +512,16 @@ bool BLECharacteristic::notifyEnabled(void)
VERIFY_STATUS(err);
}
return (cccd & BLE_GATT_HVX_NOTIFICATION);
return cccd;
}
/*------------------------------------------------------------------*/
/* NOTIFY
*------------------------------------------------------------------*/
bool BLECharacteristic::notifyEnabled(void)
{
VERIFY( _properties.notify );
return (getCccd() & BLE_GATT_HVX_NOTIFICATION);
}
bool BLECharacteristic::notify(const void* data, uint16_t len)
@@ -557,7 +556,7 @@ bool BLECharacteristic::notify(const void* data, uint16_t len)
VERIFY_STATUS( sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params), false );
remaining -= packet_len;
u8data += packet_len;
u8data += packet_len;
}
}
else
@@ -593,3 +592,83 @@ bool BLECharacteristic::notify32(int num)
{
return notify32( (uint32_t) num);
}
/*------------------------------------------------------------------*/
/* INDICATE
*------------------------------------------------------------------*/
bool BLECharacteristic::indicateEnabled(void)
{
VERIFY( _properties.indicate );
return (getCccd() & BLE_GATT_HVX_INDICATION);
}
bool BLECharacteristic::indicate(const void* data, uint16_t len)
{
VERIFY( _properties.indicate );
// could not exceed max len
uint16_t remaining = min16(len, _max_len);
if ( indicateEnabled() )
{
uint16_t conn_hdl = Bluefruit.connHandle();
uint16_t const max_payload = Bluefruit.Gap.getMTU( conn_hdl ) - 3;
const uint8_t* u8data = (const uint8_t*) data;
while ( remaining )
{
uint16_t packet_len = min16(max_payload, remaining);
ble_gatts_hvx_params_t hvx_params =
{
.handle = _handles.value_handle,
.type = BLE_GATT_HVX_INDICATION,
.offset = 0,
.p_len = &packet_len,
.p_data = (uint8_t*) u8data,
};
LOG_LV2("CHR", "Indicate %d bytes", packet_len);
// Blocking wait until receiving confirmation from peer
VERIFY_STATUS( sd_ble_gatts_hvx( conn_hdl, &hvx_params), false );
VERIFY ( Bluefruit.Gatt.waitForIndicateConfirm(conn_hdl) );
remaining -= packet_len;
u8data += packet_len;
}
}
else
{
write(data, remaining);
return false;
}
return true;
}
bool BLECharacteristic::indicate(const char * str)
{
return indicate( (const uint8_t*) str, strlen(str) );
}
bool BLECharacteristic::indicate8(uint8_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate16(uint16_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate32(uint32_t num)
{
return indicate( (uint8_t*) &num, sizeof(num));
}
bool BLECharacteristic::indicate32(int num)
{
return indicate32( (uint32_t) num);
}
@@ -135,6 +135,8 @@ class BLECharacteristic
uint32_t read32(void);
/*------------- Notify -------------*/
uint16_t getCccd(void);
bool notifyEnabled(void);
bool notify(const void* data, uint16_t len);
@@ -145,6 +147,17 @@ class BLECharacteristic
bool notify32 (uint32_t num);
bool notify32 (int num);
/*------------- Indicate -------------*/
bool indicateEnabled(void);
bool indicate(const void* data, uint16_t len);
bool indicate(const char* str);
bool indicate8 (uint8_t num);
bool indicate16 (uint16_t num);
bool indicate32 (uint32_t num);
bool indicate32 (int num);
/*------------- Internal Functions -------------*/
virtual void _eventHandler(ble_evt_t* event);
@@ -43,7 +43,9 @@ void BLEClientCharacteristic::_init(void)
_cccd_handle = BLE_GATT_HANDLE_INVALID;
_notify_cb = NULL;
_use_AdaCallback = true;
_indicate_cb = NULL;
varclr(&_use_ada_cb);
}
BLEClientCharacteristic::BLEClientCharacteristic(void)
@@ -112,11 +114,6 @@ bool BLEClientCharacteristic::discovered(void)
return _chr.handle_value != BLE_GATT_HANDLE_INVALID;
}
void BLEClientCharacteristic::useAdaCallback(bool enabled)
{
_use_AdaCallback = enabled;
}
uint16_t BLEClientCharacteristic::connHandle(void)
{
return _service->connHandle();
@@ -331,9 +328,16 @@ uint16_t BLEClientCharacteristic::write32(int value)
}
void BLEClientCharacteristic::setNotifyCallback(notify_cb_t fp)
void BLEClientCharacteristic::setNotifyCallback(notify_cb_t fp, bool useAdaCallback)
{
_notify_cb = fp;
_use_ada_cb.notify = useAdaCallback;
}
void BLEClientCharacteristic::setIndicateCallback(indicate_cb_t fp, bool useAdaCallback)
{
_indicate_cb = fp;
_use_ada_cb.indicate = useAdaCallback;
}
bool BLEClientCharacteristic::writeCCCD(uint16_t value)
@@ -384,6 +388,7 @@ bool BLEClientCharacteristic::disableIndicate (void)
void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
{
const uint16_t evt_conn_hdl = evt->evt.common_evt.conn_handle;
uint16_t gatt_status = evt->evt.gattc_evt.gatt_status;
switch(evt->header.evt_id)
@@ -392,26 +397,50 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt)
{
ble_gattc_evt_hvx_t* hvx = &evt->evt.gattc_evt.params.hvx;
if ( hvx->type == BLE_GATT_HVX_NOTIFICATION )
switch ( hvx->type )
{
if (_notify_cb)
{
// use AdaCallback or invoke directly
if (_use_AdaCallback)
case BLE_GATT_HVX_NOTIFICATION:
if (_notify_cb)
{
uint8_t* data = (uint8_t*) rtos_malloc(hvx->len);
if (!data) return;
memcpy(data, hvx->data, hvx->len);
// use AdaCallback or invoke directly
if (_use_ada_cb.notify)
{
uint8_t* data = (uint8_t*) rtos_malloc(hvx->len);
if (!data) return;
memcpy(data, hvx->data, hvx->len);
ada_callback(data, _notify_cb, this, data, hvx->len);
}else
{
_notify_cb(*this, hvx->data, hvx->len);
// data is free by callback
ada_callback(data, _notify_cb, this, data, hvx->len);
}else
{
_notify_cb(this, hvx->data, hvx->len);
}
}
}
}else
{
break;
case BLE_GATT_HVX_INDICATION:
if (_indicate_cb)
{
// use AdaCallback or invoke directly
if (_use_ada_cb.indicate)
{
uint8_t* data = (uint8_t*) rtos_malloc(hvx->len);
if (!data) return;
memcpy(data, hvx->data, hvx->len);
// data is free by callback
ada_callback(data, _indicate_cb, this, data, hvx->len);
}else
{
_indicate_cb(this, hvx->data, hvx->len);
}
// Send confirmation to server
VERIFY_STATUS( sd_ble_gattc_hv_confirm(evt_conn_hdl, hvx->handle), );
}
break;
default : break;
}
}
break;
@@ -47,8 +47,8 @@ class BLEClientCharacteristic
{
public:
/*--------- Callback Signatures ----------*/
typedef void (*notify_cb_t ) (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
typedef void (*indicate_cb_t) (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
typedef void (*notify_cb_t ) (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
typedef void (*indicate_cb_t) (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
BLEUuid uuid;
@@ -100,23 +100,30 @@ class BLEClientCharacteristic
bool disableIndicate (void);
/*------------- Callbacks -------------*/
void setNotifyCallback(notify_cb_t fp);
void useAdaCallback(bool enabled);
void setNotifyCallback(notify_cb_t fp, bool useAdaCallback = true);
void setIndicateCallback(indicate_cb_t fp, bool useAdaCallback = true);
/*------------- Internal usage -------------*/
void _assign(ble_gattc_char_t* gattc_chr);
bool _discoverDescriptor(uint16_t conn_handle, ble_gattc_handle_range_t hdl_range);
private:
ble_gattc_char_t _chr;
uint16_t _cccd_handle;
ble_gattc_char_t _chr;
uint16_t _cccd_handle;
BLEClientService* _service;
notify_cb_t _notify_cb;
bool _use_AdaCallback; // whether callback is invoked in separated task with AdaCallback
AdaMsg _adamsg;
/*------------- Callbacks -------------*/
notify_cb_t _notify_cb;
indicate_cb_t _indicate_cb;
struct ATTR_PACKED {
uint8_t notify : 1;
uint8_t indicate : 1;
} _use_ada_cb;
void _init (void);
void _eventHandler (ble_evt_t* event);
@@ -95,6 +95,12 @@ class BLEDiscovery
return discoverCharacteristic(conn_handle, chr_arr, arrcount(chr_arr));
}
uint8_t discoverCharacteristic(uint16_t conn_handle, BLEClientCharacteristic& chr1, BLEClientCharacteristic& chr2, BLEClientCharacteristic& chr3, BLEClientCharacteristic& chr4, BLEClientCharacteristic& chr5, BLEClientCharacteristic& chr6)
{
BLEClientCharacteristic* chr_arr[] = {&chr1, &chr2, &chr3, &chr4, &chr5, &chr6};
return discoverCharacteristic(conn_handle, chr_arr, arrcount(chr_arr));
}
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal
+227 -33
View File
@@ -50,6 +50,20 @@ BLEGap::BLEGap(void)
_cfg_central.event_len = BLE_GAP_EVENT_LENGTH_DEFAULT;
_cfg_central.hvn_tx_qsize = BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT;
_cfg_central.wr_cmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT;
_sec_param = (ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
};
}
@@ -75,19 +89,19 @@ uint16_t BLEGap::getMaxMtuByConnCfg(uint8_t conn_cfg)
return (conn_cfg == CONN_CFG_PERIPHERAL) ? _cfg_prph.mtu_max : _cfg_central.mtu_max;
}
uint16_t BLEGap::getMaxMtu (uint8_t conn_handle)
uint16_t BLEGap::getMaxMtu (uint8_t conn_hdl)
{
return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.mtu_max : _cfg_central.mtu_max;
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.mtu_max : _cfg_central.mtu_max;
}
uint8_t BLEGap::getHvnQueueSize (uint8_t conn_handle)
uint8_t BLEGap::getHvnQueueSize (uint8_t conn_hdl)
{
return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.hvn_tx_qsize : _cfg_central.hvn_tx_qsize;
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.hvn_tx_qsize : _cfg_central.hvn_tx_qsize;
}
uint8_t BLEGap::getWriteCmdQueueSize (uint8_t conn_handle)
uint8_t BLEGap::getWriteCmdQueueSize (uint8_t conn_hdl)
{
return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.wr_cmd_qsize : _cfg_central.wr_cmd_qsize;
return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.wr_cmd_qsize : _cfg_central.wr_cmd_qsize;
}
@@ -123,48 +137,105 @@ bool BLEGap::setAddr(uint8_t mac[6], uint8_t type)
return true;
}
bool BLEGap::connected(uint16_t conn_handle)
bool BLEGap::connected(uint16_t conn_hdl)
{
return _peers[conn_handle].connected;
return _peers[conn_hdl].connected;
}
uint8_t BLEGap::getRole(uint16_t conn_handle)
bool BLEGap::paired(uint16_t conn_hdl)
{
return _peers[conn_handle].role;
return _peers[conn_hdl].paired;
}
uint8_t BLEGap::getPeerAddr(uint16_t conn_handle, uint8_t addr[6])
bool BLEGap::requestPairing(uint16_t conn_hdl)
{
memcpy(addr, _peers[conn_handle].addr.addr, BLE_GAP_ADDR_LEN);
return _peers[conn_handle].addr.addr_type;
gap_peer_t* peer = &_peers[conn_hdl];
// skip if already paired
if ( peer->paired ) return true;
uint16_t cntr_ediv = 0xFFFF;
if ( peer->role == BLE_GAP_ROLE_CENTRAL )
{
// Check to see if we did bonded with current prph previously
bond_data_t bdata;
if ( bond_find_cntr(&peer->addr, &bdata) )
{
cntr_ediv = bdata.peer_enc.master_id.ediv;
LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, cntr_ediv);
VERIFY_STATUS( sd_ble_gap_encrypt(conn_hdl, &bdata.peer_enc.master_id, &bdata.peer_enc.enc_info), false);
}else
{
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
}
}else
{
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
}
// Wait for pairing process using on-the-fly semaphore
peer->pair_sem = xSemaphoreCreateBinary();
xSemaphoreTake(peer->pair_sem, portMAX_DELAY);
// Failed to pair using centra stored keys, this happens when
// Prph delete bonds while we did not --> let's remove the obsolete keyfile and move on
if ( !peer->paired && (cntr_ediv != 0xffff) )
{
bond_remove_key(BLE_GAP_ROLE_CENTRAL, cntr_ediv);
// Re-try with a fresh session
VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false);
xSemaphoreTake(peer->pair_sem, portMAX_DELAY);
}
vSemaphoreDelete(peer->pair_sem);
peer->pair_sem = NULL;
return peer->paired;
}
ble_gap_addr_t BLEGap::getPeerAddr(uint16_t conn_handle)
uint8_t BLEGap::getRole(uint16_t conn_hdl)
{
return _peers[conn_handle].addr;
return _peers[conn_hdl].role;
}
bool BLEGap::getHvnPacket(uint16_t conn_handle)
uint8_t BLEGap::getPeerAddr(uint16_t conn_hdl, uint8_t addr[6])
{
VERIFY( (conn_handle < BLE_MAX_CONN) && (_peers[conn_handle].hvn_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_handle].hvn_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
memcpy(addr, _peers[conn_hdl].addr.addr, BLE_GAP_ADDR_LEN);
return _peers[conn_hdl].addr.addr_type;
}
bool BLEGap::getWriteCmdPacket(uint16_t conn_handle)
ble_gap_addr_t BLEGap::getPeerAddr(uint16_t conn_hdl)
{
VERIFY( (conn_handle < BLE_MAX_CONN) && (_peers[conn_handle].wrcmd_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_handle].wrcmd_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
return _peers[conn_hdl].addr;
}
uint16_t BLEGap::getMTU (uint16_t conn_handle)
bool BLEGap::getHvnPacket(uint16_t conn_hdl)
{
return _peers[conn_handle].att_mtu;
VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].hvn_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_hdl].hvn_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
uint16_t BLEGap::getPeerName(uint16_t conn_handle, char* buf, uint16_t bufsize)
bool BLEGap::getWriteCmdPacket(uint16_t conn_hdl)
{
return Bluefruit.Gatt.readCharByUuid(conn_handle, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize);
VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].wrcmd_tx_sem != NULL) );
return xSemaphoreTake(_peers[conn_hdl].wrcmd_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT));
}
uint16_t BLEGap::getMTU (uint16_t conn_hdl)
{
return _peers[conn_hdl].att_mtu;
}
uint16_t BLEGap::getPeerName(uint16_t conn_hdl, char* buf, uint16_t bufsize)
{
return Bluefruit.Gatt.readCharByUuid(conn_hdl, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize);
}
/**
@@ -174,9 +245,9 @@ uint16_t BLEGap::getPeerName(uint16_t conn_handle, char* buf, uint16_t bufsize)
void BLEGap::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
const uint16_t conn_handle = evt->evt.common_evt.conn_handle;
const uint16_t conn_hdl = evt->evt.common_evt.conn_handle;
gap_peer_t* peer = &_peers[conn_handle];
gap_peer_t* peer = (conn_hdl == BLE_CONN_HANDLE_INVALID) ? NULL : &_peers[conn_hdl];
switch(evt->header.evt_id)
{
@@ -200,7 +271,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt)
ble_gap_evt_disconnected_t const* para = &evt->evt.gap_evt.params.disconnected;
// mark as disconnected, but keep the role for sub sequence event handler
peer->connected = false;
peer->connected = peer->paired = false;
vSemaphoreDelete( peer->hvn_tx_sem );
peer->hvn_tx_sem = NULL;
@@ -210,6 +281,129 @@ void BLEGap::_eventHandler(ble_evt_t* evt)
}
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress, Peer asking for our info
peer->bond_data = (bond_data_t*) rtos_malloc( sizeof(bond_data_t));
VERIFY(peer->bond_data, );
bond_data_t* bdata = peer->bond_data;
memclr(bdata, sizeof(bond_data_t));
peer->ediv = 0xFFFF; // invalid value for ediv
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
// ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
COMMENT_OUT(
// Change security parameter according to authentication type
if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY)
{
sec_para.mitm = 1;
sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
}
)
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &bdata->own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = NULL
},
.keys_peer = {
.p_enc_key = &bdata->peer_enc,
.p_id_key = &bdata->peer_id,
.p_sign_key = NULL,
.p_pk = NULL
}
};
VERIFY_STATUS(sd_ble_gap_sec_params_reply(conn_hdl,
BLE_GAP_SEC_STATUS_SUCCESS,
peer->role == BLE_GAP_ROLE_PERIPH ? &_sec_param : NULL,
&keyset),
);
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
// Bonding process completed
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
// Pairing succeeded --> save encryption keys ( Bonding )
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
peer->paired = true;
peer->ediv = peer->bond_data->own_enc.master_id.ediv;
bond_save_keys(peer->role, conn_hdl, peer->bond_data);
}else
{
PRINT_HEX(status->auth_status);
}
rtos_free(peer->bond_data);
peer->bond_data = NULL;
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Reconnection. If bonded previously, Central will ask for stored keys.
// return security information. Otherwise NULL
ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
bond_data_t bdata;
varclr(&bdata);
if ( bond_load_keys(peer->role, sec_req->master_id.ediv, &bdata) )
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &bdata.own_enc.enc_info, &bdata.peer_id.id_info, NULL);
peer->ediv = bdata.own_enc.master_id.ediv;
} else
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL);
}
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec;
// Connection is secured (paired)
if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) )
{
// Previously bonded --> secure by re-connection process
// --> Load & Set Sys Attr (Apply Service Context)
// Else Init Sys Attr
bond_load_cccd(peer->role, conn_hdl, peer->ediv);
peer->paired = true;
}
if (peer->pair_sem) xSemaphoreGive(peer->pair_sem);
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
// ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
//
// PRINT_INT(passkey_display->match_request);
// PRINT_BUFFER(passkey_display->passkey, 6);
// sd_ble_gap_auth_key_reply
}
break;
case BLE_GATTS_EVT_HVN_TX_COMPLETE:
if ( peer->hvn_tx_sem )
{
@@ -237,7 +431,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt)
param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us);
// Let Softdevice decide the data length
VERIFY_STATUS( sd_ble_gap_data_length_update(conn_handle, NULL, NULL), );
VERIFY_STATUS( sd_ble_gap_data_length_update(conn_hdl, NULL, NULL), );
}
break;
@@ -260,7 +454,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt)
// Tell SoftDevice to choose PHY automatically
ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO };
(void) sd_ble_gap_phy_update(conn_handle, &phy);
(void) sd_ble_gap_phy_update(conn_hdl, &phy);
}
break;
@@ -283,8 +477,8 @@ void BLEGap::_eventHandler(ble_evt_t* evt)
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
{
peer->att_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, getMaxMtu(conn_handle));
VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(conn_handle, peer->att_mtu), );
peer->att_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, getMaxMtu(conn_hdl));
VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(conn_hdl, peer->att_mtu), );
LOG_LV1("GAP", "ATT MTU is changed to %d", peer->att_mtu);
}
+44 -27
View File
@@ -39,6 +39,7 @@
#include <Arduino.h>
#include "bluefruit_common.h"
#include "BLEUuid.h"
#include "utility/bonding.h"
enum
{
@@ -49,8 +50,8 @@ enum
class BLEGap
{
public:
typedef void (*connect_callback_t ) (uint16_t conn_handle);
typedef void (*disconnect_callback_t ) (uint16_t conn_handle, uint8_t reason);
typedef void (*connect_callback_t ) (uint16_t conn_hdl);
typedef void (*disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason);
BLEGap(void);
@@ -58,23 +59,25 @@ class BLEGap
bool setAddr (uint8_t mac[6], uint8_t type);
// bool setPrivacy (); sd_ble_gap_privacy_set()
bool connected (uint16_t conn_handle);
bool connected (uint16_t conn_hdl);
bool paired (uint16_t conn_hdl);
bool requestPairing (uint16_t conn_hdl);
uint8_t getRole (uint16_t conn_handle);
uint8_t getRole (uint16_t conn_hdl);
uint8_t getPeerAddr (uint16_t conn_handle, uint8_t addr[6]);
ble_gap_addr_t getPeerAddr (uint16_t conn_handle);
uint16_t getPeerName (uint16_t conn_handle, char* buf, uint16_t bufsize);
uint8_t getPeerAddr (uint16_t conn_hdl, uint8_t addr[6]);
ble_gap_addr_t getPeerAddr (uint16_t conn_hdl);
uint16_t getPeerName (uint16_t conn_hdl, char* buf, uint16_t bufsize);
uint16_t getMTU (uint16_t conn_handle);
uint16_t getMaxMtuByConnCfg (uint8_t conn_cfg);
uint16_t getMaxMtu (uint8_t conn_handle);
uint16_t getMTU (uint16_t conn_hdl);
uint16_t getMaxMtuByConnCfg (uint8_t conn_cfg);
uint16_t getMaxMtu (uint8_t conn_hdl);
uint8_t getHvnQueueSize (uint8_t conn_handle);
uint8_t getWriteCmdQueueSize (uint8_t conn_handle);
uint8_t getHvnQueueSize (uint8_t conn_hdl);
uint8_t getWriteCmdQueueSize (uint8_t conn_hdl);
bool getHvnPacket (uint16_t conn_handle);
bool getWriteCmdPacket (uint16_t conn_handle);
bool getHvnPacket (uint16_t conn_hdl);
bool getWriteCmdPacket (uint16_t conn_hdl);
void configPrphConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
void configCentralConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize);
@@ -86,6 +89,31 @@ class BLEGap
*------------------------------------------------------------------*/
void _eventHandler(ble_evt_t* evt);
// Array of TX Packet semaphore, indexed by connection handle
// Peer info where conn_hdl serves as index
typedef struct {
bool connected;
bool paired;
uint8_t role;
uint16_t att_mtu;
ble_gap_addr_t addr;
uint16_t ediv;
bond_data_t* bond_data; // Shared keys with bonded device, size ~ 80 bytes
SemaphoreHandle_t hvn_tx_sem;
SemaphoreHandle_t wrcmd_tx_sem;
bool hvc_received;
// On-demand semaphore that are created on the fly
SemaphoreHandle_t hvc_sem;
SemaphoreHandle_t pair_sem;
} gap_peer_t;
gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; }
private:
struct {
uint16_t mtu_max;
@@ -94,21 +122,10 @@ class BLEGap
uint8_t wr_cmd_qsize;
} _cfg_prph, _cfg_central;
// Array of TX Packet semaphore, indexed by connection handle
// Peer info where conn_handle serves as index
typedef struct {
bool connected;
uint8_t role;
uint16_t att_mtu;
ble_gap_addr_t addr;
SemaphoreHandle_t hvn_tx_sem;
SemaphoreHandle_t wrcmd_tx_sem;
} gap_peer_t;
gap_peer_t _peers[BLE_MAX_CONN];
ble_gap_sec_params_t _sec_param;
friend class AdafruitBluefruit;
};
+70 -14
View File
@@ -35,6 +35,7 @@
/**************************************************************************/
#include "bluefruit.h"
#include "utility/bonding.h"
BLEGatt::BLEGatt(void)
@@ -49,6 +50,12 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe
int32_t count = 0;
ble_gattc_handle_range_t hdl_range = { .start_handle = start_hdl, .end_handle = end_hdl };
while( _adamsg.isWaiting() )
{
// TODO multiple peripherals
delay( Bluefruit.connInterval() );
}
_adamsg.begin(true);
_adamsg.prepare(buffer, bufsize);
@@ -68,13 +75,29 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe
return (count < 0) ? 0 : count;
}
bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl)
{
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(conn_hdl);
// hvi confirm semaphore is created on the fly
peer->hvc_sem = xSemaphoreCreateBinary();
xSemaphoreTake(peer->hvc_sem, portMAX_DELAY);
vSemaphoreDelete(peer->hvc_sem);
peer->hvc_sem = NULL;
return peer->hvc_received;
}
void BLEGatt::_eventHandler(ble_evt_t* evt)
{
// conn handle has fixed offset regardless of event type
const uint16_t evt_conn_hdl = evt->evt.common_evt.conn_handle;
const uint16_t evt_id = evt->header.evt_id;
// Server Service TODO multiple peripherals
/*------------- Server service -------------*/
// TODO multiple peripherals
// if ( evt_conn_hdl == Bluefruit.connHandle() )
{
if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED )
@@ -92,7 +115,7 @@ void BLEGatt::_eventHandler(ble_evt_t* evt)
}
}
// Server Characteristics
/*------------- Server Characteristics -------------*/
// TODO multiple prph connection
if ( evt_conn_hdl == Bluefruit.connHandle() )
{
@@ -106,11 +129,11 @@ void BLEGatt::_eventHandler(ble_evt_t* evt)
case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST:
// Handle has the same offset for read & write request
req_handle = evt->evt.gatts_evt.params.authorize_request.request.read.handle;
break;
break;
case BLE_GATTS_EVT_WRITE:
req_handle = evt->evt.gatts_evt.params.write.handle;
break;
break;
default: break;
}
@@ -119,11 +142,18 @@ void BLEGatt::_eventHandler(ble_evt_t* evt)
if ((req_handle != BLE_GATT_HANDLE_INVALID) && (req_handle == chr->handles().value_handle || req_handle == chr->handles().cccd_handle ))
{
chr->_eventHandler(evt);
// Save CCCD if paired
if ( Bluefruit.connPaired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) )
{
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
bond_save_cccd( peer->role, evt_conn_hdl, peer->ediv);
}
}
}
}
// Client Characteristics
/*------------- Client Characteristics -------------*/
for(int i=0; i<_client.chr_count; i++)
{
if ( evt_conn_hdl == _client.chr_list[i]->connHandle() )
@@ -179,21 +209,47 @@ void BLEGatt::_eventHandler(ble_evt_t* evt)
}
// GATTC Read Characteristic by UUID procedure
if ( evt_id == BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP )
switch ( evt_id )
{
ble_gattc_evt_char_val_by_uuid_read_rsp_t* rd_rsp = &evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp;
if (rd_rsp->count)
case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP:
{
ble_gattc_handle_value_t hdl_value;
ble_gattc_evt_char_val_by_uuid_read_rsp_t* rd_rsp = &evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp;
if ( ERROR_NONE == sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(&evt->evt.gattc_evt, &hdl_value) )
if (rd_rsp->count)
{
_adamsg.feed(hdl_value.p_value, rd_rsp->value_len);
}
ble_gattc_handle_value_t hdl_value;
_adamsg.complete();
if ( ERROR_NONE == sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(&evt->evt.gattc_evt, &hdl_value) )
{
_adamsg.feed(hdl_value.p_value, rd_rsp->value_len);
}
_adamsg.complete();
}
}
case BLE_GATTS_EVT_HVC:
{
LOG_LV2("GATTS", "Confirm received handle = 0x%04X", evt->evt.gatts_evt.params.hvc.handle);
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem);
peer->hvc_received = true;
}
break;
case BLE_GATTS_EVT_TIMEOUT:
{
LOG_LV2("GATTS", "Timeout Source = %d", evt->evt.gatts_evt.params.timeout.src);
BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl);
if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem);
peer->hvc_received = false;
}
break;
default: break;
}
}
+2
View File
@@ -60,6 +60,8 @@ class BLEGatt
uint16_t readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffer, uint16_t bufsize, uint16_t start_hdl = 1, uint16_t end_hdl = 0xffff);
bool waitForIndicateConfirm(uint16_t conn_hdl);
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
* Although declare as public, it is meant to be invoked by internal
@@ -272,6 +272,16 @@ void BLEScanner::filterUuid(BLEUuid ble_uuid[], uint8_t count)
for(uint8_t i=0; i<count; i++) _filter_uuid[i] = ble_uuid[i];
}
void BLEScanner::filterService(BLEService& svc)
{
filterUuid(svc.uuid);
}
void BLEScanner::filterService(BLEClientService& cli)
{
filterUuid(cli.uuid);
}
void BLEScanner::filterMSD(uint16_t manuf_id)
{
_filter_msd_en = true;
@@ -68,6 +68,9 @@ public:
void filterUuid(BLEUuid ble_uuid1, BLEUuid ble_uuid2, BLEUuid ble_uuid3, BLEUuid ble_uuid4);
void filterUuid(BLEUuid ble_uuid[], uint8_t count);
void filterService(BLEService& svc);
void filterService(BLEClientService& cli);
void clearFilters(void);
bool start(uint16_t timeout = 0);
+3
View File
@@ -81,6 +81,7 @@ class BLEUuid
#define UUID16_SVC_BLOOD_PRESSURE 0x1810
#define UUID16_SVC_CURRENT_TIME 0x1805
#define UUID16_SVC_CYCLING_SPEED_AND_CADENCE 0x1816
#define UUID16_SVC_CYCLING_POWER 0x1818
#define UUID16_SVC_LOCATION_AND_NAVIGATION 0x1819
#define UUID16_SVC_DEVICE_INFORMATION 0x180A
#define UUID16_SVC_GLUCOSE 0x1808
@@ -121,6 +122,8 @@ class BLEUuid
#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_CYCLING_POWER_MEASUREMENT 0x2A63
#define UUID16_CHR_CYCLING_POWER_FEATURE 0x2A65
#define UUID16_CHR_DATE_TIME 0x2A08
#define UUID16_CHR_DAY_DATE_TIME 0x2A0A
#define UUID16_CHR_DAY_OF_WEEK 0x2A09
+10 -355
View File
@@ -36,20 +36,14 @@
#include "bluefruit.h"
#include <Nffs.h>
#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS)
#include "utility/bonding.h"
#define CFG_BLE_TX_POWER_LEVEL 0
#define CFG_DEFAULT_NAME "Bluefruit52"
#define CFG_BLE_TASK_STACKSIZE (512*3)
#define CFG_SOC_TASK_STACKSIZE (200)
#define CFG_BOND_NFFS_DIR "/adafruit/bond"
#define BOND_FILENAME CFG_BOND_NFFS_DIR "/%04x"
#define BOND_FILENAME_LEN (sizeof(CFG_BOND_NFFS_DIR) + 10)
AdafruitBluefruit Bluefruit;
/*------------------------------------------------------------------*/
@@ -63,14 +57,6 @@ extern "C"
void adafruit_ble_task(void* arg);
void adafruit_soc_task(void* arg);
void _adafruit_save_bond_key_dfr(uint32_t conn_handle);
#if CFG_DEBUG >= 2
#define printBondDir() Nffs.listDir(CFG_BOND_NFFS_DIR)
#else
#define printBondDir()
#endif
/*------------------------------------------------------------------*/
/* INTERNAL FUNCTION
*------------------------------------------------------------------*/
@@ -123,7 +109,6 @@ AdafruitBluefruit::AdafruitBluefruit(void)
_tx_power = 0;
_conn_hdl = BLE_CONN_HANDLE_INVALID;
_bonded = false;
_ppcp_min_conn = BLE_GAP_CONN_MIN_INTERVAL_DFLT;
_ppcp_max_conn = BLE_GAP_CONN_MAX_INTERVAL_DFLT;
@@ -136,23 +121,6 @@ COMMENT_OUT(
_auth_type = BLE_GAP_AUTH_KEY_TYPE_NONE;
varclr(_pin);
)
varclr(&_bond_data);
_bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv
_sec_param = (ble_gap_sec_params_t)
{
.bond = 1,
.mitm = 0,
.lesc = 0,
.keypress = 0,
.io_caps = BLE_GAP_IO_CAPS_NONE,
.oob = 0,
.min_key_size = 7,
.max_key_size = 16,
.kdist_own = { .enc = 1, .id = 1},
.kdist_peer = { .enc = 1, .id = 1},
};
}
void AdafruitBluefruit::configServiceChanged(bool changed)
@@ -447,9 +415,8 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count)
// Create Timer for led advertising blinky
_led_blink_th = xTimerCreate(NULL, ms2tick(CFG_ADV_BLINKY_INTERVAL/2), true, NULL, bluefruit_blinky_cb);
// Initialize nffs for bonding (it is safe to call nffs_pkg_init() multiple time)
Nffs.begin();
(void) Nffs.mkdir_p(CFG_BOND_NFFS_DIR);
// Initialize bonding
bond_init();
return ERROR_NONE;
}
@@ -580,7 +547,7 @@ uint16_t AdafruitBluefruit::connHandle(void)
bool AdafruitBluefruit::connPaired(void)
{
return _bonded;
return Gap.paired(_conn_hdl);
}
uint16_t AdafruitBluefruit::connInterval(void)
@@ -731,35 +698,13 @@ void AdafruitBluefruit::printInfo(void)
Serial.println();
/*------------- List the paried device -------------*/
Serial.printf(title_fmt, "Paired Devices");
Serial.printf(title_fmt, "Peripheral Paired Devices");
Serial.println();
bond_print_list(BLE_GAP_ROLE_PERIPH);
NffsDir dir(CFG_BOND_NFFS_DIR);
NffsDirEntry dirEntry;
while( dir.read(&dirEntry) )
{
if ( !dirEntry.isDirectory() )
{
char name[64];
dirEntry.getName(name, sizeof(name));
Serial.printf(" %s : ", name);
// open file to read device name
NffsFile file(CFG_BOND_NFFS_DIR, dirEntry, FS_ACCESS_READ);
varclr(name);
file.seek(BOND_FILE_DEVNAME_OFFSET);
if ( file.read(name, CFG_MAX_DEVNAME_LEN) )
{
Serial.println(name);
}
file.close();
}
}
Serial.printf(title_fmt, "Central Paired Devices");
Serial.println();
bond_print_list(BLE_GAP_ROLE_CENTRAL);
Serial.println();
}
@@ -913,116 +858,11 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
break;
case BLE_GAP_EVT_DISCONNECTED:
// Save all configured cccd
if (_bonded) _saveBondCCCD();
if (_disconnect_cb) ada_callback(NULL, _disconnect_cb, _conn_hdl, evt->evt.gap_evt.params.disconnected.reason);
LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason);
_conn_hdl = BLE_CONN_HANDLE_INVALID;
_bonded = false;
break;
case BLE_GAP_EVT_SEC_PARAMS_REQUEST:
{
// Pairing in progress
varclr(&_bond_data);
_bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv
/* Step 1: Pairing/Bonding
* - Central supplies its parameters
* - We replies with our security parameters
*/
// ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params;
COMMENT_OUT(
// Change security parameter according to authentication type
if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY)
{
sec_para.mitm = 1;
sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY;
}
)
ble_gap_sec_keyset_t keyset =
{
.keys_own = {
.p_enc_key = &_bond_data.own_enc,
.p_id_key = NULL,
.p_sign_key = NULL,
.p_pk = NULL
},
.keys_peer = {
.p_enc_key = &_bond_data.peer_enc,
.p_id_key = &_bond_data.peer_id,
.p_sign_key = NULL,
.p_pk = NULL
}
};
VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID);
}
break;
case BLE_GAP_EVT_SEC_INFO_REQUEST:
{
// Reconnection. If bonded previously, Central will ask for stored keys.
// return security information. Otherwise NULL
ble_gap_evt_sec_info_request_t* sec_request = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request;
if ( _loadBondKeys(sec_request->master_id.ediv) )
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_bond_data.own_enc.enc_info, &_bond_data.peer_id.id_info, NULL);
} else
{
sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL);
}
}
break;
case BLE_GAP_EVT_PASSKEY_DISPLAY:
{
// ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display;
//
// PRINT_INT(passkey_display->match_request);
// PRINT_BUFFER(passkey_display->passkey, 6);
// sd_ble_gap_auth_key_reply
}
break;
case BLE_GAP_EVT_CONN_SEC_UPDATE:
{
// Connection is secured aka Paired
COMMENT_OUT( ble_gap_conn_sec_t* conn_sec = (ble_gap_conn_sec_t*) &evt->evt.gap_evt.params.conn_sec_update.conn_sec; )
// Previously bonded --> secure by re-connection process
// --> Load & Set Sys Attr (Apply Service Context)
// Else Init Sys Attr
_loadBondCCCD(_bond_data.own_enc.master_id.ediv);
// Consider Paired as Bonded
_bonded = true;
}
break;
case BLE_GAP_EVT_AUTH_STATUS:
{
// Bonding process completed
ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status;
// Pairing/Bonding succeeded --> save encryption keys
if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status)
{
_bonded = true;
ada_callback(NULL, _adafruit_save_bond_key_dfr, _conn_hdl);
}else
{
PRINT_HEX(status->auth_status);
}
}
break;
case BLE_GATTS_EVT_SYS_ATTR_MISSING:
@@ -1077,196 +917,11 @@ void AdafruitBluefruit::_setConnLed (bool on_off)
*------------------------------------------------------------------*/
bool AdafruitBluefruit::requestPairing(void)
{
// skip if already bonded
if (_bonded) return true;
VERIFY_STATUS( sd_ble_gap_authenticate(_conn_hdl, &_sec_param ), false);
uint32_t start = millis();
// timeout in 30 seconds
while ( !_bonded && (start + 30000 > millis()) )
{
yield();
}
return _bonded;
return Gap.requestPairing(_conn_hdl);
}
void AdafruitBluefruit::clearBonds(void)
{
// Detele bonds dir
Nffs.remove(CFG_BOND_NFFS_DIR);
// Create an empty one
Nffs.mkdir_p(CFG_BOND_NFFS_DIR);
printBondDir();
bond_clear_prph();
}
/*------------------------------------------------------------------*/
/* Saving Bond Data to Nffs in following layout
* - _bond_data 80 bytes
* - Name 32 bytes
* - CCCD variable
*------------------------------------------------------------------*/
void _adafruit_save_bond_key_dfr(uint32_t conn_handle)
{
(void) conn_handle;
Bluefruit._saveBondKeys();
}
void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle)
{
(void) conn_handle;
Bluefruit._saveBondCCCD();
}
void AdafruitBluefruit::_saveBondKeys(void)
{
char filename[BOND_FILENAME_LEN];
sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv);
char devname[CFG_MAX_DEVNAME_LEN] = { 0 };
Gap.getPeerName(_conn_hdl, devname, CFG_MAX_DEVNAME_LEN);
NffsFile file(filename, FS_ACCESS_WRITE);
VERIFY( file.exists(), );
bool result = true;
// write keys
if ( !file.write((uint8_t*)&_bond_data, sizeof(_bond_data)) )
{
result = false;
}
// write device name
if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) )
{
result = false;
}
file.close();
if (result)
{
LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename);
}else
{
LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname);
}
printBondDir();
}
bool AdafruitBluefruit::_loadBondKeys(uint16_t ediv)
{
VERIFY_STATIC(sizeof(_bond_data) == 80 );
char filename[BOND_FILENAME_LEN];
sprintf(filename, BOND_FILENAME, ediv);
bool result = (Nffs.readFile(filename, &_bond_data, sizeof(_bond_data)) > 0);
if ( result )
{
LOG_LV2("BOND", "Load Keys from file %s", filename);
}else
{
LOG_LV1("BOND", "Keys not found");
}
return result;
}
void AdafruitBluefruit::_saveBondCCCD(void)
{
VERIFY( _bond_data.own_enc.master_id.ediv != 0xFFFF, );
uint16_t len=0;
sd_ble_gatts_sys_attr_get(_conn_hdl, NULL, &len, SVC_CONTEXT_FLAG);
uint8_t* sys_attr = (uint8_t*) rtos_malloc( len );
VERIFY( sys_attr, );
if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(_conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) )
{
// save to file
char filename[BOND_FILENAME_LEN];
sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv);
if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) )
{
LOG_LV2("BOND", "CCCD setting is saved to file %s", filename);
}else
{
LOG_LV1("BOND", "Failed to save CCCD setting");
}
}
printBondDir();
rtos_free(sys_attr);
}
void AdafruitBluefruit::_loadBondCCCD(uint16_t ediv)
{
bool loaded = false;
char filename[BOND_FILENAME_LEN];
sprintf(filename, BOND_FILENAME, ediv);
NffsFile file(filename, FS_ACCESS_READ);
if ( file.exists() )
{
int32_t len = file.size() - BOND_FILE_CCCD_OFFSET;
if ( len )
{
uint8_t* sys_attr = (uint8_t*) rtos_malloc( len );
if (sys_attr)
{
file.seek(BOND_FILE_CCCD_OFFSET);
if ( file.read(sys_attr, len ) )
{
if (ERROR_NONE == sd_ble_gatts_sys_attr_set(_conn_hdl, sys_attr, len, SVC_CONTEXT_FLAG) )
{
loaded = true;
LOG_LV2("BOND", "Load CCCD from file %s", filename);
}else
{
LOG_LV1("BOND", "CCCD setting not found");
}
}
rtos_free(sys_attr);
}
}
}
file.close();
if ( !loaded )
{
sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0);
}
}
void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key)
{
if (!_bonded)
{
(*addr) = getPeerAddr();
}else
{
(*addr) = _bond_data.peer_id.id_addr_info;
(*irk) = _bond_data.peer_id.id_info;
(*enc_key) = _bond_data.own_enc;
}
}
+2 -24
View File
@@ -40,7 +40,6 @@
#include "bluefruit_common.h"
#define CFG_ADV_BLINKY_INTERVAL 500
#define CFG_MAX_DEVNAME_LEN 32
/* Note changing these parameters will affect APP_RAM_BASE
* --> need to update RAM region in linker file
@@ -81,8 +80,10 @@
#include "clients/BLEClientUart.h"
#include "clients/BLEClientDis.h"
#include "clients/BLEClientCts.h"
#include "clients/BLEClientHidAdafruit.h"
#include "utility/AdaCallback.h"
#include "utility/bonding.h"
enum
{
@@ -185,10 +186,6 @@ class AdafruitBluefruit
void _startConnLed (void);
void _stopConnLed (void);
void _setConnLed (bool on_off);
void _bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key);
void _saveBondKeys(void);
void _saveBondCCCD(void);
private:
/*------------- SoftDevice Configuration -------------*/
@@ -219,27 +216,10 @@ class AdafruitBluefruit
BLEDfu _dfu_svc;
uint16_t _conn_hdl;
bool _bonded;
BLEGap::connect_callback_t _connect_cb;
BLEGap::disconnect_callback_t _disconnect_cb;
ble_gap_sec_params_t _sec_param;
// Shared keys with bonded device, size = 80 bytes
struct
{
ble_gap_enc_key_t own_enc;
ble_gap_enc_key_t peer_enc;
ble_gap_id_key_t peer_id;
} _bond_data;
enum
{
BOND_FILE_DEVNAME_OFFSET = sizeof(_bond_data),
BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN
};
COMMENT_OUT(
uint8_t _auth_type;
char _pin[BLE_GAP_PASSKEY_LEN];
@@ -248,8 +228,6 @@ COMMENT_OUT(
/*------------------------------------------------------------------*/
/* INTERNAL USAGE ONLY
*------------------------------------------------------------------*/
bool _loadBondKeys(uint16_t ediv);
void _loadBondCCCD(uint16_t ediv);
void _ble_handler(ble_evt_t* evt);
friend void SD_EVT_IRQHandler(void);
@@ -43,6 +43,8 @@
#include "utility/AdaMsg.h"
#define CFG_MAX_DEVNAME_LEN 32
#define BLE_GENERIC_TIMEOUT 100
#define BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS 2000
@@ -40,8 +40,8 @@
#define DEBUG_ANCS 0
void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
void bleancs_data_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
void bleancs_data_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
/* ANCS Service : 7905F431-B5CE-4E99-A40F-4B1E122D00D0
* Control Point : 69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9
@@ -94,10 +94,9 @@ bool BLEAncs::begin(void)
_notification.setNotifyCallback(bleancs_notification_cb);
// Data Attribute is likely requested in notification callback
// Data Attribute is most likely requested in notification callback
// let's call data's callback in the ble task
_data.useAdaCallback(false);
_data.setNotifyCallback(bleancs_data_cb);
_data.setNotifyCallback(bleancs_data_cb, false);
return true;
}
@@ -384,14 +383,14 @@ bool BLEAncs::actNegative(uint32_t uid)
/*------------------------------------------------------------------*/
/* Callback
*------------------------------------------------------------------*/
void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len)
void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEAncs& svc = (BLEAncs&) chr.parentService();
BLEAncs& svc = (BLEAncs&) chr->parentService();
svc._handleNotification(data, len);
}
void bleancs_data_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len)
void bleancs_data_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEAncs& svc = (BLEAncs&) chr.parentService();
BLEAncs& svc = (BLEAncs&) chr->parentService();
svc._handleData(data, len);
}
@@ -177,8 +177,8 @@ class BLEAncs : public BLEClientService
void _handleNotification(uint8_t* data, uint16_t len);
void _handleData(uint8_t* data, uint16_t len);
friend void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
friend void bleancs_data_cb (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
friend void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
friend void bleancs_data_cb (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
};
@@ -36,7 +36,7 @@
#include "bluefruit.h"
void blects_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
void blects_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
BLEClientCts::BLEClientCts(void)
: BLEClientService(UUID16_SVC_CURRENT_TIME), _cur_time(UUID16_CHR_CURRENT_TIME), _local_info(UUID16_CHR_LOCAL_TIME_INFORMATION)
@@ -107,7 +107,7 @@ void BLEClientCts::_cur_time_notify_cb(uint8_t* data, uint16_t len)
if ( _adjust_cb ) _adjust_cb( Time.adjust_reason );
}
void blects_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len)
void blects_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
((BLEClientCts&) chr.parentService())._cur_time_notify_cb(data, len);
((BLEClientCts&) chr->parentService())._cur_time_notify_cb(data, len);
}
@@ -0,0 +1,194 @@
/**************************************************************************/
/*!
@file BLEClientHidAdafruit.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, 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"
BLEClientHidAdafruit::BLEClientHidAdafruit(void)
: BLEClientService(UUID16_SVC_HUMAN_INTERFACE_DEVICE),
_protcol_mode(UUID16_CHR_PROTOCOL_MODE),
_kbd_boot_input(UUID16_CHR_BOOT_KEYBOARD_INPUT_REPORT), _kbd_boot_output(UUID16_CHR_BOOT_KEYBOARD_OUTPUT_REPORT),
_mse_boot_input(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT),
_hid_info(UUID16_CHR_HID_INFORMATION), _hid_control(UUID16_CHR_HID_CONTROL_POINT)
{
_kbd_cb = NULL;
_mse_cb = NULL;
varclr(&_last_kbd_report);
varclr(&_last_mse_report);
}
void kbd_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEClientHidAdafruit& svc = (BLEClientHidAdafruit&) chr->parentService();
svc._handle_kbd_input(data, len);
}
void mse_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEClientHidAdafruit& svc = (BLEClientHidAdafruit&) chr->parentService();
svc._handle_mse_input(data, len);
}
bool BLEClientHidAdafruit::begin(void)
{
// Invoke base class begin()
BLEClientService::begin();
_protcol_mode.begin(this);
_hid_info.begin(this);
_hid_control.begin(this);
_kbd_boot_input.begin(this);
_kbd_boot_output.begin(this);
_mse_boot_input.begin(this);
// set notify callback
_kbd_boot_input.setNotifyCallback(kbd_client_notify_cb);
_mse_boot_input.setNotifyCallback(mse_client_notify_cb);
}
void BLEClientHidAdafruit::setKeyboardReportCallback(kbd_callback_t fp)
{
_kbd_cb = fp;
}
void BLEClientHidAdafruit::setMouseReportCallback(mse_callback_t fp)
{
_mse_cb = fp;
}
bool BLEClientHidAdafruit::discover(uint16_t conn_handle)
{
// Call Base class discover
VERIFY( BLEClientService::discover(conn_handle) );
_conn_hdl = BLE_CONN_HANDLE_INVALID; // make as invalid until we found all chars
// Discover all characteristics
Bluefruit.Discovery.discoverCharacteristic(conn_handle, _protcol_mode, _kbd_boot_input, _kbd_boot_output, _mse_boot_input, _hid_info, _hid_control);
VERIFY( _protcol_mode.discovered() && _hid_info.discovered() && _hid_control.discovered() );
VERIFY ( keyboardPresent() || mousePresent() );
_conn_hdl = conn_handle;
return true;
}
/*------------------------------------------------------------------*/
/* Info
*------------------------------------------------------------------*/
bool BLEClientHidAdafruit::getHidInfo(uint8_t info[4])
{
return 4 == _hid_info.read(info, 4);
}
uint8_t BLEClientHidAdafruit::getCountryCode(void)
{
uint8_t info[4] = { 0 };
getHidInfo(info);
return info[2];
}
bool BLEClientHidAdafruit::setProtocolMode(uint8_t mode)
{
return _protcol_mode.write8(mode);
}
/*------------------------------------------------------------------*/
/* Keyboard
*------------------------------------------------------------------*/
bool BLEClientHidAdafruit::keyboardPresent(void)
{
return _kbd_boot_input.discovered() && _kbd_boot_output.discovered();
}
bool BLEClientHidAdafruit::enableKeyboard(void)
{
_kbd_boot_input.enableNotify();
}
bool BLEClientHidAdafruit::disableKeyboard(void)
{
_kbd_boot_input.disableNotify();
}
void BLEClientHidAdafruit::_handle_kbd_input(uint8_t* data, uint16_t len)
{
varclr(&_last_kbd_report);
memcpy(&_last_kbd_report, data, len);
if ( _kbd_cb ) _kbd_cb(&_last_kbd_report);
}
void BLEClientHidAdafruit::getKeyboardReport(hid_keyboard_report_t* report)
{
memcpy(report, &_last_kbd_report, sizeof(hid_keyboard_report_t));
}
/*------------------------------------------------------------------*/
/* Mouse
*------------------------------------------------------------------*/
bool BLEClientHidAdafruit::mousePresent(void)
{
return _mse_boot_input.discovered();
}
bool BLEClientHidAdafruit::enableMouse(void)
{
_mse_boot_input.enableNotify();
}
bool BLEClientHidAdafruit::disableMouse(void)
{
_mse_boot_input.disableNotify();
}
void BLEClientHidAdafruit::_handle_mse_input(uint8_t* data, uint16_t len)
{
varclr(&_last_mse_report);
memcpy(&_last_mse_report, data, len);
if ( _mse_cb ) _mse_cb(&_last_mse_report);
}
void BLEClientHidAdafruit::getMouseReport(hid_mouse_report_t* report)
{
memcpy(report, &_last_mse_report, sizeof(hid_mouse_report_t));
}
@@ -0,0 +1,107 @@
/**************************************************************************/
/*!
@file BLEClientHidAdafruit.h
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, 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 BLECLIENTHIDADAFRUIT_H_
#define BLECLIENTHIDADAFRUIT_H_
#include "bluefruit_common.h"
#include "BLEClientCharacteristic.h"
#include "BLEClientService.h"
#include "services/BLEHidGeneric.h"
// Only support Boot Keyboard and/or Boot Mouse, there is no Consumer Control support
class BLEClientHidAdafruit : public BLEClientService
{
public:
// Callback Signatures
typedef void (*kbd_callback_t ) (hid_keyboard_report_t* report);
typedef void (*mse_callback_t ) (hid_mouse_report_t* report);
BLEClientHidAdafruit(void);
virtual bool begin(void);
virtual bool discover(uint16_t conn_handle);
bool getHidInfo(uint8_t info[4]);
uint8_t getCountryCode(void);
bool setProtocolMode(uint8_t mode);
// Keyboard API
bool keyboardPresent(void);
bool enableKeyboard(void);
bool disableKeyboard(void);
void getKeyboardReport(hid_keyboard_report_t* report);
// Mouse API
bool mousePresent(void);
bool enableMouse(void);
bool disableMouse(void);
void getMouseReport(hid_mouse_report_t* report);
// Report callback
void setKeyboardReportCallback(kbd_callback_t fp);
void setMouseReportCallback(mse_callback_t fp);
protected:
kbd_callback_t _kbd_cb;
mse_callback_t _mse_cb;
hid_keyboard_report_t _last_kbd_report;
hid_mouse_report_t _last_mse_report;
// Only support Boot protocol for keyboard and Mouse
BLEClientCharacteristic _protcol_mode;
BLEClientCharacteristic _hid_info;
BLEClientCharacteristic _hid_control;
BLEClientCharacteristic _kbd_boot_input;
BLEClientCharacteristic _kbd_boot_output;
BLEClientCharacteristic _mse_boot_input;
void _handle_kbd_input(uint8_t* data, uint16_t len);
void _handle_mse_input(uint8_t* data, uint16_t len);
friend void kbd_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
friend void mse_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
};
#endif /* BLECLIENTHIDADAFRUIT_H_ */
@@ -36,7 +36,7 @@
#include "bluefruit.h"
void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
BLEClientUart::BLEClientUart(uint16_t fifo_depth)
: BLEClientService(BLEUART_UUID_SERVICE), _txd(BLEUART_UUID_CHR_TXD), _rxd(BLEUART_UUID_CHR_RXD),
@@ -96,9 +96,9 @@ void BLEClientUart::disconnect(void)
flush();
}
void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len)
void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len)
{
BLEClientUart& uart_svc = (BLEClientUart&) chr.parentService();
BLEClientUart& uart_svc = (BLEClientUart&) chr->parentService();
uart_svc._rx_fifo.write(data, len);
// invoke callback
@@ -83,7 +83,7 @@ class BLEClientUart : public BLEClientService, public Stream
Adafruit_FIFO _rx_fifo;
rx_callback_t _rx_cb;
friend void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len);
friend void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len);
};
#endif /* BLECLIENTUART_H_ */
@@ -92,17 +92,19 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt
(request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) &&
(request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL))
{
uint16_t conn_hdl = Bluefruit.connHandle();
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);
sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply);
return;
}
reply.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS;
sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply);
sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply);
enum { START_DFU = 1 };
if ( request->data[0] == START_DFU )
@@ -128,10 +130,22 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt
// Get CCCD
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);
sd_ble_gatts_sys_attr_get(conn_hdl, peer_data->sys_attr, &sysattr_len, BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS);
// Get Bond Data
Bluefruit._bledfu_get_bond_data(&peer_data->addr, &peer_data->irk, &peer_data->enc_key);
// Get Bond Data or using Address if not bonded
peer_data->addr = Bluefruit.Gap.getPeerAddr(conn_hdl);
if ( Bluefruit.Gap.paired(conn_hdl) )
{
bond_data_t bdata;
if ( bond_load_keys( BLE_GAP_ROLE_PERIPH, Bluefruit.Gap._get_peer(conn_hdl)->ediv, &bdata ) )
{
peer_data->addr = bdata.peer_id.id_addr_info;
peer_data->irk = bdata.peer_id.id_info;
peer_data->enc_key = bdata.own_enc;
}
}
// Calculate crc
peer_data->crc16 = crc16((uint8_t*) peer_data, offsetof(peer_data_t, crc16));
@@ -205,7 +205,8 @@ err_t BLEHidAdafruit::begin(void)
uint16_t output_len[] = { 1 };
setReportLen(input_len, output_len, NULL);
enableBootProtocol(true, true);
enableKeyboard(true);
enableMouse(true);
setReportMap(hid_report_descriptor, sizeof(hid_report_descriptor));
VERIFY_STATUS( BLEHidGeneric::begin() );
@@ -221,7 +222,13 @@ err_t BLEHidAdafruit::begin(void)
*------------------------------------------------------------------*/
bool BLEHidAdafruit::keyboardReport(hid_keyboard_report_t* report)
{
return inputReport( REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t));
if ( isBootMode() )
{
return bootKeyboardReport(report, sizeof(hid_keyboard_report_t));
}else
{
return inputReport( REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t));
}
}
bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode[6])
@@ -313,7 +320,13 @@ bool BLEHidAdafruit::consumerKeyRelease(void)
*------------------------------------------------------------------*/
bool BLEHidAdafruit::mouseReport(hid_mouse_report_t* report)
{
return inputReport( REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t));
if ( isBootMode() )
{
return bootMouseReport(report, sizeof(hid_mouse_report_t));
}else
{
return inputReport( REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t));
}
}
bool BLEHidAdafruit::mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan)
@@ -45,7 +45,9 @@ enum {
BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_feature)
: BLEService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _chr_control(UUID16_CHR_HID_CONTROL_POINT)
{
_boot_keyboard = _boot_mouse = false;
_has_keyboard = _has_mouse = false;
_protocol_mode = HID_PROTOCOL_MODE_REPORT;
_report_map = NULL;
_report_map_len = 0;
@@ -88,10 +90,17 @@ BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_
}
}
void BLEHidGeneric::enableBootProtocol(bool bootKeyboard, bool bootMouse)
/*------------------------------------------------------------------*/
/* CONFIG
*------------------------------------------------------------------*/
void BLEHidGeneric::enableKeyboard(bool enable)
{
_boot_keyboard = bootKeyboard;
_boot_mouse = bootMouse;
_has_keyboard = enable;
}
void BLEHidGeneric::enableMouse(bool enable)
{
_has_mouse = enable;
}
void BLEHidGeneric::setHidInfo(uint16_t bcd, uint8_t country, uint8_t flags)
@@ -119,6 +128,10 @@ void BLEHidGeneric::setOutputReportCallback(uint8_t reportID, output_report_cb_t
_output_cbs[reportID] = fp;
}
/*------------------------------------------------------------------*/
/* Callbacks
*------------------------------------------------------------------*/
// TODO output report
COMMENT_OUT (
void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request)
{
@@ -129,6 +142,17 @@ void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* requ
}
)
void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset)
{
BLEHidGeneric& svc = (BLEHidGeneric&) chr.parentService();
svc._protocol_mode = *data;
LOG_LV2("HID", "Protocol Mode : %d (0 Boot, 1 Report)", *data);
}
/*------------------------------------------------------------------*/
/* Begin
*------------------------------------------------------------------*/
err_t BLEHidGeneric::begin(void)
{
VERIFY ( (_report_map != NULL) && _report_map_len, NRF_ERROR_INVALID_PARAM);
@@ -137,15 +161,16 @@ err_t BLEHidGeneric::begin(void)
VERIFY_STATUS( BLEService::begin() );
// Protocol Mode
if ( _boot_keyboard || _boot_mouse )
if ( _has_keyboard || _has_mouse )
{
_chr_protocol = new BLECharacteristic(UUID16_CHR_PROTOCOL_MODE);
VERIFY(_chr_protocol, NRF_ERROR_NO_MEM);
_chr_protocol->setProperties(CHR_PROPS_READ | CHR_PROPS_WRITE_WO_RESP);
_chr_protocol->setFixedLen(1);
_chr_protocol->setWriteCallback(blehid_generic_protocol_mode_cb);
VERIFY_STATUS( _chr_protocol->begin() );
_chr_protocol->write8(1);
_chr_protocol->write8(_protocol_mode);
}
// Input reports
@@ -192,7 +217,7 @@ err_t BLEHidGeneric::begin(void)
report_map.write(_report_map, _report_map_len);
// Boot Keyboard Input & Output Report
if ( _boot_keyboard )
if ( _has_keyboard )
{
_chr_boot_keyboard_input = new BLECharacteristic(UUID16_CHR_BOOT_KEYBOARD_INPUT_REPORT);
_chr_boot_keyboard_input->setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY);
@@ -209,7 +234,7 @@ err_t BLEHidGeneric::begin(void)
}
// Boot Mouse Input Report
if ( _boot_mouse )
if ( _has_mouse )
{
_chr_boot_mouse_input = new BLECharacteristic(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT);
_chr_boot_mouse_input->setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY);
@@ -232,11 +257,14 @@ err_t BLEHidGeneric::begin(void)
_chr_control.setPermission(SECMODE_NO_ACCESS, SECMODE_ENC_NO_MITM);
_chr_control.setFixedLen(1);
VERIFY_STATUS( _chr_control.begin() );
_chr_control.write( (uint8_t) 0 );
_chr_control.write8(0);
return ERROR_NONE;
}
/*------------------------------------------------------------------*/
/* Input Report
*------------------------------------------------------------------*/
bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len)
{
// 0 will treated as report ID = 1
@@ -245,8 +273,18 @@ bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len)
return _chr_inputs[reportID-1].notify( (uint8_t const*) data, len);
}
bool BLEHidGeneric::bootKeyboardReport(void const* data, int len)
{
return _chr_boot_keyboard_input->notify(data, len);
}
bool BLEHidGeneric::bootMouseReport(void const* data, int len)
{
return _chr_boot_mouse_input->notify(data, len);
}
/*------------------------------------------------------------------*/
/*
/* Ascii to Keycode
*------------------------------------------------------------------*/
const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] =
{
@@ -383,3 +421,112 @@ const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] =
{0, HID_KEY_DELETE } // 0x7F Delete
};
/*------------------------------------------------------------------*/
/* Keycode to Ascii
*------------------------------------------------------------------*/
const hid_keycode_to_ascii_t HID_KEYCODE_TO_ASCII[128] =
{
{0 , 0 }, // 0x00
{0 , 0 }, // 0x01
{0 , 0 }, // 0x02
{0 , 0 }, // 0x03
{'a' , 'A' }, // 0x04
{'b' , 'B' }, // 0x05
{'c' , 'C' }, // 0x06
{'d' , 'D' }, // 0x07
{'e' , 'E' }, // 0x08
{'f' , 'F' }, // 0x09
{'g' , 'G' }, // 0x0a
{'h' , 'H' }, // 0x0b
{'i' , 'I' }, // 0x0c
{'j' , 'J' }, // 0x0d
{'k' , 'K' }, // 0x0e
{'l' , 'L' }, // 0x0f
{'m' , 'M' }, // 0x10
{'n' , 'N' }, // 0x11
{'o' , 'O' }, // 0x12
{'p' , 'P' }, // 0x13
{'q' , 'Q' }, // 0x14
{'r' , 'R' }, // 0x15
{'s' , 'S' }, // 0x16
{'t' , 'T' }, // 0x17
{'u' , 'U' }, // 0x18
{'v' , 'V' }, // 0x19
{'w' , 'W' }, // 0x1a
{'x' , 'X' }, // 0x1b
{'y' , 'Y' }, // 0x1c
{'z' , 'Z' }, // 0x1d
{'1' , '!' }, // 0x1e
{'2' , '@' }, // 0x1f
{'3' , '#' }, // 0x20
{'4' , '$' }, // 0x21
{'5' , '%' }, // 0x22
{'6' , '^' }, // 0x23
{'7' , '&' }, // 0x24
{'8' , '*' }, // 0x25
{'9' , '(' }, // 0x26
{'0' , ')' }, // 0x27
{'\r' , '\r' }, // 0x28
{'\x1b', '\x1b' }, // 0x29
{'\b' , '\b' }, // 0x2a
{'\t' , '\t' }, // 0x2b
{' ' , ' ' }, // 0x2c
{'-' , '_' }, // 0x2d
{'=' , '+' }, // 0x2e
{'[' , '{' }, // 0x2f
{']' , '}' }, // 0x30
{'\\' , '|' }, // 0x31
{'#' , '~' }, // 0x32
{';' , ':' }, // 0x33
{'\'' , '\"' }, // 0x34
{0 , 0 }, // 0x35
{',' , '<' }, // 0x36
{'.' , '>' }, // 0x37
{'/' , '?' }, // 0x38
{0 , 0 }, // 0x39
{0 , 0 }, // 0x3a
{0 , 0 }, // 0x3b
{0 , 0 }, // 0x3c
{0 , 0 }, // 0x3d
{0 , 0 }, // 0x3e
{0 , 0 }, // 0x3f
{0 , 0 }, // 0x40
{0 , 0 }, // 0x41
{0 , 0 }, // 0x42
{0 , 0 }, // 0x43
{0 , 0 }, // 0x44
{0 , 0 }, // 0x45
{0 , 0 }, // 0x46
{0 , 0 }, // 0x47
{0 , 0 }, // 0x48
{0 , 0 }, // 0x49
{0 , 0 }, // 0x4a
{0 , 0 }, // 0x4b
{0 , 0 }, // 0x4c
{0 , 0 }, // 0x4d
{0 , 0 }, // 0x4e
{0 , 0 }, // 0x4f
{0 , 0 }, // 0x50
{0 , 0 }, // 0x51
{0 , 0 }, // 0x52
{0 , 0 }, // 0x53
{'/' , '/' }, // 0x54
{'*' , '*' }, // 0x55
{'-' , '-' }, // 0x56
{'+' , '+' }, // 0x57
{'\r' , '\r' }, // 0x58
{'1' , 0 }, // 0x59 /* numpad1 & end */ \
{'2' , 0 }, // 0x5a
{'3' , 0 }, // 0x5b
{'4' , 0 }, // 0x5c
{'5' , '5' }, // 0x5d
{'6' , 0 }, // 0x5e
{'7' , 0 }, // 0x5f
{'8' , 0 }, // 0x60
{'9' , 0 }, // 0x61
{'0' , 0 }, // 0x62
{'0' , 0 }, // 0x63
{'=' , '=' }, // 0x67
};
@@ -41,12 +41,24 @@
#include "BLECharacteristic.h"
#include "BLEService.h"
enum
{
HID_PROTOCOL_MODE_BOOT = 0,
HID_PROTOCOL_MODE_REPORT = 1
};
typedef struct{
uint8_t shift;
uint8_t keycode;
}hid_ascii_to_keycode_entry_t;
extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128];
typedef struct{
uint8_t ascii;
uint8_t shifted;
}hid_keycode_to_ascii_t;
extern hid_keycode_to_ascii_t const HID_KEYCODE_TO_ASCII[128];
/// Standard HID Boot Protocol Mouse Report.
typedef ATTR_PACKED_STRUCT(struct)
{
@@ -91,7 +103,9 @@ class BLEHidGeneric : public BLEService
BLEHidGeneric(uint8_t num_input, uint8_t num_output = 0, uint8_t num_feature = 0);
void enableBootProtocol(bool bootKeyboard, bool bootMouse);
void enableKeyboard(bool enable);
void enableMouse(bool enable);
void setHidInfo(uint16_t bcd, uint8_t country, uint8_t flags);
void setReportLen(uint16_t input_len[], uint16_t output_len[] = NULL, uint16_t feature_len[] = NULL);
@@ -101,15 +115,21 @@ class BLEHidGeneric : public BLEService
virtual err_t begin(void);
bool isBootMode(void) { return _protocol_mode == HID_PROTOCOL_MODE_BOOT; }
// Report
bool inputReport(uint8_t reportID, void const* data, int len);
bool bootKeyboardReport(void const* data, int len);
bool bootMouseReport(void const* data, int len);
protected:
uint8_t _num_input;
uint8_t _num_output;
uint8_t _num_feature;
bool _boot_keyboard;
bool _boot_mouse;
bool _has_keyboard;
bool _has_mouse;
bool _protocol_mode;
uint8_t _hid_info[4];
const uint8_t* _report_map;
@@ -133,6 +153,8 @@ class BLEHidGeneric : public BLEService
BLECharacteristic _chr_control;
friend void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset);
COMMENT_OUT (
friend void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request);
)
@@ -36,15 +36,21 @@
#include "AdaMsg.h"
AdaMsg::AdaMsg(void)
void AdaMsg::_init(void)
{
_dynamic = true;
_waiting = false;
_sem = NULL;
buffer = NULL;
remaining = xferlen = 0;
}
AdaMsg::AdaMsg(void)
{
_init();
}
// dynamic mean semaphore is malloced and freed only when in action
void AdaMsg::begin(bool dynamic)
{
@@ -58,6 +64,7 @@ void AdaMsg::begin(bool dynamic)
void AdaMsg::stop(void)
{
if (!_dynamic) vSemaphoreDelete(_sem);
_init();
}
void AdaMsg::prepare(void* buf, uint16_t bufsize)
@@ -82,10 +89,12 @@ int32_t AdaMsg::waitUntilComplete(uint32_t ms)
int result = -1;
_waiting = true;
if ( xSemaphoreTake(_sem, ms2tick(ms) ) )
{
result = xferlen;
}
_waiting = false;
if (_dynamic)
{
@@ -96,6 +105,11 @@ int32_t AdaMsg::waitUntilComplete(uint32_t ms)
return result;
}
bool AdaMsg::isWaiting(void)
{
return _waiting;
}
uint16_t AdaMsg::feed(void* data, uint16_t len)
{
len = min16(len, remaining);
@@ -42,8 +42,11 @@ class AdaMsg
{
private:
bool _dynamic;
volatile bool _waiting;
SemaphoreHandle_t _sem;
void _init(void);
public:
uint8_t* buffer;
uint16_t remaining;
@@ -57,6 +60,7 @@ class AdaMsg
void prepare(void* buf, uint16_t bufsize);
int32_t waitUntilComplete(uint32_t ms);
bool isWaiting(void);
uint16_t feed(void* data, uint16_t len);
void complete(void);
@@ -0,0 +1,339 @@
/**************************************************************************/
/*!
@file bonding.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, 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 <Arduino.h>
#include <Nffs.h>
#include "bonding.h"
#include "bluefruit.h"
#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS)
#if CFG_DEBUG >= 2
#define printBondDir(role) dbgPrintDir( role == BLE_GAP_ROLE_PERIPH ? BOND_DIR_PRPH : BOND_DIR_CNTR )
#else
#define printBondDir(role)
#endif
static void get_fname(char* fname, uint8_t role, uint16_t ediv)
{
sprintf(fname, ( role == BLE_GAP_ROLE_PERIPH ) ? BOND_FNAME_PRPH : BOND_FNAME_CNTR, ediv);
}
/*------------------------------------------------------------------*/
/* Saving Bond Data to Nffs in following layout
* - _bond_data 80 bytes
* - Name 32 bytes
* - CCCD variable
*------------------------------------------------------------------*/
void bond_init(void)
{
// Initialize nffs for bonding (it is safe to call nffs_pkg_init() multiple time)
Nffs.begin();
(void) Nffs.mkdir_p(BOND_DIR_PRPH);
(void) Nffs.mkdir_p(BOND_DIR_CNTR);
}
/*------------------------------------------------------------------*/
/* Keys
*------------------------------------------------------------------*/
static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata)
{
char filename[BOND_FNAME_LEN];
get_fname(filename, role, role == BLE_GAP_ROLE_PERIPH ? bdata->own_enc.master_id.ediv : bdata->peer_enc.master_id.ediv);
char devname[CFG_MAX_DEVNAME_LEN] = { 0 };
Bluefruit.Gap.getPeerName(conn_hdl, devname, CFG_MAX_DEVNAME_LEN);
NffsFile file(filename, FS_ACCESS_WRITE);
VERIFY( file.exists(), );
bool result = true;
// write keys
if ( !file.write((uint8_t*)bdata, sizeof(bond_data_t)) )
{
result = false;
}
// If couldn't get devname use peer mac address
if ( !strlen(devname) )
{
uint8_t* mac = bdata->peer_id.id_addr_info.addr;
sprintf(devname, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
}
file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN);
file.close();
if (result)
{
LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename);
}else
{
LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname);
}
printBondDir(role);
}
void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata)
{
uint8_t* buf = (uint8_t*) rtos_malloc( sizeof(bond_data_t) );
VERIFY(buf, );
memcpy(buf, bdata, sizeof(bond_data_t));
// queue to execute in Ada Callback thread
ada_callback(buf, bond_save_keys_dfr, role, conn_hdl, buf);
}
bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata)
{
char filename[BOND_FNAME_LEN];
get_fname(filename, role, ediv);
bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0);
if ( result )
{
LOG_LV2("BOND", "Load Keys from file %s", filename);
}else
{
LOG_LV1("BOND", "Keys not found");
}
return result;
}
/*------------------------------------------------------------------*/
/* CCCD
*------------------------------------------------------------------*/
static void bond_save_cccd_dfr (uint8_t role, uint16_t conn_hdl, uint16_t ediv)
{
uint16_t len=0;
sd_ble_gatts_sys_attr_get(conn_hdl, NULL, &len, SVC_CONTEXT_FLAG);
uint8_t* sys_attr = (uint8_t*) rtos_malloc( len );
VERIFY( sys_attr, );
if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) )
{
// save to file
char filename[BOND_FNAME_LEN];
get_fname(filename, role, ediv);
if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) )
{
LOG_LV2("BOND", "CCCD setting is saved to file %s", filename);
}else
{
LOG_LV1("BOND", "Failed to save CCCD setting");
}
}
rtos_free(sys_attr);
printBondDir(role);
}
void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv)
{
VERIFY( ediv != 0xFFFF, );
// queue to execute in Ada Callback thread
ada_callback(NULL, bond_save_cccd_dfr, role, cond_hdl, ediv);
}
bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv)
{
bool loaded = false;
char filename[BOND_FNAME_LEN];
get_fname(filename, role, ediv);
NffsFile file(filename, FS_ACCESS_READ);
if ( file.exists() )
{
int32_t len = file.size() - BOND_FILE_CCCD_OFFSET;
if ( len )
{
uint8_t* sys_attr = (uint8_t*) rtos_malloc( len );
if (sys_attr)
{
file.seek(BOND_FILE_CCCD_OFFSET);
if ( file.read(sys_attr, len ) )
{
if (ERROR_NONE == sd_ble_gatts_sys_attr_set(cond_hdl, sys_attr, len, SVC_CONTEXT_FLAG) )
{
loaded = true;
LOG_LV2("BOND", "Load CCCD from file %s", filename);
}else
{
LOG_LV1("BOND", "CCCD setting not found");
}
}
rtos_free(sys_attr);
}
}
}
file.close();
if ( !loaded )
{
sd_ble_gatts_sys_attr_set(cond_hdl, NULL, 0, 0);
}
return loaded;
}
void bond_print_list(uint8_t role)
{
const char* dpath = (role == BLE_GAP_ROLE_PERIPH ? BOND_DIR_PRPH : BOND_DIR_CNTR);
NffsDir dir(dpath);
NffsDirEntry dirEntry;
while( dir.read(&dirEntry) )
{
if ( !dirEntry.isDirectory() )
{
char name[64];
dirEntry.getName(name, sizeof(name));
cprintf(" %s : ", name);
// open file to read device name
NffsFile file(dpath, dirEntry, FS_ACCESS_READ);
varclr(name);
file.seek(BOND_FILE_DEVNAME_OFFSET);
if ( file.read(name, CFG_MAX_DEVNAME_LEN) )
{
cprintf(name);
}
cprintf("\n");
file.close();
}
}
cprintf("\n");
}
bool bond_find_cntr(ble_gap_addr_t* addr, bond_data_t* bdata)
{
bool found = false;
NffsDir dir(BOND_DIR_CNTR);
NffsDirEntry dirEntry;
while( dir.read(&dirEntry) && !found )
{
// Read bond data of each stored file
if ( !dirEntry.isDirectory() )
{
NffsFile file(BOND_DIR_CNTR, dirEntry, FS_ACCESS_READ);
if ( file.read( (uint8_t*)bdata, sizeof(bond_data_t)) )
{
if ( !memcmp(addr->addr, bdata->peer_id.id_addr_info.addr, 6) )
{
// Compare static address
found = true;
}else if ( addr->addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE )
{
// Resolving private address
}
}
file.close();
}
}
return found;
}
/*------------------------------------------------------------------*/
/* DELETE
*------------------------------------------------------------------*/
void bond_clear_prph(void)
{
// Detele bonds dir
Nffs.remove(BOND_DIR_PRPH);
// Create an empty one
(void) Nffs.mkdir_p(BOND_DIR_PRPH);
}
void bond_clear_cntr(void)
{
// Detele bonds dir
Nffs.remove(BOND_DIR_CNTR);
// Create an empty one
(void) Nffs.mkdir_p(BOND_DIR_CNTR);
}
void bond_clear_all(void)
{
// Detele bonds dir
Nffs.remove(BOND_DIR_ROOT);
// Create an empty one for prph and central
(void) Nffs.mkdir_p(BOND_DIR_PRPH);
(void) Nffs.mkdir_p(BOND_DIR_CNTR);
}
void bond_remove_key(uint8_t role, uint16_t ediv)
{
char filename[BOND_FNAME_LEN];
get_fname(filename, role, ediv);
Nffs.remove(filename);
}
@@ -0,0 +1,83 @@
/**************************************************************************/
/*!
@file bonding.h
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, 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 BONDING_H_
#define BONDING_H_
#include "bluefruit_common.h"
#define BOND_DIR_ROOT "/adafruit/bond"
#define BOND_DIR_PRPH BOND_DIR_ROOT "/prph"
#define BOND_DIR_CNTR BOND_DIR_ROOT "/cntr"
#define BOND_FNAME_PRPH BOND_DIR_PRPH "/%04x"
#define BOND_FNAME_CNTR BOND_DIR_CNTR "/%04x"
#define BOND_FNAME_LEN max(sizeof(BOND_FNAME_PRPH), sizeof(BOND_FNAME_CNTR))
// Shared keys with bonded device, size = 80 bytes
typedef struct
{
ble_gap_enc_key_t own_enc;
ble_gap_enc_key_t peer_enc;
ble_gap_id_key_t peer_id;
} bond_data_t;
enum
{
BOND_FILE_DEVNAME_OFFSET = sizeof(bond_data_t),
BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN
};
void bond_init(void);
void bond_clear_prph(void);
void bond_clear_cntr(void);
void bond_clear_all(void);
void bond_remove_key(uint8_t role, uint16_t ediv);
void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata);
bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata);
void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv);
bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv);
void bond_print_list(uint8_t role);
bool bond_find_cntr(ble_gap_addr_t* addr, bond_data_t* bdata);
#endif /* BONDING_H_ */
+3 -1
View File
@@ -214,7 +214,9 @@ uint8_t TwoWire::endTransmission(bool stopBit)
while(!_p_twim->EVENTS_TXSTARTED && !_p_twim->EVENTS_ERROR);
_p_twim->EVENTS_TXSTARTED = 0x0UL;
while(!_p_twim->EVENTS_LASTTX && !_p_twim->EVENTS_ERROR);
if (txBuffer.available()) {
while(!_p_twim->EVENTS_LASTTX && !_p_twim->EVENTS_ERROR);
}
_p_twim->EVENTS_LASTTX = 0x0UL;
if (stopBit || _p_twim->EVENTS_ERROR)