1// Bluetooth lab B4 Pair & trust. uv run pio run -d labs/ble-lab-b4 -e ble-lab-b4 -t upload2// B3's Bench service gets a Vault: a characteristic only an encrypted, authenticated link may read3// or write. Touch it from the phone and pairing starts: the passkey appears on the TFT, or both4// screens show 6 digits and you confirm with the button. The board then remembers the phone (a5// bond, saved in flash), recognises it behind its changing private address, and can refuse6// everybody else.7//8// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional (it does what BOOT does).9//10// Views: ceremony · bonds · gatt · link · log (click = next view, double-click = the view's action;11// while numbers wait for comparison: click = yes, long press = no)12// Serial: help lists the commands. Shared code: kit/lib/ble-kit (bench_service.h, server_link.h).13#include <Preferences.h>14 15#include "b4_views.h"16#include "bench_views.h"17#include "ble_lab.h"18#include "ceremony.h"19 20namespace {21 22b4::B4Link links;23bench::BenchService bench_;24b4v::Settings settings;25Preferences prefs;26b4v::BondRow bondRows[8];27int bondCount = 0;28uint32_t bondsAt = 0;29 30void refreshBonds() {31 bondCount = std::min(NimBLEDevice::getNumBonds(), 8);32 for (int i = 0; i < bondCount; i++) {33 const NimBLEAddress a = NimBLEDevice::getBondedAddress(i);34 strlcpy(bondRows[i].addr, a.toString().c_str(), sizeof(bondRows[i].addr));35 bondRows[i].random = a.getType() != BLE_ADDR_PUBLIC;36 }37 bondsAt = millis();38}39 40// What the board says about itself when pairing starts (its IO capabilities), and what it wants.41void applySecurity() {42 static const uint8_t io[] = {BLE_HS_IO_NO_INPUT_OUTPUT, BLE_HS_IO_DISPLAY_ONLY, BLE_HS_IO_DISPLAY_YESNO};43 NimBLEDevice::setSecurityIOCap(io[settings.method]);44 // bond = remember the keys · mitm = demand a check by a person · sc = LE Secure Connections (ECDH)45 NimBLEDevice::setSecurityAuth(true, settings.method != 0, true);46 // Keys both sides hand over after pairing: the encryption key (LTK) and the identity key (IRK).47 NimBLEDevice::setSecurityInitKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);48 NimBLEDevice::setSecurityRespKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);49}50 51// "allow bonded": only phones on the filter accept list (the bonded identities) may connect. The52// controller resolves each private address with the stored IRKs before it checks the list.53void applyAllow() {54 NimBLEAdvertising *adv = NimBLEDevice::getAdvertising();55 const bool wasOn = adv->isAdvertising();56 adv->stop();57 while (NimBLEDevice::getWhiteListCount()) NimBLEDevice::whiteListRemove(NimBLEDevice::getWhiteListAddress(0));58 if (settings.allowBondedOnly)59 for (int i = 0; i < NimBLEDevice::getNumBonds(); i++) NimBLEDevice::whiteListAdd(NimBLEDevice::getBondedAddress(i));60 // Scan requests stay open to all (phones still see the board), connections only from the list.61 adv->setScanFilter(false, settings.allowBondedOnly);62 if (settings.allowBondedOnly && NimBLEDevice::getNumBonds() == 0) BLE_NOTE(Warn, "no bonds yet: nobody can connect now");63 if (wasOn || ble::link().get().radio != ble::Radio::Connected) {64 if (adv->start()) ble::link().edit([](ble::LinkState &s) {65 s.advertising = true;66 if (s.radio != ble::Radio::Connected) s.radio = ble::Radio::Advertising;67 });68 }69}70 71// ---- Views ------------------------------------------------------------------------------------72 73void drawCeremony(BleLab &lab, FrameBuffer &fb, float t) { b4v::ceremony(fb, b4::recorder().get(), lab.state(), settings, t); }74void drawBonds(BleLab &lab, FrameBuffer &fb, float t) { b4v::bonds(fb, bondRows, bondCount, lab.state(), t); }75void drawGatt(BleLab &, FrameBuffer &fb, float t) { bv::gatt(fb, bench_.state(), t); }76void drawLink(BleLab &lab, FrameBuffer &fb, float t) { bv::link(fb, lab.state(), t); }77void drawLog(BleLab &, FrameBuffer &fb, float) { bv::log(fb); }78 79const BleView kViews[] = {80 {"ceremony", drawCeremony, "secure"},81 {"bonds", drawBonds, "bonds"},82 {"gatt", drawGatt, "press"},83 {"link", drawLink, "secure"},84 {"log", drawLog, nullptr},85};86 87// ---- Commands ---------------------------------------------------------------------------------88 89void cmdPair(BleLab &lab, const String &, const String &lower) {90 static const char *const names[] = {"justworks", "passkey", "compare"};91 for (uint8_t i = 0; i < 3; i++)92 if (lower == names[i]) {93 settings.method = i;94 prefs.putUChar("method", i);95 applySecurity();96 BLE_NOTE(Good, "next pairing: %s (saved)", b4v::methodName(i));97 if (NimBLEDevice::getNumBonds()) BLE_NOTE(Info, "old bonds keep their old level: forget + pair again");98 return lab.showView("ceremony");99 }100 lab.warn("pair justworks | passkey | compare (now: %s)", b4v::methodName(settings.method));101}102 103// The GATT table is built once at start, with its permissions: changing them means a restart.104void cmdLock(BleLab &lab, const String &, const String &lower) {105 if (lower != "on" && lower != "off") return lab.warn("lock on | lock off (now %s)", settings.lock ? "on" : "off");106 prefs.putBool("lock", lower == "on");107 Serial.printf("lock %s saved. The GATT table is fixed at start-up, so the board restarts now...\n", lower.c_str());108 Serial.flush();109 delay(300);110 ESP.restart();111}112 113void printBonds() {114 refreshBonds();115 Serial.printf("%d bonded device%s (identity addresses, as the bond store keeps them):\n", bondCount, bondCount == 1 ? "" : "s");116 for (int i = 0; i < bondCount; i++) Serial.printf(" %d %s %s\n", i + 1, bondRows[i].addr, bondRows[i].random ? "random static" : "public");117}118 119void cmdBonds(BleLab &lab, const String &, const String &) {120 printBonds();121 lab.showView("bonds");122}123 124void cmdForget(BleLab &lab, const String &arg, const String &lower) {125 refreshBonds();126 const ble::LinkState s = ble::link().get();127 if (lower == "all") {128 NimBLEDevice::deleteAllBonds();129 BLE_NOTE(Warn, "forgot every bond");130 } else {131 long n = 0;132 if (!BleLab::number(arg, 1, std::max(bondCount, 1), n) || bondCount == 0) return lab.warn("forget <1-%d> | forget all (see bonds)", bondCount);133 NimBLEDevice::deleteBond(NimBLEDevice::getBondedAddress(n - 1));134 BLE_NOTE(Warn, "forgot bond %ld: %s", n, bondRows[n - 1].addr);135 }136 BLE_NOTE(Info, "now forget \"Bench B4\" on the phone too");137 if (s.radio == ble::Radio::Connected && s.peer.bonded) NimBLEDevice::getServer()->disconnect(s.peer.handle);138 refreshBonds();139 if (settings.allowBondedOnly) applyAllow();140}141 142void cmdAllow(BleLab &lab, const String &, const String &lower) {143 if (lower != "bonded" && lower != "anyone") return lab.warn("allow bonded | allow anyone (now %s)", settings.allowBondedOnly ? "bonded" : "anyone");144 settings.allowBondedOnly = lower == "bonded";145 prefs.putBool("allow", settings.allowBondedOnly);146 applyAllow();147 BLE_NOTE(Good, "%s may connect (saved)", settings.allowBondedOnly ? "only bonded phones" : "anyone");148}149 150void cmdYes(BleLab &lab, const String &, const String &) {151 if (!links.confirm(true)) lab.warn("no numbers are waiting for a comparison");152}153void cmdNo(BleLab &lab, const String &, const String &) {154 if (!links.confirm(false)) lab.warn("no numbers are waiting for a comparison");155}156 157// The peripheral asks; the phone starts encryption (stored keys) or pairing (no keys yet).158void cmdSecure(BleLab &lab, const String &, const String &) {159 const ble::LinkState s = ble::link().get();160 if (s.radio != ble::Radio::Connected) return lab.warn("connect a phone first");161 if (s.peer.encrypted) return BLE_NOTE(Info, "already encrypted");162 if (NimBLEDevice::startSecurity(s.peer.handle)) BLE_NOTE(Tx, "Security Request: please encrypt");163 else lab.warn("the request was refused (pairing already running?)");164}165 166void cmdVault(BleLab &lab, const String &arg, const String &) {167 if (arg.isEmpty()) return lab.warn("vault <text>: a secret only a paired phone can read");168 bench_.setVault(arg.c_str());169 BLE_NOTE(Info, "Vault set (%u bytes)", arg.length());170}171 172void cmdPress(BleLab &, const String &, const String &) { bench_.button(1); }173 174void cmdDisconnect(BleLab &lab, const String &, const String &) {175 const ble::LinkState s = ble::link().get();176 if (s.radio != ble::Radio::Connected) return lab.warn("nobody is connected");177 NimBLEDevice::getServer()->disconnect(s.peer.handle);178}179 180const BleCommand kCommands[] = {181⋯ 11 lines of data folded away. Show them192};193 194// ---- Hooks ------------------------------------------------------------------------------------195 196void setup(BleLab &lab) {197 prefs.begin("b4", false);198 settings.method = prefs.getUChar("method", 1) % 3;199 settings.lock = prefs.getBool("lock", false);200 settings.allowBondedOnly = prefs.getBool("allow", false);201 applySecurity();202 NimBLEDevice::setCustomGapHandler(b4::gapListener);203 NimBLEServer *server = NimBLEDevice::createServer();204 server->setCallbacks(&links, false);205 bench::Options o;206 o.vault = true;207 o.lockControls = settings.lock;208 bench_.begin(server, o);209 bench_.setVault("the bench's secret: 42");210 server->start();211 bench::advertise(lab.spec().deviceName, false);212 applyAllow();213 refreshBonds();214 BLE_NOTE(Info, "pairing: %s, lock %s, %s may connect", b4v::methodName(settings.method), settings.lock ? "on" : "off",215 settings.allowBondedOnly ? "bonded" : "anyone");216}217 218void tick(BleLab &lab) {219 bench_.tick();220 uint8_t c[3];221 if (bench_.takeLed(c)) {222 lab.claimLed(true);223 rgbLedWrite(PIN_RGB, c[0], c[1], c[2]);224 }225 if (millis() - bondsAt > 1000) refreshBonds();226}227 228bool gesture(BleLab &, Gesture g, bool) {229 if (links.comparing()) {230 if (g == Gesture::Click) links.confirm(true);231 else if (g == Gesture::LongPress) links.confirm(false);232 return true;233 }234 bench_.button(g == Gesture::Click ? 1 : g == Gesture::DoubleClick ? 2 : 3);235 return false;236}237 238const BleLabSpec kSpec{239 "ble-lab-b4", "B4", "Pair & trust", "Bench B4", kViews, sizeof(kViews) / sizeof(kViews[0]), 0,240 kCommands, sizeof(kCommands) / sizeof(kCommands[0]), setup, tick, gesture, nullptr,241};242 243BleLab lab(kSpec);244 245} // namespace246 247void setup() { lab.begin(); }248 249void loop() { lab.loop(); }
// Bluetooth lab B4 Pair & trust. uv run pio run -d labs/ble-lab-b4 -e ble-lab-b4 -t upload
// B3's Bench service gets a Vault: a characteristic only an encrypted, authenticated link may read
// or write. Touch it from the phone and pairing starts: the passkey appears on the TFT, or both
// screens show 6 digits and you confirm with the button. The board then remembers the phone (a
// bond, saved in flash), recognises it behind its changing private address, and can refuse
// everybody else.
//
// Wiring: the screen from lesson 03. The push button on GPIO 5 is optional (it does what BOOT does).
// Views: ceremony · bonds · gatt · link · log (click = next view, double-click = the view's action;
// while numbers wait for comparison: click = yes, long press = no)
// Serial: help lists the commands. Shared code: kit/lib/ble-kit (bench_service.h, server_link.h).
#include <Preferences.h>
#include "b4_views.h"
#include "bench_views.h"
#include "ble_lab.h"
#include "ceremony.h"
namespace {
b4::B4Link links;
bench::BenchService bench_;
b4v::Settings settings;
Preferences prefs;
b4v::BondRow bondRows[8];
int bondCount = 0;
uint32_t bondsAt = 0;
void refreshBonds() {
bondCount = std::min(NimBLEDevice::getNumBonds(), 8);
for (int i = 0; i < bondCount; i++) {
const NimBLEAddress a = NimBLEDevice::getBondedAddress(i);
strlcpy(bondRows[i].addr, a.toString().c_str(), sizeof(bondRows[i].addr));
bondRows[i].random = a.getType() != BLE_ADDR_PUBLIC;
}
bondsAt = millis();
// What the board says about itself when pairing starts (its IO capabilities), and what it wants.
void applySecurity() {
static const uint8_t io[] = {BLE_HS_IO_NO_INPUT_OUTPUT, BLE_HS_IO_DISPLAY_ONLY, BLE_HS_IO_DISPLAY_YESNO};
NimBLEDevice::setSecurityIOCap(io[settings.method]);
// bond = remember the keys · mitm = demand a check by a person · sc = LE Secure Connections (ECDH)
NimBLEDevice::setSecurityAuth(true, settings.method != 0, true);
// Keys both sides hand over after pairing: the encryption key (LTK) and the identity key (IRK).
NimBLEDevice::setSecurityInitKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);
NimBLEDevice::setSecurityRespKey(BLE_SM_PAIR_KEY_DIST_ENC | BLE_SM_PAIR_KEY_DIST_ID);
// "allow bonded": only phones on the filter accept list (the bonded identities) may connect. The
// controller resolves each private address with the stored IRKs before it checks the list.
void applyAllow() {
NimBLEAdvertising *adv = NimBLEDevice::getAdvertising();
const bool wasOn = adv->isAdvertising();
adv->stop();
while (NimBLEDevice::getWhiteListCount()) NimBLEDevice::whiteListRemove(NimBLEDevice::getWhiteListAddress(0));
if (settings.allowBondedOnly)
for (int i = 0; i < NimBLEDevice::getNumBonds(); i++) NimBLEDevice::whiteListAdd(NimBLEDevice::getBondedAddress(i));
// Scan requests stay open to all (phones still see the board), connections only from the list.
adv->setScanFilter(false, settings.allowBondedOnly);
if (settings.allowBondedOnly && NimBLEDevice::getNumBonds() == 0) BLE_NOTE(Warn, "no bonds yet: nobody can connect now");
if (wasOn || ble::link().get().radio != ble::Radio::Connected) {
if (adv->start()) ble::link().edit([](ble::LinkState &s) {
s.advertising = true;
if (s.radio != ble::Radio::Connected) s.radio = ble::Radio::Advertising;
});
// ---- Views ------------------------------------------------------------------------------------
void drawCeremony(BleLab &lab, FrameBuffer &fb, float t) { b4v::ceremony(fb, b4::recorder().get(), lab.state(), settings, t); }
void drawBonds(BleLab &lab, FrameBuffer &fb, float t) { b4v::bonds(fb, bondRows, bondCount, lab.state(), t); }
void drawGatt(BleLab &, FrameBuffer &fb, float t) { bv::gatt(fb, bench_.state(), t); }
void drawLink(BleLab &lab, FrameBuffer &fb, float t) { bv::link(fb, lab.state(), t); }
void drawLog(BleLab &, FrameBuffer &fb, float) { bv::log(fb); }
const BleView kViews[] = {
{"ceremony", drawCeremony, "secure"},
{"bonds", drawBonds, "bonds"},
{"gatt", drawGatt, "press"},
{"link", drawLink, "secure"},
{"log", drawLog, nullptr},
};
// ---- Commands ---------------------------------------------------------------------------------
void cmdPair(BleLab &lab, const String &, const String &lower) {
static const char *const names[] = {"justworks", "passkey", "compare"};
for (uint8_t i = 0; i < 3; i++)
if (lower == names[i]) {
settings.method = i;
prefs.putUChar("method", i);
applySecurity();
BLE_NOTE(Good, "next pairing: %s (saved)", b4v::methodName(i));
if (NimBLEDevice::getNumBonds()) BLE_NOTE(Info, "old bonds keep their old level: forget + pair again");
return lab.showView("ceremony");
lab.warn("pair justworks | passkey | compare (now: %s)", b4v::methodName(settings.method));
// The GATT table is built once at start, with its permissions: changing them means a restart.
void cmdLock(BleLab &lab, const String &, const String &lower) {
if (lower != "on" && lower != "off") return lab.warn("lock on | lock off (now %s)", settings.lock ? "on" : "off");
prefs.putBool("lock", lower == "on");
Serial.printf("lock %s saved. The GATT table is fixed at start-up, so the board restarts now...\n", lower.c_str());
Serial.flush();
delay(300);
ESP.restart();
void printBonds() {
refreshBonds();
Serial.printf("%d bonded device%s (identity addresses, as the bond store keeps them):\n", bondCount, bondCount == 1 ? "" : "s");
for (int i = 0; i < bondCount; i++) Serial.printf(" %d %s %s\n", i + 1, bondRows[i].addr, bondRows[i].random ? "random static" : "public");
void cmdBonds(BleLab &lab, const String &, const String &) {
printBonds();
lab.showView("bonds");
void cmdForget(BleLab &lab, const String &arg, const String &lower) {
const ble::LinkState s = ble::link().get();
if (lower == "all") {
NimBLEDevice::deleteAllBonds();
BLE_NOTE(Warn, "forgot every bond");
} else {
long n = 0;
if (!BleLab::number(arg, 1, std::max(bondCount, 1), n) || bondCount == 0) return lab.warn("forget <1-%d> | forget all (see bonds)", bondCount);
NimBLEDevice::deleteBond(NimBLEDevice::getBondedAddress(n - 1));
BLE_NOTE(Warn, "forgot bond %ld: %s", n, bondRows[n - 1].addr);
BLE_NOTE(Info, "now forget \"Bench B4\" on the phone too");
if (s.radio == ble::Radio::Connected && s.peer.bonded) NimBLEDevice::getServer()->disconnect(s.peer.handle);
if (settings.allowBondedOnly) applyAllow();
void cmdAllow(BleLab &lab, const String &, const String &lower) {
if (lower != "bonded" && lower != "anyone") return lab.warn("allow bonded | allow anyone (now %s)", settings.allowBondedOnly ? "bonded" : "anyone");
settings.allowBondedOnly = lower == "bonded";
prefs.putBool("allow", settings.allowBondedOnly);
applyAllow();
BLE_NOTE(Good, "%s may connect (saved)", settings.allowBondedOnly ? "only bonded phones" : "anyone");
void cmdYes(BleLab &lab, const String &, const String &) {
if (!links.confirm(true)) lab.warn("no numbers are waiting for a comparison");
void cmdNo(BleLab &lab, const String &, const String &) {
if (!links.confirm(false)) lab.warn("no numbers are waiting for a comparison");
// The peripheral asks; the phone starts encryption (stored keys) or pairing (no keys yet).
void cmdSecure(BleLab &lab, const String &, const String &) {
if (s.radio != ble::Radio::Connected) return lab.warn("connect a phone first");
if (s.peer.encrypted) return BLE_NOTE(Info, "already encrypted");
if (NimBLEDevice::startSecurity(s.peer.handle)) BLE_NOTE(Tx, "Security Request: please encrypt");
else lab.warn("the request was refused (pairing already running?)");
void cmdVault(BleLab &lab, const String &arg, const String &) {
if (arg.isEmpty()) return lab.warn("vault <text>: a secret only a paired phone can read");
bench_.setVault(arg.c_str());
BLE_NOTE(Info, "Vault set (%u bytes)", arg.length());
void cmdPress(BleLab &, const String &, const String &) { bench_.button(1); }
void cmdDisconnect(BleLab &lab, const String &, const String &) {
if (s.radio != ble::Radio::Connected) return lab.warn("nobody is connected");
NimBLEDevice::getServer()->disconnect(s.peer.handle);
const BleCommand kCommands[] = {
// ---- Hooks ------------------------------------------------------------------------------------
void setup(BleLab &lab) {
prefs.begin("b4", false);
settings.method = prefs.getUChar("method", 1) % 3;
settings.lock = prefs.getBool("lock", false);
settings.allowBondedOnly = prefs.getBool("allow", false);
NimBLEDevice::setCustomGapHandler(b4::gapListener);
NimBLEServer *server = NimBLEDevice::createServer();
server->setCallbacks(&links, false);
bench::Options o;
o.vault = true;
o.lockControls = settings.lock;
bench_.begin(server, o);
bench_.setVault("the bench's secret: 42");
server->start();
bench::advertise(lab.spec().deviceName, false);
BLE_NOTE(Info, "pairing: %s, lock %s, %s may connect", b4v::methodName(settings.method), settings.lock ? "on" : "off",
settings.allowBondedOnly ? "bonded" : "anyone");
void tick(BleLab &lab) {
bench_.tick();
uint8_t c[3];
if (bench_.takeLed(c)) {
lab.claimLed(true);
rgbLedWrite(PIN_RGB, c[0], c[1], c[2]);
if (millis() - bondsAt > 1000) refreshBonds();
bool gesture(BleLab &, Gesture g, bool) {
if (links.comparing()) {
if (g == Gesture::Click) links.confirm(true);
else if (g == Gesture::LongPress) links.confirm(false);
return true;
bench_.button(g == Gesture::Click ? 1 : g == Gesture::DoubleClick ? 2 : 3);
return false;
const BleLabSpec kSpec{
"ble-lab-b4", "B4", "Pair & trust", "Bench B4", kViews, sizeof(kViews) / sizeof(kViews[0]), 0,
kCommands, sizeof(kCommands) / sizeof(kCommands[0]), setup, tick, gesture, nullptr,
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-b4 includes C++ source files covering pairing vs bonding, IO capabilities, Just Works · Passkey · Numeric Comparison, LE Secure Connections (ECDH), MITM protection, LTK & IRK, private addresses, filter accept list.