From 3a298a54931ceff157ae25c7bdf4f761c8e15aa6 Mon Sep 17 00:00:00 2001 From: microbuilder Date: Tue, 1 Aug 2017 00:26:34 +0200 Subject: [PATCH 1/2] First commit of RSSI proximity project --- .../Projects/rssi_proximity/README.md | 24 + .../rssi_proximity_central.ino | 534 ++++++++++++++++++ .../rssi_proximity_peripheral.ino | 157 +++++ 3 files changed, 715 insertions(+) create mode 100644 libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/README.md create mode 100644 libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino create mode 100644 libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_peripheral/rssi_proximity_peripheral.ino diff --git a/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/README.md b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/README.md new file mode 100644 index 00000000..f6edc00b --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/README.md @@ -0,0 +1,24 @@ +# RSSI Proximity Project + +This project demonstrates how you can use a single Bluefruit nRF52 device +running in Central mode to listen for a specific signature in the advertising +packets of nearby Bluefruit nRF52 devices running in peripheral mode. + +The Central mode device will sort those devices with the matching signature by +proximity based on their RSSI (relative signal strength) value. + +Most of the Central mode advertising API is used in this demo, making it an +excellent place to start if you want to create your own custom Central based +project(s). + +## Project Files + +This project consists of two parts: + +- `rssi_proximity_central`: This project should be run on one Bluefruit nRF52 + board and will configure the board as a Central device, actively scanning + for any peripheral devices in listening range. +- `rssi_proximity_peripheral`: This project should be run on one or more + Bluefruit nRF52 boards and will configure the boards as peripheral devices, + sending out a specifically formatted advertising packet at a regular + interval. diff --git a/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino new file mode 100644 index 00000000..b163ff68 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino @@ -0,0 +1,534 @@ +/********************************************************************* + 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 + + Author: KTOWN (Kevin Townsend) + Copyright (C) Adafruit Industries 2017 +*********************************************************************/ + +/* This example scans for advertising devices (peripherals) in range, + * looking for a specific UUID in the advertising packet. When this + * UUID is found, it will display an alert, sorting devices detected + * in range by their RSSI value, which is an approximate indicator of + * proximity (though highly dependent on environmental obstacles, etc.). + * + * A simple 'bubble sort' algorithm is used, along with a simple + * set of decisions about whether and where to insert new records + * in the record list. + * + * This example is intended to be used with multiple peripherals + * devices running the *_peripheral.ino version of this application. + * + * VERBOSE_OUTPUT + * -------------- + * Verbose advertising packet analysis can be enabled for + * advertising packet contents to help debug issues with the + * advertising payloads, with fully parsed data displayed in the + * Serial Monitor. + * + * ENABLE_TFT + * ---------- + * An ILI9341 based TFT can optionally be used to display proximity + * alerts. The Adafruit TFT Feather Wing is recommended and is the only + * device tested with this functionality. + * + * ARRAY_SIZE + * ---------- + * The numbers of peripherals tracked and sorted can be set via the + * ARRAY_SIZE macro. + * + * TIMEOUT_MS + * ---------- + * This value determines the number of milliseconds before a tracked + * peripheral has it's last sample 'invalidated', such as when a device + * is tracked and then goes out of range. + */ + +#include +#include +#include + +#define VERBOSE_OUTPUT (0) // Set this to 1 for verbose adv packet output to the serial monitor +#define ENABLE_TFT (0) // Set this to 1 to enable ILI9341 TFT display support +#define ARRAY_SIZE (6) // The number of RSSI values to store and compare +#define TIMEOUT_MS (2500) // Number of milliseconds before a record is invalidated in the list + +#if (ARRAY_SIZE <= 0) + #error "ARRAY_SIZE must be a non-zero value" +#endif + +// Custom UUID used to differentiate this device. +// Use any online UUID generator to generate a valid UUID. +// Note that the byte order is reversed ... CUSTOM_UUID +// below corresponds to the follow value: +// df67ff1a-718f-11e7-8cf7-a6006ad3dba0 +const uint8_t CUSTOM_UUID[] = +{ + 0xA0, 0xDB, 0xD3, 0x6A, 0x00, 0xA6, 0xF7, 0x8C, + 0xE7, 0x11, 0x8F, 0x71, 0x1A, 0xFF, 0x67, 0xDF +}; + +BLEUuid uuid = BLEUuid(CUSTOM_UUID); + +/* TFT setup if the TFT display is available */ +#if (ENABLE_TFT) + #include + #include + + /* Pin setup for the TFT display over SPI */ + #ifdef ARDUINO_NRF52_FEATHER + #define TFT_DC 11 + #define TFT_CS 31 + #define STMPE_CS 30 + #define SD_CS 27 + #else + #error "Unknown target. Please make sure you are using an nRF52 Feather and BSP 0.6.5 or higher!" + #endif + + Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); +#endif + +/* This struct is used to track detected nodes */ +typedef struct node_record_s +{ + uint8_t addr[6]; // Six byte device address + int8_t rssi; // RSSI value + int32_t timestamp; // Timestamp for invalidation purposes + int8_t reserved; // Padding for word alignment +} node_record_t; + +node_record_t records[ARRAY_SIZE]; + +void setup() +{ + Serial.begin(115200); + Serial.println("Bluefruit52 Central Proximity Example"); + Serial.println("-------------------------------------\n"); + + /* Enable the TFT display if available */ + #if ENABLE_TFT + tft.begin(); + tft.fillScreen(ILI9341_BLACK); + tft.setCursor(40, 0); + tft.setTextColor(ILI9341_WHITE); + tft.setTextSize(2); + tft.println("DUNKIN"); + #endif + + /* Clear the results list */ + memset(records, 0, sizeof(records)); + for (uint8_t i = 0; i= -80 dBm + //Bluefruit.Scanner.filterUuid(uuid); // Only invoke callback if the target UUID was found + //Bluefruit.Scanner.filterMSD(0xFFFF); // Only invoke callback when MSD is present with the specified Company ID + Bluefruit.Scanner.setInterval(160, 80); // in units of 0.625 ms + Bluefruit.Scanner.useActiveScan(true); // Request scan response data + Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after n seconds + Serial.println("Scanning ..."); +} + +/* This callback handler is fired every time a valid advertising packet is detected */ +void scan_callback(ble_gap_evt_adv_report_t* report) +{ + /* Try to insert this packet into the existing record list */ + node_record_t record; + memcpy(record.addr, report->peer_addr.addr, 6); /* Copy the 6-byte device ADDR */ + record.rssi = report->rssi; /* Copy the RSSI value */ + record.timestamp = millis(); /* Set the timestamp (approximate) */ + if (insertRecord(&record) == 1) /* Returns -1 if the list was updated */ + { + /* The list was updated, print the new values */ + printRecordList(); + } + + /* Display the device on the TFT if available */ +#if ENABLE_TFT + tft.fillRect(0, 0, 240, 30, ILI9341_BLACK); + tft.setTextSize(1); + tft.setCursor(0, 0); + tft.print("["); + tft.print(millis()); + tft.print("] "); + tft.print(report->peer_addr.addr[0]); + tft.print(":"); + tft.print(report->peer_addr.addr[1]); + tft.print(":"); + tft.print(report->peer_addr.addr[2]); + tft.print(":"); + tft.print(report->peer_addr.addr[3]); + tft.print(":"); + tft.print(report->peer_addr.addr[4]); + tft.print(":"); + tft.println(report->peer_addr.addr[5]); + tft.print("RSSI: "); + tft.print(report->rssi); + tft.println(" dBm"); +#endif + +/* Fully parse and display the advertising packet if verbose/debug output is requested */ +#if VERBOSE_OUTPUT + uint8_t len = 0; + uint8_t buffer[32]; + memset(buffer, 0, sizeof(buffer)); + + /* Display the timestamp and device address */ + if (report->scan_rsp) + { + Serial.printf("[SR%10d] Packet received from ", millis()); + } + else + { + Serial.printf("[ADV%9d] Packet received from ", millis()); + } + Serial.printBuffer(report->peer_addr.addr, 6, ':'); + Serial.println(""); + + /* Raw buffer contents */ + Serial.printf("%14s %d bytes\n", "PAYLOAD", report->dlen); + if (report->dlen) + { + Serial.printf("%15s", " "); + Serial.printBuffer(report->data, report->dlen, '-'); + Serial.println(); + } + + /* RSSI value */ + Serial.printf("%14s %d dBm\n", "RSSI", report->rssi); + + /* Adv Type */ + Serial.printf("%14s ", "ADV TYPE"); + switch (report->type) + { + case BLE_GAP_ADV_TYPE_ADV_IND: + Serial.printf("Connectable undirected\n"); + break; + case BLE_GAP_ADV_TYPE_ADV_DIRECT_IND: + Serial.printf("Connectable directed\n"); + break; + case BLE_GAP_ADV_TYPE_ADV_SCAN_IND: + Serial.printf("Scannable undirected\n"); + break; + case BLE_GAP_ADV_TYPE_ADV_NONCONN_IND: + Serial.printf("Non-connectable undirected\n"); + break; + } + + /* Shortened Local Name */ + if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME, buffer, sizeof(buffer))) + { + Serial.printf("%14s %s\n", "SHORT NAME", buffer); + memset(buffer, 0, sizeof(buffer)); + } + + /* Complete Local Name */ + if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, buffer, sizeof(buffer))) + { + Serial.printf("%14s %s\n", "COMPLETE NAME", buffer); + memset(buffer, 0, sizeof(buffer)); + } + + /* TX Power Level */ + if (Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer))) + { + Serial.printf("%14s %i\n", "TX PWR LEVEL", buffer[0]); + memset(buffer, 0, sizeof(buffer)); + } + + /* Check for UUID16 Complete List */ + len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer)); + if ( len ) + { + printUuid16List(buffer, len); + } + + /* Check for UUID16 More Available List */ + len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer)); + if ( len ) + { + printUuid16List(buffer, len); + } + + /* Check for UUID128 Complete List */ + len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer)); + if ( len ) + { + printUuid128List(buffer, len); + } + + /* Check for UUID128 More Available List */ + len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer)); + if ( len ) + { + printUuid128List(buffer, len); + } + + /* Check for BLE UART UUID */ + if ( Bluefruit.Scanner.checkReportForUuid(report, BLEUART_UUID_SERVICE) ) + { + Serial.printf("%14s %s\n", "BLE UART", "UUID Found!"); + } + + /* Check for DIS UUID */ + if ( Bluefruit.Scanner.checkReportForUuid(report, UUID16_SVC_DEVICE_INFORMATION) ) + { + Serial.printf("%14s %s\n", "DIS", "UUID Found!"); + } + + /* Check for Manufacturer Specific Data */ + len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, buffer, sizeof(buffer)); + if (len) + { + Serial.printf("%14s ", "MAN SPEC DATA"); + Serial.printBuffer(buffer, len, '-'); + Serial.println(); + memset(buffer, 0, sizeof(buffer)); + } + + Serial.println(); +#endif +} + +/* Prints a UUID16 list to the Serial Monitor */ +void printUuid16List(uint8_t* buffer, uint8_t len) +{ + Serial.printf("%14s %s", "16-Bit UUID"); + for(int i=0; i= ------------------| + * THE LOWEST RSSI? | + * | | + * | NO | + * | | + * \ / \ / + * +---------------+ +----------------+ + * | IGNORE RECORD | | REPLACE RECORD | + * +---------------+ +----------------+ + * | | + * | \ / + * \ / +----------------+ + * EXIT <------------- | BUBBLE SORT | + * +----------------+ + */ + + /* 1. Bubble Sort + * This puts the lists in a known state where we can make + * certain assumptions about the last record in the array. + */ + bubbleSort(); + + /* 2. Check for a match on existing device address */ + /* Replace it if a match is found, then sort */ + uint8_t match = 0; + for (i=0; iaddr, 6) == 0) + { + match = 1; + } + if (match) + { + memcpy((void *)&records[i], (void *)&record, sizeof(node_record_t)); + goto sort_then_exit; + } + } + + /* 3. Check for zero'ed records */ + /* Insert if a zero record is found, then sort */ + for (i=0; i=, then sort */ + if (records[ARRAY_SIZE-1].rssi <= record->rssi) + { + memcpy((void *)&records[ARRAY_SIZE-1], (void *)&record, sizeof(node_record_t)); + goto sort_then_exit; + } + + /* Nothing to do ... RSSI is lower than the last value, exit and ignore */ + return 0; + +sort_then_exit: + /* Bubble sort */ + bubbleSort(); + return 1; +} + +void loop() +{ + /* Toggle red LED every second */ + digitalToggle(LED_RED); + + delay(1000); +} + diff --git a/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_peripheral/rssi_proximity_peripheral.ino b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_peripheral/rssi_proximity_peripheral.ino new file mode 100644 index 00000000..76cee95b --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_peripheral/rssi_proximity_peripheral.ino @@ -0,0 +1,157 @@ +/********************************************************************* + 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 + + Author: KTOWN (Kevin Townsend) + Copyright (C) Adafruit Industries 2017 +*********************************************************************/ + +/* This example constantly advertises a custom 128-bit UUID, and is + * intended to be used in combination with a Central sketch that scans + * for this UUID, and then displays an alert message, sorting matching + * devices by their RSSI level which is an approximate indication of + * distance (although highly subject to environmental obstacles). + * + * By including a custom UUID in the advertising packet, we can easily + * filter the scan results on the Central device, rather than manually + * parsing the advertising packet(s) of every device in range. + * + * This example is intended to be run with the *_central.ino version + * of this application. + */ + +#include +#include + +// Software Timer for blinking RED LED +SoftwareTimer blinkTimer; + +// Custom UUID used to differentiate this device. +// Use any online UUID generator to generate a valid UUID. +// Note that the byte order is reversed ... CUSTOM_UUID +// below corresponds to the follow value: +// df67ff1a-718f-11e7-8cf7-a6006ad3dba0 +const uint8_t CUSTOM_UUID[] = +{ + 0xA0, 0xDB, 0xD3, 0x6A, 0x00, 0xA6, 0xF7, 0x8C, + 0xE7, 0x11, 0x8F, 0x71, 0x1A, 0xFF, 0x67, 0xDF +}; + +BLEUuid uuid = BLEUuid(CUSTOM_UUID); + +void setup() +{ + Serial.begin(115200); + Serial.println("Bluefruit52 Peripheral Proximity Example"); + Serial.println("----------------------------------------\n"); + + // Initialize blinkTimer for 1000 ms and start it + blinkTimer.begin(1000, blink_timer_callback); + blinkTimer.start(); + + err_t err = Bluefruit.begin(); + if (err) + { + Serial.print("Unable to init Bluefruit (ERROR CODE: "); + Serial.print(err); + Serial.println(")"); + while(1) + { + digitalToggle(LED_RED); + delay(100); + } + } + else + { + Serial.println("Bluefruit initialized (peripheral mode)"); + } + + Bluefruit.setTxPower(4); // Maximum TX power = 4 dBm + Bluefruit.setName("Bluefruit52"); + + // Set up and start advertising + startAdv(); + + Serial.println("Advertising started"); +} + +void startAdv(void) +{ + // Note: The entire advertising packet is limited to 31 bytes! + + // Advertising packet + Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.Advertising.addTxPower(); + + // Preferred Solution: Add a custom UUID to the advertising payload, which + // we will look for on the Central side via Bluefruit.Scanner.filterUuid(uuid); + // A valid 128-bit UUID can be generated online with almost no chance of conflict + // with another device or etup + Bluefruit.Advertising.addUuid(uuid); + + /* + // Alternative Solution: Manufacturer Specific Data (MSD) + // You could also send a custom MSD payload and filter for the 'Company ID' + // via 'Bluefruit.Scanner.filterMSD(CID);', although this does require a + // valid CID, which is why the UUID method above is more appropriate in + // most situations. For a complete list of valid company IDs see: + // https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers + // For test purposes, 0xFFFF CAN be used, but according to the Bluetooth SIG: + // > "This value may be used in the internal and interoperability tests before a + // > Company ID has been assigned. This value shall not be used in shipping end + // > products." + uint8_t msd_payload[4]; // Two bytes are required for the CID, so we have 2 bytes user data, expand as needed + uint16_t msd_cid = 0xFFFF; + memset(msd_payload, 0, sizeof(msd_payload)); + memcpy(msd_payload, (uint8_t*)&msd_cid, sizeof(msd_cid)); + msd_payload[2] = 0x11; + msd_payload[3] = 0x22; + Bluefruit.Advertising.addData(BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, msd_payload, sizeof(msd_payload)); + */ + + // Not enough room in the advertising packet for name + // so store it in the Scan Response instead + Bluefruit.ScanResponse.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 units of 0.625 ms + Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode + Bluefruit.Advertising.start(); +} + +void loop() +{ +} + +/** + * Software Timer callback is invoked via a built-in FreeRTOS thread with + * minimal stack size. Therefore it should be as simple as possible. If + * a periodically heavy task is needed, please use Scheduler.startLoop() to + * create a dedicated task for it. + * + * More information http://www.freertos.org/RTOS-software-timer.html + */ +void blink_timer_callback(TimerHandle_t xTimerID) +{ + (void) xTimerID; + digitalToggle(LED_RED); +} + From 1504fc98eac8b027828e404b13e3292911d8bfb6 Mon Sep 17 00:00:00 2001 From: Kevin Townsend Date: Tue, 1 Aug 2017 00:41:36 +0200 Subject: [PATCH 2/2] Update flow chart --- .../rssi_proximity_central.ino | 33 +++++++++---------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino index b163ff68..8d8339de 100644 --- a/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino +++ b/libraries/Bluefruit52Lib/examples/Projects/rssi_proximity/rssi_proximity_central/rssi_proximity_central.ino @@ -442,25 +442,25 @@ int insertRecord(node_record_t *record) * 1. | BUBBLE SORT | // Put list in known state! * +-------------+ * | - * \ / - * ENTRY YES - * 2. EXISTS W/THIS ------------------+ - * ADDRESS? | - * | | + * _____\ /_____ + * / ENTRY \ YES + * 2. < EXISTS W/THIS > ------------------+ + * \ ADDRESS? / | + * ----------- | * | NO | * | | - * \ / | - * IS YES | - * 3. THERE A ZERO'ED ------------------+ - * RECORD? | - * | | + * ______\ /______ | + * / IS \ YES | + * 3. < THERE A ZERO'ED >------------------+ + * \ RECORD? / | + * ------------- | * | NO | * | | - * \ / | - * IS THE YES | - * 4. RECORD'S RSSI >= ------------------| - * THE LOWEST RSSI? | - * | | + * ______\ /________ | + * / IS THE \ YES | + * 4.< RECORD'S RSSI >= >----------------| + * \ THE LOWEST RSSI? / | + * ---------------- | * | NO | * | | * \ / \ / @@ -476,8 +476,7 @@ int insertRecord(node_record_t *record) /* 1. Bubble Sort * This puts the lists in a known state where we can make - * certain assumptions about the last record in the array. - */ + * certain assumptions about the last record in the array. */ bubbleSort(); /* 2. Check for a match on existing device address */