1// Bluetooth lab B1 Listen. uv run pio run -d labs/ble-lab-b1 -e ble-lab-b1 -t upload2// The board only listens: every Bluetooth LE device around you shouts short "advertising" packets3// on three radio channels, many times a second, whether anyone listens or not. B1 hears them all,4// guesses what each one is, and takes the packets apart byte by byte. Nothing is ever sent to them.5//6// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional (it does what BOOT does).7//8// Views: radar · list · inspect · air (click = next, double-click = the action in the footer,9// long press = pause or resume the scan)10// Serial: help lists the commands. Shared code: kit/lib/ble-kit.11#include "b1_views.h"12#include "ble_lab.h"13#include "listener.h"14 15namespace {16 17b1::Listener ears;18b1::AirHistory history;19b1::Pick pick;20ble::Heard rows[ble::ScanTable::kMax];21int rowCount = 0;22 23// The picked device in this frame's rows, or nullptr when it went quiet.24const ble::Heard *picked() {25 for (int i = 0; i < rowCount; i++)26 if (pick.matches(rows[i])) return &rows[i];27 return nullptr;28}29 30void pickIndex(int i) {31 if (i < 0 || i >= rowCount) return;32 pick.take(rows[i]);33 char addr[18];34 rows[i].addrText(addr, sizeof(addr));35 BLE_NOTE(Info, "picked %d: %s %s", i + 1, rows[i].label(), addr);36}37 38// ---- Views ------------------------------------------------------------------------------------39 40void drawRadar(BleLab &, FrameBuffer &fb, float t) { b1v::radar(fb, rows, rowCount, pick, ears.settings, ears.scanning(), history.latest(), t); }41void drawList(BleLab &, FrameBuffer &fb, float) { b1v::list(fb, rows, rowCount, pick); }42void drawInspect(BleLab &, FrameBuffer &fb, float) { b1v::inspect(fb, picked(), ears.settings); }43void drawAir(BleLab &, FrameBuffer &fb, float) { b1v::air(fb, history, rows, rowCount, ears.settings, ears.scanning()); }44 45const BleView kViews[] = {46 {"radar", drawRadar, "next"},47 {"list", drawList, "next"},48 {"inspect", drawInspect, "watch"},49 {"air", drawAir, "mode"},50};51 52// ---- Commands ---------------------------------------------------------------------------------53 54void cmdScan(BleLab &lab, const String &, const String &lower) {55 const bool on = lower.isEmpty() ? !ears.scanning() : lower == "on";56 if (!lower.isEmpty() && lower != "on" && lower != "off") return lab.warn("scan | scan on | scan off");57 on ? ears.start() : ears.stop();58}59 60void cmdMode(BleLab &lab, const String &, const String &lower) {61 if (!lower.isEmpty() && lower != "active" && lower != "passive") return lab.warn("mode | mode active | mode passive");62 ears.settings.active = lower.isEmpty() ? !ears.settings.active : lower == "active";63 ears.start();64}65 66void cmdTiming(BleLab &lab, const String &arg, const String &) {67 const int sp = arg.indexOf(' ');68 long interval = 0, window = 0;69 if (sp < 0 || !BleLab::number(arg.substring(0, sp), 10, 10240, interval) || !BleLab::number(arg.substring(sp + 1), 10, interval, window))70 return lab.warn("timing <interval ms> <window ms>, 10-10240, window <= interval (default 100 100)");71 ears.settings.intervalMs = uint16_t(interval);72 ears.settings.windowMs = uint16_t(window);73 ears.start();74}75 76void cmdNear(BleLab &lab, const String &arg, const String &lower) {77 long dbm = 0;78 if (lower == "off") ears.settings.nearDbm = -127;79 else if (BleLab::number(arg, -100, -20, dbm)) ears.settings.nearDbm = int(dbm);80 else return lab.warn("near <dBm> (e.g. near -70) | near off");81 if (ears.settings.nearDbm == -127) BLE_NOTE(Info, "showing every device");82 else BLE_NOTE(Info, "showing devices stronger than %d dBm", ears.settings.nearDbm);83}84 85void cmdPick(BleLab &lab, const String &arg, const String &) {86 long n = 0;87 if (!BleLab::number(arg, 1, std::max(rowCount, 1), n)) return lab.warn("pick <1-%d>: the number on the list view", rowCount);88 pickIndex(n - 1);89 lab.showView("inspect");90}91 92void cmdNext(BleLab &, const String &, const String &) {93 if (rowCount == 0) return;94 int at = -1;95 for (int i = 0; i < rowCount; i++)96 if (pick.matches(rows[i])) at = i;97 pickIndex((at + 1) % rowCount);98}99 100void cmdWatch(BleLab &lab, const String &, const String &lower) {101 if (lower == "off" || ears.watching()) {102 ears.watch(b1::Pick{});103 return BLE_NOTE(Info, "watch off");104 }105 if (!picked()) return lab.warn("pick a device first (list view, double-click; or pick <n>)");106 ears.watch(pick);107 BLE_NOTE(Info, "watching %s: one line per packet, see the gaps", picked()->label());108}109 110void cmdList(BleLab &, const String &, const String &) {111 Serial.printf("%d devices heard in the last 30 s (strongest first):\n", rowCount);112 Serial.println(" # dBm ~m kind address type packets name / maker");113 for (int i = 0; i < rowCount; i++) {114 const ble::Heard &h = rows[i];115 char addr[18];116 h.addrText(addr, sizeof(addr));117 Serial.printf("%3d %4d %4.1f %-14s %s %-14s %7lu %s%s\n", i + 1, int(h.rssiAvg), ad::distanceMeters(int(h.rssiAvg), ears.settings.rssiAt1m),118 ad::kindName(h.kind), addr, ad::addrKindName(h.addrKind()), static_cast<unsigned long>(h.packets), h.label(),119 h.connectable ? "" : " (broadcast only)");120 }121}122 123void printBytes(const char *what, const uint8_t *p, uint8_t n) {124 Serial.printf(" %s, %u of 31 bytes:\n ", what, n);125 const ad::Parsed ps = ad::split(p, n);126 for (int f = 0; f < ps.count; f++) {127 const ad::Field &fl = ps.fields[f];128 Serial.printf(" [%02X %02X |", fl.len + 1, fl.type);129 for (int i = 0; i < fl.len; i++) Serial.printf(" %02X", p[fl.offset + i]);130 Serial.printf("] %s\n ", ad::typeName(fl.type));131 }132 if (ps.malformed) Serial.print(" malformed: a length runs past the end");133 Serial.println();134}135 136void cmdBytes(BleLab &lab, const String &, const String &) {137 const ble::Heard *h = picked();138 if (!h) return lab.warn("pick a device first");139 char addr[18];140 h->addrText(addr, sizeof(addr));141 Serial.printf("%s %s (%s)\n", h->label(), addr, ad::addrKindName(h->addrKind()));142 printBytes("advertisement", h->adv, h->advLen);143 if (h->rspLen) printBytes("scan response", h->rsp, h->rspLen);144 else Serial.println(ears.settings.active ? " no scan response (it doesn't send one)" : " scan response: switch to mode active to ask for it");145}146 147void cmdCalib(BleLab &lab, const String &, const String &) {148 const ble::Heard *h = picked();149 if (!h) return lab.warn("pick your phone first, hold it 1 m from the board, then calib");150 ears.settings.rssiAt1m = int(h->rssiAvg);151 BLE_NOTE(Good, "1 m = %d dBm now: distances use it", ears.settings.rssiAt1m);152}153 154void cmdClear(BleLab &, const String &, const String &) {155 ears.table.clear();156 pick = b1::Pick{};157 BLE_NOTE(Info, "table cleared");158}159 160const BleCommand kCommands[] = {161⋯ 11 lines of data folded away. Show them172};173 174// ---- Hooks ------------------------------------------------------------------------------------175 176void setup(BleLab &) { ears.begin(); }177 178void tick(BleLab &) {179 rowCount = ears.table.snapshot(rows, ble::ScanTable::kMax, 30000, ears.settings.nearDbm);180 int recent = 0; // "in range" = heard in the last 10 s181 for (int i = 0; i < rowCount; i++) recent += millis() - rows[i].lastSeen < 10000;182 history.tick(ears.table, recent);183 if (!pick.set && rowCount) pick.take(rows[0]);184}185 186const BleLabSpec kSpec{187 "ble-lab-b1", "B1", "Listen", "Bench B1", kViews, sizeof(kViews) / sizeof(kViews[0]), 0,188 kCommands, sizeof(kCommands) / sizeof(kCommands[0]), setup, tick, nullptr, "scan",189};190 191BleLab lab(kSpec);192 193} // namespace194 195void setup() { lab.begin(); }196 197void loop() { lab.loop(); }
// Bluetooth lab B1 Listen. uv run pio run -d labs/ble-lab-b1 -e ble-lab-b1 -t upload
// The board only listens: every Bluetooth LE device around you shouts short "advertising" packets
// on three radio channels, many times a second, whether anyone listens or not. B1 hears them all,
// guesses what each one is, and takes the packets apart byte by byte. Nothing is ever sent to them.
//
// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional (it does what BOOT does).
// Views: radar · list · inspect · air (click = next, double-click = the action in the footer,
// long press = pause or resume the scan)
// Serial: help lists the commands. Shared code: kit/lib/ble-kit.
#include "b1_views.h"
#include "ble_lab.h"
#include "listener.h"
namespace {
b1::Listener ears;
b1::AirHistory history;
b1::Pick pick;
ble::Heard rows[ble::ScanTable::kMax];
int rowCount = 0;
// The picked device in this frame's rows, or nullptr when it went quiet.
const ble::Heard *picked() {
for (int i = 0; i < rowCount; i++)
if (pick.matches(rows[i])) return &rows[i];
return nullptr;
}
void pickIndex(int i) {
if (i < 0 || i >= rowCount) return;
pick.take(rows[i]);
char addr[18];
rows[i].addrText(addr, sizeof(addr));
BLE_NOTE(Info, "picked %d: %s %s", i + 1, rows[i].label(), addr);
// ---- Views ------------------------------------------------------------------------------------
void drawRadar(BleLab &, FrameBuffer &fb, float t) { b1v::radar(fb, rows, rowCount, pick, ears.settings, ears.scanning(), history.latest(), t); }
void drawList(BleLab &, FrameBuffer &fb, float) { b1v::list(fb, rows, rowCount, pick); }
void drawInspect(BleLab &, FrameBuffer &fb, float) { b1v::inspect(fb, picked(), ears.settings); }
void drawAir(BleLab &, FrameBuffer &fb, float) { b1v::air(fb, history, rows, rowCount, ears.settings, ears.scanning()); }
const BleView kViews[] = {
{"radar", drawRadar, "next"},
{"list", drawList, "next"},
{"inspect", drawInspect, "watch"},
{"air", drawAir, "mode"},
};
// ---- Commands ---------------------------------------------------------------------------------
void cmdScan(BleLab &lab, const String &, const String &lower) {
const bool on = lower.isEmpty() ? !ears.scanning() : lower == "on";
if (!lower.isEmpty() && lower != "on" && lower != "off") return lab.warn("scan | scan on | scan off");
on ? ears.start() : ears.stop();
void cmdMode(BleLab &lab, const String &, const String &lower) {
if (!lower.isEmpty() && lower != "active" && lower != "passive") return lab.warn("mode | mode active | mode passive");
ears.settings.active = lower.isEmpty() ? !ears.settings.active : lower == "active";
ears.start();
void cmdTiming(BleLab &lab, const String &arg, const String &) {
const int sp = arg.indexOf(' ');
long interval = 0, window = 0;
if (sp < 0 || !BleLab::number(arg.substring(0, sp), 10, 10240, interval) || !BleLab::number(arg.substring(sp + 1), 10, interval, window))
return lab.warn("timing <interval ms> <window ms>, 10-10240, window <= interval (default 100 100)");
ears.settings.intervalMs = uint16_t(interval);
ears.settings.windowMs = uint16_t(window);
void cmdNear(BleLab &lab, const String &arg, const String &lower) {
long dbm = 0;
if (lower == "off") ears.settings.nearDbm = -127;
else if (BleLab::number(arg, -100, -20, dbm)) ears.settings.nearDbm = int(dbm);
else return lab.warn("near <dBm> (e.g. near -70) | near off");
if (ears.settings.nearDbm == -127) BLE_NOTE(Info, "showing every device");
else BLE_NOTE(Info, "showing devices stronger than %d dBm", ears.settings.nearDbm);
void cmdPick(BleLab &lab, const String &arg, const String &) {
long n = 0;
if (!BleLab::number(arg, 1, std::max(rowCount, 1), n)) return lab.warn("pick <1-%d>: the number on the list view", rowCount);
pickIndex(n - 1);
lab.showView("inspect");
void cmdNext(BleLab &, const String &, const String &) {
if (rowCount == 0) return;
int at = -1;
if (pick.matches(rows[i])) at = i;
pickIndex((at + 1) % rowCount);
void cmdWatch(BleLab &lab, const String &, const String &lower) {
if (lower == "off" || ears.watching()) {
ears.watch(b1::Pick{});
return BLE_NOTE(Info, "watch off");
if (!picked()) return lab.warn("pick a device first (list view, double-click; or pick <n>)");
ears.watch(pick);
BLE_NOTE(Info, "watching %s: one line per packet, see the gaps", picked()->label());
void cmdList(BleLab &, const String &, const String &) {
Serial.printf("%d devices heard in the last 30 s (strongest first):\n", rowCount);
Serial.println(" # dBm ~m kind address type packets name / maker");
for (int i = 0; i < rowCount; i++) {
const ble::Heard &h = rows[i];
h.addrText(addr, sizeof(addr));
Serial.printf("%3d %4d %4.1f %-14s %s %-14s %7lu %s%s\n", i + 1, int(h.rssiAvg), ad::distanceMeters(int(h.rssiAvg), ears.settings.rssiAt1m),
ad::kindName(h.kind), addr, ad::addrKindName(h.addrKind()), static_cast<unsigned long>(h.packets), h.label(),
h.connectable ? "" : " (broadcast only)");
void printBytes(const char *what, const uint8_t *p, uint8_t n) {
Serial.printf(" %s, %u of 31 bytes:\n ", what, n);
const ad::Parsed ps = ad::split(p, n);
for (int f = 0; f < ps.count; f++) {
const ad::Field &fl = ps.fields[f];
Serial.printf(" [%02X %02X |", fl.len + 1, fl.type);
for (int i = 0; i < fl.len; i++) Serial.printf(" %02X", p[fl.offset + i]);
Serial.printf("] %s\n ", ad::typeName(fl.type));
if (ps.malformed) Serial.print(" malformed: a length runs past the end");
Serial.println();
void cmdBytes(BleLab &lab, const String &, const String &) {
const ble::Heard *h = picked();
if (!h) return lab.warn("pick a device first");
h->addrText(addr, sizeof(addr));
Serial.printf("%s %s (%s)\n", h->label(), addr, ad::addrKindName(h->addrKind()));
printBytes("advertisement", h->adv, h->advLen);
if (h->rspLen) printBytes("scan response", h->rsp, h->rspLen);
else Serial.println(ears.settings.active ? " no scan response (it doesn't send one)" : " scan response: switch to mode active to ask for it");
void cmdCalib(BleLab &lab, const String &, const String &) {
if (!h) return lab.warn("pick your phone first, hold it 1 m from the board, then calib");
ears.settings.rssiAt1m = int(h->rssiAvg);
BLE_NOTE(Good, "1 m = %d dBm now: distances use it", ears.settings.rssiAt1m);
void cmdClear(BleLab &, const String &, const String &) {
ears.table.clear();
pick = b1::Pick{};
BLE_NOTE(Info, "table cleared");
const BleCommand kCommands[] = {
// ---- Hooks ------------------------------------------------------------------------------------
void setup(BleLab &) { ears.begin(); }
void tick(BleLab &) {
rowCount = ears.table.snapshot(rows, ble::ScanTable::kMax, 30000, ears.settings.nearDbm);
int recent = 0; // "in range" = heard in the last 10 s
for (int i = 0; i < rowCount; i++) recent += millis() - rows[i].lastSeen < 10000;
history.tick(ears.table, recent);
if (!pick.set && rowCount) pick.take(rows[0]);
const BleLabSpec kSpec{
"ble-lab-b1", "B1", "Listen", "Bench B1", kViews, sizeof(kViews) / sizeof(kViews[0]), 0,
kCommands, sizeof(kCommands) / sizeof(kCommands[0]), setup, tick, nullptr, "scan",
BleLab lab(kSpec);
} // namespace
void setup() { lab.begin(); }
void loop() { lab.loop(); }
New word #include
#include
Pastes another file in here, so this file can use what it declares.
PlatformIO environment ble-lab-b1 includes C++ source files covering advertising, channels 37 · 38 · 39, AD structures, active vs passive scan, RSSI → distance, private addresses, scan duty cycle.