Something went wrong. Try again.
An experimental port of NetBSD, FreeBSD, OpenBSD, and XNU to unkernel unkernel.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339// SPDX-License-Identifier: MIT// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>// Bluetooth: a walk through the guest's Bluetooth with stock BlueZ, to try// the page's adapter (bluetooth.ts: Settings > Bluetooth) on a real device. bt.sh starts dbus and bluetoothd where// nothing has, waits for hci0, scans (a scan with no device added brings// up the page's notice with its Add Bluetooth device button), connects to// the device picked, prints its GATT services and characteristics with// their flags, reads the readable ones and then prints the notifications// of one. `./bt.sh shell` is bluetoothctl (with an address: connected to// that device, which is what the Terminal buttons of Settings > Bluetooth// run, bluetoothShell()) and `./bt.sh mon` is btmon, for what the walk does// not cover. Everything goes through bluetoothctl, so// the script is the same on Debian and Alpine.// Checked 2026-11-29 on a fake peripheral under Node (Debian as the image's// user, Alpine as root, both without a terminal, so without the questions);// not run in a browser or on a real device.import type { TerminalApp } from "../types.ts";
const README = `Bluetooth: try the guest's Bluetooth adapter on a BLE device.
The guest's adapter (hci0) reaches the devices this browser lets the pageuse. Add one first, or when the script asks: Settings > Bluetooth, Adddevice..., and pick it in the browser's list (the notice a scan brings uphas the same button). Any BLE device with standard servicesdoes: a heart rate strap, a fitness band, a sensor, or a phone runningnRF Connect as a peripheral.
./bt.sh scan, pick a device, connect, list its services, read its values, then print its notifications ./bt.sh AA:BB:CC:DD:EE:FF the same on a device by address ./bt.sh scan only scan and list ./bt.sh shell bluetoothctl (scan on, connect ADDR, menu gatt) ./bt.sh shell AA:BB:CC:DD:EE:FF bluetoothctl, connected to a device ./bt.sh mon btmon: the HCI packets, to see what fails
What cannot work here: pairing (the browser's system does it, so "pair"fails and the device disconnects), advertising and the peripheral role,classic Bluetooth (audio, serial profiles), and the services the browserhides from pages (keyboards and mice among them).`;
// No "${" and no backquote in the script: it is a template literal.const BT_SH = String.raw`#!/bin/sh# A walk through the guest's Bluetooth with BlueZ's bluetoothctl. Written by# the unkernel launcher's Bluetooth app.# ./bt.sh [ADDR | scan | shell [ADDR] | mon]# BT_SECONDS=N stops the notifications after N seconds (default: Ctrl-C).cd "$(dirname "$0")"B=$(printf '\033[1m') D=$(printf '\033[90m') N=$(printf '\033[0m')ESC=$(printf '\033') CR=$(printf '\r') TAB=$(printf '\t')SUDO=[ "$(id -u)" = 0 ] || SUDO=sudotmp=$(mktemp -d)trap 'rm -rf "$tmp"' EXITtrap 'exit 130' INT TERM
say() { printf '%s%s%s\n' "$B" "$*" "$N"; }note() { printf '%s%s%s\n' "$D" "$*" "$N"; }# bluetoothctl's output as plain lines: no colours, no prompts redrawn.PLAIN="s/$ESC\[[0-9;]*[a-zA-Z]//g; s/$CR\$//; s/.*$CR//"clean() { sed "$PLAIN"; }# GNU sed writes each line at once with -u; busybox's has no such option.U=sed -u '' </dev/null >/dev/null 2>&1 && U=-u
start_daemons() { pidof bluetoothd >/dev/null 2>&1 && return 0 note "Starting dbus and bluetoothd" if [ -f /etc/alpine-release ] || ! command -v service >/dev/null 2>&1; then $SUDO mkdir -p /run/dbus pidof dbus-daemon >/dev/null 2>&1 || $SUDO dbus-daemon --system d=/usr/lib/bluetooth/bluetoothd [ -x $d ] || d=/usr/libexec/bluetooth/bluetoothd $SUDO sh -c "$d >/dev/null 2>&1 &" else pidof dbus-daemon >/dev/null 2>&1 || $SUDO service dbus start >/dev/null $SUDO service bluetooth start >/dev/null fi}
have_adapter() { bluetoothctl show 2>/dev/null | grep -q 'Powered:'; }
wait_adapter() { i=0 while ! have_adapter; do i=$((i + 1)) if [ $i = 10 ]; then say "The guest has no Bluetooth adapter (no hci0)." echo "In the page: Settings > Bluetooth, and choose Browser Bluetooth as the" echo "adapter. It needs a browser with Web Bluetooth (Chrome or Edge)." note "Waiting for it. Ctrl-C stops." fi sleep 0.5 done bluetoothctl power on >/dev/null 2>&1 bluetoothctl show | clean | sed -n 's/^Controller \([0-9A-F:]*\).*/Adapter hci0, address \1/p'}
# The devices heard in a scan and the connected ones (which do not advertise), as "ADDR NAME"# lines in $tmp/devices; not those BlueZ only remembers.scan() { note "Scanning for 6 seconds" { bluetoothctl --timeout 6 scan on 2>&1 bluetoothctl devices Connected 2>/dev/null } | clean | sed -n 's/^.*Device \([0-9A-F:]\{17\}\).*/\1/p' | sort -u >"$tmp/heard" bluetoothctl devices 2>/dev/null | clean | sed -n 's/^Device \([0-9A-F:]\{17\}\) \{0,1\}/\1 /p' | grep -F -f "$tmp/heard" >"$tmp/devices" [ -s "$tmp/devices" ]}
list_devices() { i=0 while read -r a name; do i=$((i + 1)) printf ' %s%d%s %s %s\n' "$B" $i "$N" "$a" "$name" done <"$tmp/devices"}
scan_until_found() { until scan; do say "No device found." echo "The browser shows the guest only the devices you add. Use the notice's" echo "Add Bluetooth device button, or Settings > Bluetooth, Add device..., and" echo "pick the device in the browser's list." [ -t 0 ] || exit 1 printf '%s' "Enter scans again, Ctrl-C stops: " read -r _ || exit 1 done}
pick() { n=$(wc -l <"$tmp/devices") list_devices if [ "$n" = 1 ] || ! [ -t 0 ]; then addr=$(sed -n '1s/ .*//p' "$tmp/devices") return fi while :; do printf '%s' "Device to connect to (1-$n): " read -r k || exit 1 case $k in '' | *[!0-9]*) continue ;; esac addr=$(sed -n "$k"'s/ .*//p' "$tmp/devices") [ -n "$addr" ] && return done}
connect() { say "Connecting to $addr" bluetoothctl connect "$addr" 2>&1 | clean | grep -E 'Failed|Error|not available|successful' | sed 's/^/ /' if ! bluetoothctl info "$addr" 2>/dev/null | grep -q 'Connected: yes'; then say "The connection failed." echo "Is the device on, near, and not connected to something else?" note "./bt.sh mon in another terminal shows the HCI packets of a new attempt." exit 1 fi # The services come a moment after the link. i=0 while [ $i -lt 20 ]; do bluetoothctl gatt.list-attributes "$addr" 2>/dev/null | clean >"$tmp/attrs" grep -q '/char' "$tmp/attrs" && break i=$((i + 1)) sleep 0.5 done bluetoothctl info "$addr" | clean | grep -E '^.(Name|Battery Percentage|RSSI):' | sed "s/^$TAB/ /"}
# $tmp/chars: "PATH UUID FLAGS NAME" for each characteristic (FLAGS joined by commas, - for none).# $tmp/attrs holds list-attributes' records: a kind line, then the path, the UUID and the name.load_chars() { awk -v tab="$TAB" ' /^(Primary Service|Secondary Service|Characteristic|Descriptor)/ { kind = $1; f = 0; next } { sub("^" tab, ""); f++; if (f == 1) path = $0; else if (f == 2) uuid = $0; else if (f == 3 && kind == "Characteristic") print path " " uuid " " $0 } ' "$tmp/attrs" >"$tmp/charlist" # The flags: attribute-info of every characteristic in one session, keyed by service path and UUID. ( while read -r p _; do echo "gatt.attribute-info $p"; done <"$tmp/charlist" sleep 1.5 ) | bluetoothctl 2>&1 | clean | awk -v tab="$TAB" ' function out() { if (uuid != "") print svc "/" uuid " " (flags == "" ? "-" : flags) } /^Characteristic - / { out(); uuid = ""; svc = ""; flags = ""; next } { sub("^" tab, "") } /^UUID: / { if (match($0, /\([0-9a-f-]+\)$/)) uuid = substr($0, RSTART + 1, RLENGTH - 2); next } /^Service: / { svc = $2; next } /^Flags: / { flags = flags (flags == "" ? "" : ",") $2; next } END { out() } ' >"$tmp/flags" awk ' NR == FNR { fl[$1] = $2; next } { p = $1; u = $2; svc = p; sub("/char[0-9a-f]*$", "", svc); k = svc "/" u; $1 = ""; $2 = ""; sub("^ ", ""); print p " " u " " (k in fl ? fl[k] : "-") " " $0 } ' "$tmp/flags" "$tmp/charlist" >"$tmp/chars"}
show_tree() { say "Services and characteristics" awk -v tab="$TAB" -v b="$B" -v d="$D" -v n="$N" ' function short(u) { return u ~ /^0000....-0000-1000-8000-00805f9b34fb$/ ? "0x" substr(u, 5, 4) : u } NR == FNR { p = $1; fl[p] = $3; next } /^(Primary Service|Secondary Service|Characteristic|Descriptor)/ { kind = $1; f = 0; next } { sub("^" tab, ""); f++ if (f == 1) path = $0 else if (f == 2) uuid = $0 else if (f == 3) { if (kind == "Characteristic") printf " %s %s%s [%s]%s\n", $0, d, short(uuid), (path in fl ? fl[path] : "?"), n else if (kind == "Descriptor") printf " %s%s %s%s\n", d, $0, short(uuid), n else printf " %s%s%s %s%s%s\n", b, $0, n, d, short(uuid), n } } ' "$tmp/chars" "$tmp/attrs"}
# Read every readable characteristic (the first 16) in one session.read_values() { awk '$3 ~ /(^|,)read(,|$)/' "$tmp/chars" | head -n 16 >"$tmp/readable" [ -s "$tmp/readable" ] || { note "No readable characteristic."; return; } say "Values" ( while read -r p _; do echo "gatt.select-attribute $p" sleep 0.3 echo "gatt.read" sleep 1.2 done <"$tmp/readable" sleep 0.5 ) | bluetoothctl 2>&1 | clean >"$tmp/reads" # A read prints the value twice (the property change and the answer): keep one copy. awk -v d="$D" -v n="$N" ' function flush( i, h, same) { if (cur == "") return h = cnt if (cnt > 0 && cnt % 2 == 0) { same = 1; for (i = 1; i <= cnt / 2; i++) if (v[i] != v[i + cnt / 2]) same = 0; if (same) h = cnt / 2 } printf " %s\n", name[cur] if (err != "") printf " %s%s%s\n", d, err, n else if (cnt == 0) printf " %s(no answer)%s\n", d, n for (i = 1; i <= h; i++) printf " %s\n", v[i] } NR == FNR { p = $1; $1 = ""; $2 = ""; $3 = ""; sub("^ ", ""); name[p] = $0; next } /^Attempting to read / { flush(); cur = $4; cnt = 0; err = ""; next } /^Failed to read: / { err = $0; next } /^ [0-9a-f][0-9a-f]( |$)/ { if (cur != "") v[++cnt] = $0 } END { flush() } ' "$tmp/readable" "$tmp/reads"}
# The notifications of one characteristic: the heart rate if there is one, else the first that# notifies or indicates other than Service Changed.notifications() { line=$(awk '$3 ~ /notify|indicate/ && $2 ~ /^00002a37-/' "$tmp/chars" | head -n 1) [ -n "$line" ] || line=$(awk '$3 ~ /notify|indicate/ && $2 !~ /^00002a05-/' "$tmp/chars" | head -n 1) [ -n "$line" ] || { note "No characteristic notifies."; return; } p=$(echo "$line" | cut -d' ' -f1) say "Notifications of $(echo "$line" | cut -d' ' -f4-)" if [ -n "$BT_SECONDS" ]; then note "For $BT_SECONDS seconds."; else note "Ctrl-C stops."; fi ( echo "gatt.select-attribute $p" sleep 0.3 echo "gatt.notify on" if [ -n "$BT_SECONDS" ]; then sleep "$BT_SECONDS"; else while :; do sleep 3600; done; fi ) | bluetoothctl 2>&1 | sed $U -n "$PLAIN; /^Failed/p; /^ [0-9a-f][0-9a-f] /p; /^ [0-9a-f][0-9a-f]\$/p"}
case "$1" in-h | --help | help) cat README; exit 0 ;;esacstart_daemonscase "$1" inshell) wait_adapter if [ -n "$2" ]; then # A scan first: BlueZ connects only to a device it has heard. addr=$2 note "Scanning for 6 seconds" bluetoothctl --timeout 6 scan on >/dev/null 2>&1 say "Connecting to $addr" bluetoothctl connect "$addr" 2>&1 | clean | grep -E 'Failed|Error|not available|successful' | sed 's/^/ /' note "menu gatt, list-attributes, select-attribute UUID, read, write \"0x01 0x02\", notify on; back, disconnect; quit leaves" else note "scan on, devices, connect ADDR, menu gatt, list-attributes, select-attribute UUID, read, notify on; quit leaves" fi exec bluetoothctl ;;mon) command -v btmon >/dev/null 2>&1 || { echo "btmon is not installed"; exit 1; } exec $SUDO btmon ;;scan) wait_adapter scan_until_found list_devices exit 0 ;;esacwait_adapterif [ -n "$1" ]; then addr=$1 note "Scanning for 6 seconds" bluetoothctl --timeout 6 scan on >/dev/null 2>&1else scan_until_found pickficonnectif ! grep -q '/char' "$tmp/attrs"; then say "Connected, but the device shows no services." echo "The browser gives the page only the services named when the device is" echo "added: for a vendor's own, put their UUIDs in Settings > Bluetooth (custom" echo "service UUIDs), then forget the device and add it again." exit 1fiload_charsshow_treeread_valuesnotificationsechonote "Still connected. ./bt.sh shell is bluetoothctl (disconnect $addr ends the link)."`;
const app = { id: "bluetooth", title: "Bluetooth", desc: "Try the guest's Bluetooth on a BLE device: scan, connect, its GATT services, values and notifications, with BlueZ's bluetoothctl and btmon", // The Bluetooth rune (crafted). icon: { svg: '<path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="m7 7.5 10 9-5 4.5V3l5 4.5-10 9"/>' }, colors: ["#3b82f6", "#1e3a8a"], needs: { net: true, bluetooth: true }, packages: { debian: ["bluez"], alpine: ["bluez", "bluez-btmon", "dbus"] }, files: { README, "bt.sh": { content: BT_SH, mode: 0o755 }, }, commands: ["cat README", "./bt.sh"],} satisfies TerminalApp;export default app;
/** The app as bluetoothctl in a terminal, connected to a device when given its guest address (Settings > Bluetooth, the Terminal buttons). */export function bluetoothShell(addr?: string): TerminalApp { return { ...app, commands: [addr ? `./bt.sh shell ${addr}` : "./bt.sh shell"] };}