Bluetooth & BLE HID Subsystem
Bluetooth 5.0 LE scanning, GATT, and wireless BLE HID Keyboard emulation.
20. Bluetooth Subsystem API (Bluetooth)
The Bluetooth API provides native asynchronous hardware control over the 2.4 GHz Bluetooth controller across both ESP32-S3 (BLE 5.0) and classic ESP32 hardware.
20.1 Adapter & Lifecycle Management
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.enable([options]) | options: Object { mode?: "ble" | "classic" | "dual" } | Boolean | Powers on the radio and starts controller tasks. Defaults to "ble" on ESP32-S3. |
Bluetooth.disable() | None | Boolean | Powers down the 2.4 GHz RF circuitry without releasing controller memory, allowing seamless toggling. |
Bluetooth.getState() | None | String | Returns current power state: "poweredOff", "poweringOn", "poweredOn". |
Bluetooth.getCapabilities() | None | Object | Returns hardware capability object detailing supported silicon features. |
Bluetooth.hasFeature(name) | name: String | Boolean | Checks if a feature is supported: "ble", "ble5", "classic", "spp", "a2dp", "hfp", "codedPhy", "mesh", "l2capCoC". |
Bluetooth.getDeviceName() | None | String | Returns local GAP broadcast name. |
Bluetooth.setDeviceName(name) | name: String | undefined | Sets local GAP advertised device name. Persists to LittleFS. |
Bluetooth.getMacAddress() | None | String | Returns factory 6-byte hardware Bluetooth MAC address string ("XX:XX:XX:XX:XX:XX"). |
Bluetooth.setTxPower(level) | level: Number (dBm) | Boolean | Sets transmit output power (e.g. 9 for +9 dBm). |
Bluetooth.getTxPower() | None | Number | Returns current transmit power in dBm. |
Bluetooth.poll() | None | undefined | Pumps pending Bluetooth hardware event queues and dispatches discovery and notification callbacks to JavaScript. Automatically executed during System.delay(ms). |
Example: Adapter Initialization & Capability Check
// Check silicon capabilities dynamically
if (Bluetooth.hasFeature("ble5")) {
console.log("Device supports BLE 5.0 High-Throughput & Coded PHY!");
}
// Power on radio
Bluetooth.enable();
console.log("Radio State:", Bluetooth.getState());
console.log("Device Name:", Bluetooth.getDeviceName());
console.log("Bluetooth MAC:", Bluetooth.getMacAddress());
20.2 BLE Central: Scanner (Bluetooth.BLE.Scanner)
The Bluetooth.BLE.Scanner sniffs broadcast advertisements, beacons, and neighbor peripherals without establishing a GATT connection. It incorporates zero-heap circular duplicate debouncing (250 ms window) on Core 0 and a thread-safe telemetry queue with a DROP_OLDEST policy.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.BLE.Scanner.start([options]) | options: Object { timeout?: number, active?: boolean, interval?: number, window?: number } | Boolean | Starts LE scanning asynchronously. Defaults: timeout: 0 (continuous scan until stop()), active: true, interval: 100, window: 99 (99% continuous duty cycle). |
Bluetooth.BLE.Scanner.stop() | None | undefined | Halts scanning immediately to free radio airtime. |
Bluetooth.BLE.Scanner.isScanning() | None | Boolean | Returns true if an LE scan is currently active. |
Bluetooth.BLE.Scanner.on('discover', cb) | 'discover', cb(device) | undefined | Registers listener invoked for each discovered peripheral packet. |
Bluetooth.BLE.Scanner.off('discover') | 'discover' | undefined | Unregisters the discovery listener. |
Smartphone Discovery Note: Merely opening Bluetooth Settings on Android or iOS does not broadcast generic BLE peripheral advertisements (it operates in Classic inquiry scan or Central scanner mode). To test scanning a phone, install a BLE utility app such as nRF Connect for Mobile or LightBlue, navigate to the Advertiser tab, and tap Start Advertising.
Discovery events are dispatched to JavaScript automatically on every System.delay(ms) call or via explicit Bluetooth.poll() invocations.
Discovered Device Object Schema
Each discovered packet provides:
{
address: "24:6F:28:XX:XX:XX", // Peripheral String MAC address
addressType: "public", // "public" or "random"
name: "Heart Rate Monitor", // Local GAP name (or empty string)
rssi: -65, // Measured signal strength in dBm
advertisement: {
txPower: 9, // Advertised TX power in dBm
serviceUUIDs: ["180D"], // Array of advertised 16-bit or 128-bit service UUID strings
manufacturerData: Uint8Array, // Raw manufacturer specific data buffer (or null)
raw: Uint8Array // Complete advertising payload buffer (or null)
}
}
Example: Active BLE Peripheral Discovery
// Power on radio if not active
Bluetooth.enable();
// Subscribe to incoming advertisements
Bluetooth.BLE.Scanner.on("discover", function(device) {
console.log("Found device:", device.name || "(Unknown)", "| MAC:", device.address, "| RSSI:", device.rssi);
// Inspect service UUIDs
if (device.advertisement.serviceUUIDs.length > 0) {
console.log("Services:", device.advertisement.serviceUUIDs.join(", "));
}
});
// Start active scan for 10 seconds
Bluetooth.BLE.Scanner.start({ active: true, timeout: 10000 });
20.3 High-Level Utilities & Beacon Parser (Bluetooth.Utils)
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.Utils.parseBeacon(device) | device: Object | Object | null | Automatically decodes Apple iBeacon or Google Eddystone-URL frames from a discovered device packet. Returns null if the packet is not a recognised beacon. |
Decoded iBeacon Schema
{
type: "ibeacon",
uuid: "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0",
major: 100,
minor: 1,
txPower: -59, // Measured RSSI at 1 meter
distance: 1.45 // Estimated distance in meters (path-loss model)
}
Decoded Eddystone-URL Schema
{
type: "eddystone_url",
url: "https://kryonos.org",
txPower: -20 // Calibrated TX power at 0 meters
}
Example: Proximity Beacon Radar
Bluetooth.BLE.Scanner.on("discover", function(device) {
var beacon = Bluetooth.Utils.parseBeacon(device);
if (beacon) {
if (beacon.type === "ibeacon") {
console.log("iBeacon Found! UUID:", beacon.uuid, "Distance:", beacon.distance.toFixed(2) + "m");
} else if (beacon.type === "eddystone_url") {
console.log("Eddystone URL Beacon:", beacon.url);
}
}
});
Bluetooth.BLE.Scanner.start({ active: true, timeout: 15000 });
20.4 BLE Central: GATT Client Connections (Bluetooth.BLE)
Enables point-to-point connections with external BLE peripherals (smartwatches, heart rate monitors, OBD-II scanners, BLE sensors). Built on a robust handle-based architecture that protects against use-after-free corruption during asynchronous disconnects.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.BLE.connect(address, [options]) | address: String, options: Object | Promise<BluetoothRemoteDevice> | Connects to the peripheral at the given MAC. options: { timeout: Number, mtu: Number }. |
Bluetooth.BLE.getConnectedDevices() | None | Array<BluetoothRemoteDevice> | Returns all currently connected remote device instances. |
BluetoothRemoteDevice Properties & Methods
device.address: String MAC address.device.conn_handle: Integer connection handle.device.disconnect(): Closes the GATT link immediately. ReturnsBoolean.device.isConnected(): ReturnsBoolean.device.readRSSI(): Queries live signal strength in dBm. ReturnsNumber.device.requestMtu(desiredMtu): Requests ATT MTU exchange (up to 512 bytes). ReturnsBoolean.device.setPreferredPhy(options): Configures BLE 5.0 2M / Coded PHY (options: { txPhy: "1M"|"2M", rxPhy: "1M"|"2M" }). ReturnsBoolean.device.getServices([serviceUUIDs]): ReturnsPromise<Array<GattService>>.device.on('disconnect', callback): Subscribes to unexpected disconnection events.
GattService Properties & Methods
service.uuid: 16-bit or 128-bit service UUID string.service.isPrimary: Alwaystrue.service.getCharacteristics([uuids]): ReturnsPromise<Array<GattCharacteristic>>.
GattCharacteristic Properties & Methods
char.uuid: Characteristic UUID string.char.properties: Array of supported properties (e.g.['read', 'write', 'notify']).char.read(): Reads the current characteristic value. ReturnsPromise<Uint8Array>.char.write(data, [withoutResponse]): Writes aUint8Arrayor String. ReturnsPromise<Boolean>.char.startNotifications(): Subscribes to CCCD indications/notifications. ReturnsPromise<Boolean>.char.stopNotifications(): Unsubscribes from CCCD notifications. ReturnsPromise<Boolean>.char.on('valueChange', callback): Dispatches whenever incoming notification packets arrive. Callback signature:cb(data: Uint8Array).char.off('valueChange', [callback]): Removes notification listeners.char.getDescriptors(): ReturnsPromise<Array<GattDescriptor>>.
GattDescriptor Properties & Methods
desc.uuid: Descriptor UUID (e.g."2902").desc.read(): ReturnsPromise<Uint8Array>.desc.write(data): Writes raw descriptor payload. ReturnsPromise<Boolean>.
Example: Heart Rate Monitor Connection & Notifications
Bluetooth.BLE.connect("C0:4E:30:11:22:33", { timeout: 5000, mtu: 512 })
.then(function(device) {
console.log("Connected to:", device.address);
return device.getServices(["180D"]); // Heart Rate Service
})
.then(function(services) {
return services[0].getCharacteristics(["2A37"]); // Heart Rate Measurement
})
.then(function(chars) {
var hrChar = chars[0];
hrChar.on("valueChange", function(data) {
console.log("Heart Rate BPM:", data[1]);
});
return hrChar.startNotifications();
})
.catch(function(err) {
console.error("BLE Connect failed:", err.message);
});
20.5 BLE Peripheral: Local GATT Server (Bluetooth.BLE.Server)
Allows the KryonOS device to broadcast custom GATT services and characteristics that neighbor smartphones or computers can read and subscribe to.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.BLE.Server.createService(uuid) | uuid: String | GattLocalService | Creates and registers a local primary GATT service. |
Bluetooth.BLE.Server.start() | None | Boolean | Starts hosting all registered local GATT services. |
Bluetooth.BLE.Server.stop() | None | Boolean | Stops hosting GATT server. |
GattLocalService.addCharacteristic(options)
Options schema:
{
uuid: "2A24", // Characteristic UUID
properties: ["read", "notify"], // Supported permissions: 'read', 'write', 'notify', 'indicate'
value: new Uint8Array([0x01, 0x02]) // Initial value (optional)
}
Returns a handle object:
char.uuid: Characteristic UUID string.char.setValue(data, [notify = false]): Updates the local value and optionally pushes a notify/indicate packet to connected clients.
20.6 BLE Broadcaster & Advertiser (Bluetooth.BLE.Advertiser)
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.BLE.Advertiser.start(options) | options: Object | Boolean | Broadcasts standard GAP advertisement packets. options: { name, serviceUUIDs, intervalMin, intervalMax }. |
Bluetooth.BLE.Advertiser.startExtended(options) | options: Object | Boolean | (ESP32-S3 BLE 5.0) Transmits extended advertising payloads up to 251 bytes. |
Bluetooth.BLE.Advertiser.stop() | None | Boolean | Halts advertising transmission. |
Bluetooth.BLE.Advertiser.isAdvertising() | None | Boolean | Returns true if advertising is currently active. |
Example: Broadcasting Local GATT Service
var srv = Bluetooth.BLE.Server.createService("180A");
var modelChar = srv.addCharacteristic({
uuid: "2A24",
properties: ["read"],
value: new Uint8Array([0x4B, 0x72, 0x79, 0x6F, 0x6E]) // "Kryon"
});
Bluetooth.BLE.Server.start();
Bluetooth.BLE.Advertiser.start({
name: "KryonOS Deck",
serviceUUIDs: ["180A"]
});
20.7 BLE HID Wireless Keyboard (Bluetooth.BLE.Keyboard)
The Bluetooth.BLE.Keyboard API turns the ESP32 (LilyGO T-Deck Plus, Cardputer) into a wireless Human Interface Device (HID) over GATT keyboard that connects directly to smartphones (iOS / Android), tablets, and PCs.
| Method | Parameters | Return Type | Description |
|---|---|---|---|
Bluetooth.BLE.Keyboard.start([deviceName]) | deviceName: String | Boolean | Initializes the HID service, registers keyboard descriptors, sets Just Works bonding security, and starts advertising. Defaults to "T-Deck Keyboard". |
Bluetooth.BLE.Keyboard.stop() | None | undefined | Halts advertising and stops the HID keyboard server. |
Bluetooth.BLE.Keyboard.isConnected() | None | Boolean | Returns true if a host (phone/PC) is connected and paired. |
Bluetooth.BLE.Keyboard.write(charOrString) | text: String | Boolean | Converts ASCII characters to USB HID keycodes and transmits them with automatic shift modifiers. |
Bluetooth.BLE.Keyboard.sendKey(keycode, [mod]) | keycode: Number, mod: Number | Boolean | Sends a raw 8-byte USB HID keyboard report followed by an automatic release. |
Bluetooth.BLE.Keyboard.sendSpecial(name) | name: String | Boolean | Sends named keys: "enter", "backspace", "tab", "space", "esc", "up", "down", "left", "right", "home", "end". |
Bluetooth.BLE.Keyboard.sendMedia(name) | name: String | Boolean | Sends consumer control media reports: "play", "pause", "next", "prev", "mute", "volup", "voldown". |
Example: Wireless Typing to Phone
Bluetooth.BLE.Keyboard.start("T-Deck Plus Keyboard");
// Listen for physical keyboard input
while (true) {
var ev = Keyboard.getEvent();
if (ev) {
if (ev.name === "BACKSPACE") {
Bluetooth.BLE.Keyboard.sendSpecial("backspace");
} else if (ev.char && ev.char.length > 0) {
Bluetooth.BLE.Keyboard.write(ev.char);
}
}
System.delay(20);
}
20.8 Periodic Sync & Raw L2CAP Channels (Bluetooth.BLE.Periodic, Bluetooth.BLE.L2CAP)
Bluetooth.BLE.Periodic.sync(address, sid): Synchronizes with external sensor periodic telemetry trains without requiring a GATT link (ESP32-S3 BLE 5.0).Bluetooth.BLE.Periodic.on('data', callback): Receives periodic sensor updates:cb(data, rssi).device.createL2capChannel(psm): Establishes a raw, high-throughput binary streaming channel bypassing ATT MTU overhead.Bluetooth.BLE.L2CAP.listen(psm): Registers a server listening socket for incoming L2CAP connections.
20.9 Security, Pairing & Mesh (Bluetooth.BLE.Security, Bluetooth.Mesh)
Bluetooth.BLE.Security.setPairingMode(mode):"none"|"justWorks"|"passkey"|"numericComparison".Bluetooth.BLE.Security.setStaticPasskey(pinCode): Configures a 6-digit numeric passkey.Bluetooth.BLE.Security.getBondedDevices(): Returns array of bonded peer MAC addresses.Bluetooth.BLE.Security.removeBond(address): Removes bonding keys from NVS.Bluetooth.Mesh.init(config): Initializes the ESP-BLE-MESH stack (relay,friend,lowPower,proxy).Bluetooth.Mesh.startProvisioning(bearer): Places node into unprovisioned broadcast mode.Bluetooth.Mesh.isProvisioned(): ReturnsBoolean.Bluetooth.Mesh.send(target, appKeyIndex, modelId, opcode, payload): Transmits routed mesh packets.Bluetooth.Mesh.reset(): Purges mesh credentials and network keys from NVS.
20.10 Bluetooth Classic Subsystems (Bluetooth.Classic)
Hardware Support: Classic Bluetooth BR/EDR profiles (SPP, A2DP, HFP, HID) are supported exclusively on base ESP32 hardware (e.g. CYD / WROOM). On ESP32-S3 targets, Bluetooth.Classic.isSupported evaluates to false, and calling Classic methods safely returns or rejects with an UnsupportedHardwareError without crashing.
Bluetooth.Classic.Discovery:start([timeoutMs])/stop(): Legacy inquiry scan.on('deviceFound', callback): Receives{ address, name, cod, rssi }.
Bluetooth.Classic.Serial(RFCOMM):connect(address, channel): Connects to legacy serial devices (HC-05, OBD-II scanners, GPS). ReturnsPromise<Socket>.listen(channel): Registers a virtual serial server socket.
Bluetooth.Classic.Audio(A2DP & AVRCP):startSink()/stopSink(): Turns the device into a Bluetooth speaker, streaming received audio toAudioEngineand I2S DAC.startSource(address)/stopSource(): Streams internal audio playback to Bluetooth headphones.sendControl(action): Sends AVRCP commands:"play","pause","next","previous","volumeUp","volumeDown".
Bluetooth.Classic.Telephony(HFP/HSP):init(options),connect(address),dial(number),answer(),hangup().setSpeakerVolume(0-15),setMicVolume(0-15).
Bluetooth.Classic.HID:connectHost(address): Connects legacy gamepads and controllers.startDevice(descriptor)/sendReport(reportId, data): Emulates a Bluetooth gamepad or keyboard.