diff --git a/AGENTS.md b/AGENTS.md index 8430dfd..e5c63b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,7 @@ All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7` - `./scripts/prune-rootfs-packages.sh world|purge` — removes Wayland-only, Rust-based, and retired packages from a target rootfs inside the build container. - `./scripts/build-bananarchy-daemons.sh` — cross-builds the three compiled ARM idle daemons (`bananarchy-lid`, `bananarchy-cover-idle`, `bananarchy-volume-keys`) from `src/bananarchy-daemons/`; `--check` validates the ARM ELF artifacts and overlay sync. No Python-based daemon runs in the idle system. - `./scripts/build-lk2nd-beatles.sh` — cross-builds all three beatles lk2nd images (normal, diagnostic and display; the display image is the flasher default) from the pinned upstream lk2nd commit plus `bootloader/lk2nd/nokia-beatles.patch` in rootless Docker (`--check` validates all three shipped images, `--only normal|diagnostic|display` builds one, `--force-panel-init` forces the panel replay, `--with-display` enables SPI display during boot). Offline validators: `scripts/check-lk2nd-beatles.py` and `scripts/test-lk2nd-beatles-port.py`. -- `./scripts/test-webarchy-renderer.py` and `./scripts/test-idle-blank-lock.py` — host unit/integration tests for the Webarchy renderer profile and the idle-blank screenlock wiring (both also run by `check-rebuild.sh`). +- `./scripts/test-webarchy-renderer.py`, `./scripts/test-idle-blank-lock.py` and `./scripts/test-bluetooth-scan.py` — host unit/integration tests for the Webarchy renderer profile, the idle-blank screenlock wiring and the Bluetooth discovery parser (all also run by `check-rebuild.sh`). - `./scripts/check-rebuild.sh` — offline preflight for a clean clone (syntax, package list, plugin artifacts, overlay sync, SMS long-message rendering guard, ignored local agent config, Docker, version helper). - `./scripts/sync-prebuilt-overlay.sh [--check]` — mirrors `prebuilt/` artifacts into `overlay/rootfs/`; `--check` only reports drift. - `./scripts/bootstrap-flash-deps.sh` — installs `pyusb` and `pyserial` into the gitignored `.flash-deps/` directory for `flash-edl.py`. diff --git a/CHANGELOG.md b/CHANGELOG.md index b184d09..1a21137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ Release versions follow the `
` format (where `2026` is `a`, Work since `a1108` has focused on reliable 2720 Flip hardware support and a reproducible boot/flash path. Earlier incremental and superseded diagnostic entries are consolidated here. +### Bluetooth scanning + +- **Scan found no devices**: the Bluetooth tab ran `bluetoothctl --timeout 15 scan on` with stdout discarded and then queried `bluetoothctl devices` from a second process. BlueZ discovery belongs to the D-Bus client that started it: when the scanning client exits, discovery stops and unpaired devices may be removed before the follow-up query, so a fresh scan legitimately produced an empty list on the 2720 Flip's WCNSS controller. `networks.so` now captures the discovery stream, parses ANSI-coloured `[NEW]`/`[CHG]` device and name/alias lines (`parseBtScanDevices()`), merges them with the persistent `bluetoothctl devices` list, powers the controller on when `bluetoothctl show` reports `Powered: no`, and falls back to a plain `scan on` if `--timeout` is unsupported. `isBtEnabledFast()` no longer depends solely on `/run/bluetoothd.pid`. `scripts/test-bluetooth-scan.py` validates the parser on the host and `check-rebuild.sh` guards the rebuilt `networks.so`. The `nokia-argon` path keeps the same paired-device and OBEX behaviour. + ### Screenlock daemon on idle blank - **Screenlock never triggered on blank**: dwm's native idle blanking called `bananarchy-idle-blank.sh off`, which only powered the panel down through `sxmo_wm.sh display off`. It never entered the Sxmo state machine, and the session no longer starts an `idle_locker` job, so `locker.so` received no `LOCK_BLANK` and the phone stayed unlocked after blanking. `bananarchy-idle-lock.sh` now arms a trusted `sxmo_state.sh set screenoff` transition after 30 seconds of dark panel (`xlocker screenoff` -> `LOCK_BLANK`), configurable with `bananarchy-idle-lock.sh get|label|set ` (`~/.config/sxmo/idle_lock_delay`; `0` locks immediately, `off` restores blank-without-passcode). `bananarchy-idle-blank.sh off/on`, `bananarchy-screen-wake.sh` and `sxmo_hook_unlock.sh` cancel the pending lock on every wake, and the transition is skipped if the panel is already back on, so a quick key press still returns to the unlocked desktop on `nokia-argon` as well as the 2720 Flip. `scripts/test-idle-blank-lock.py` exercises arming, cancellation and both wake paths against stubbed Sxmo commands, and `check-rebuild.sh` guards the wiring. diff --git a/MANUAL.md b/MANUAL.md index a3ae1b5..0042b5e 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -216,7 +216,7 @@ All twenty-five phone applications are compiled as shared-object plugins (`/usr/ - **Three connectivity tabs (`Left`/`Right` or `1`–`3`)**: - **`1:Wi-Fi`**: toggle Wi-Fi radio, rescan (`*`), toggle **Wi-Fi Hotspot**, and connect to WPA2/open networks with a multi-tap password dialog (`*` toggles password visibility). - **`2:Cell/APN`**: toggle **Mobile Data** (configuring the QMI `bam-dmux` `wwan0` static IPv4 bearer, default route, and DNS automatically), inspect `wwan0` IPv4 status, edit **APN Configuration**, and toggle **USB Tethering**. - - **`3:Bluetooth`**: toggle **Bluetooth Power** (showing a live `ON (N Active)` badge and starting `/usr/bin/bananarchy-bt-obex`), toggle **Discoverable** (`ON (Visible)` vs `OFF (Hidden)`, persisted in `~/.config/sxmo/bt_discoverable`), edit the **Bluetooth Device Name** (`Name: [Edit]`, persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname), monitor the live **OBEX File Receiver** widget (`#` opens `~/Downloads/` in `xfiles`), scan nearby devices (`*` or `Scan`, 15-second discovery scan), and manage paired/discovered devices. Active connections are pinned to the top of the device list with a green border and live profile/battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and the device actions menu (`Center OK`) provides **Connect Device**, **Disconnect Device**, **Pair & Trust Device**, **Switch Audio (A2DP / HSP-HFP)**, and **Forget / Remove Device**. Supports Bluetooth **A2DP** (`sbc_xq`, `aac`, `ldac`, `aptx`, `aptx_hd`) and **HSP/HFP** (`mSBC` / `CVSD`) audio (routable via `xdrawer`, `dmenu Audio`, and `sxmo_audio.sh`), **HID keyboards** (automatically switching `fcitx5-t9` and NeoUI/plugin inputs to `[KBD]` direct QWERTY mode so `0-9`, `*`, `#`, `Shift+0-9`, and letters bypass T9 multi-tap and preedit popups), **HID mice** (automatically showing the X11 mouse cursor whenever a mouse is connected and hiding it when disconnected), and **HID gamepads** (automatically bridged to the phone's D-Pad, softkeys, and action keys via `/dev/uinput`). + - **`3:Bluetooth`**: toggle **Bluetooth Power** (showing a live `ON (N Active)` badge and starting `/usr/bin/bananarchy-bt-obex`), toggle **Discoverable** (`ON (Visible)` vs `OFF (Hidden)`, persisted in `~/.config/sxmo/bt_discoverable`), edit the **Bluetooth Device Name** (`Name: [Edit]`, persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname), monitor the live **OBEX File Receiver** widget (`#` opens `~/Downloads/` in `xfiles`), scan nearby devices (`*` or `Scan`, 15-second discovery scan), and manage paired/discovered devices. The scan keeps the `bluetoothctl scan on` output and parses its `[NEW] Device ` / `[CHG] Device ... Name:` lines, because BlueZ stops client-scoped discovery when `bluetoothctl` exits and can drop unpaired devices before a separate `bluetoothctl devices` query runs; the controller is also powered on automatically if `bluetoothctl show` reports `Powered: no`. Active connections are pinned to the top of the device list with a green border and live profile/battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and the device actions menu (`Center OK`) provides **Connect Device**, **Disconnect Device**, **Pair & Trust Device**, **Switch Audio (A2DP / HSP-HFP)**, and **Forget / Remove Device**. Supports Bluetooth **A2DP** (`sbc_xq`, `aac`, `ldac`, `aptx`, `aptx_hd`) and **HSP/HFP** (`mSBC` / `CVSD`) audio (routable via `xdrawer`, `dmenu Audio`, and `sxmo_audio.sh`), **HID keyboards** (automatically switching `fcitx5-t9` and NeoUI/plugin inputs to `[KBD]` direct QWERTY mode so `0-9`, `*`, `#`, `Shift+0-9`, and letters bypass T9 multi-tap and preedit popups), **HID mice** (automatically showing the X11 mouse cursor whenever a mouse is connected and hiding it when disconnected), and **HID gamepads** (automatically bridged to the phone's D-Pad, softkeys, and action keys via `/dev/uinput`). 13. **Ringtones, notification/SMS sounds, and ringer manager (`ringtones.so` / `xringtones`)**: - **Open**: select **Ringtones** from the System, Config, or Audio menu, select **Notification Sound** from the **Notifications (`Notifs`)** menu, or run `xringtones [--notif] [file]`. diff --git a/README.md b/README.md index 73bc461..10fbb21 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs - **Phone dialer (`xdialer`), call log (`xcalllog`), and call screen (`xcallscreen`)**: press any digit on the home screen to start dialing with live T9 contact matching, run interactive carrier USSD codes (`*100#`, etc.), or type `*#06#` to inspect both IMEIs. When two SIM cards are active in Dual-SIM Dual Standby (DSDS), placing a call or running a USSD code prompts to choose between `SIM 1` and `SIM 2`. Incoming and active calls on either SIM (as well as incoming/active VoIP calls from `xsip` and `xtox`) open a dedicated call screen with an active `[SIM 1]`/`[SIM 2]`/`[SIP]`/`[TOX]` badge, earpiece/speaker switching, microphone mute, DTMF keypad, and one-key normalized WAV call recording (`~/Recordings/rec_HHMMSS_.wav`). The call log includes a 5-tab view (`All`, `Miss`, `In`, `Out`, `Spam`) with integrated anti-spam number blocking (`~/.config/sxmo/block.tsv`) that automatically hangs up blocked callers and logs them to the `Spam` tab without triggering missed-call notifications. - **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view that renders and scrolls full-length concatenated/Unicode (`UCS-2`) messages line by line, a multi-tap message composer with an encoding-aware GSM-7/UCS-2 segment counter and outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration. - **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, instant default SIM switching (`Set as Default SIM (Calls/SMS)`), full Primary/Secondary GW (`4G/Data`) slot swapping (`Make Primary GW (4G/Data Swap)`), SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console. -- **Networks and Bluetooth manager (`xnetworks`) with OBEX file transfer (`bananarchy-bt-obex`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing, with built-in Bluetooth OBEX Object Push file reception (`~/Downloads` status and receiver toggle in the `Bluetooth` tab) and **Send via Bluetooth** in `xfiles`. +- **Networks and Bluetooth manager (`xnetworks`) with OBEX file transfer (`bananarchy-bt-obex`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing, with built-in Bluetooth OBEX Object Push file reception (`~/Downloads` status and receiver toggle in the `Bluetooth` tab) and **Send via Bluetooth** in `xfiles`. Bluetooth discovery parses the live `bluetoothctl scan on` stream instead of relying on a second `devices` query, so nearby unpaired devices survive the end of a scan. - **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), Bluetooth file sharing, music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, **Send via Bluetooth** OBEX file push to paired/discovered devices, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), image viewer, and dedicated monophonic ringtone viewer (`RingtoneView` for Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` with graphical piano-roll pitch contour, note sequence viewer, live audio preview, and one-key assignment as call ringtone or notification/SMS sound — plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio, tracker, or monophonic melody file as call ringtone or notification/SMS sound), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, `NRT`, `RTTTL`, `RTX`, `EMY`, `IMY`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. - **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xkopher`, `webarchy`)**: - **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) supporting both account-registered calling (with Digest MD5 authentication and standby `REGISTER` keepalive) and direct accountless P2P SIP URI calling (`user@host[:port]` or `sip:user@host[:port]`), RFC 3263 DNS `SRV` (`_sip._udp.`) proxy discovery and dialog routing, RFC 6189 **ZRTP** media-path Diffie-Hellman (`DH3k`/`DH2k`) key agreement and RFC 3711 **SRTP** (`AES-128-CM` + `HMAC-SHA1-80`) voice encryption with a 4-character `SAS` verification code, incoming `INVITE` ringing and call handling integrated with `xcallscreen` (`[SIP/]` / `[SIP/:]`), multi-codec wideband and narrowband RTP/SRTP audio (`Opus` 16 kHz / 48 kHz RTP clock with in-band FEC, `ITU-T G.722` 16 kHz wideband SB-ADPCM, `G.711 PCMU`/`PCMA` 8 kHz, `GSM 06.10` Full Rate 8 kHz, `ITU-T G.726-32` 8 kHz ADPCM, `IMA ADPCM DVI4` 8/16 kHz, and `L16` uncompressed 16-bit PCM 8/16 kHz) with per-account and direct-mode codec preference selection, and RFC 2833 / RFC 4733 DTMF. diff --git a/overlay/rootfs/usr/lib/dwm/plugins/networks.so b/overlay/rootfs/usr/lib/dwm/plugins/networks.so index 6c989cf..1942652 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/networks.so and b/overlay/rootfs/usr/lib/dwm/plugins/networks.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so index 6c989cf..1942652 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so differ diff --git a/scripts/check-rebuild.sh b/scripts/check-rebuild.sh index f7c2bbe..ba9eb71 100755 --- a/scripts/check-rebuild.sh +++ b/scripts/check-rebuild.sh @@ -1158,6 +1158,28 @@ if [ -x "$BASE_DIR/scripts/test-idle-blank-lock.py" ] && \ fail "host idle-blank screenlock integration test failed" fi +echo "[check] Bluetooth scan stream parsing..." +NET_SRC="$BASE_DIR/src/dwm-plugins/networks_plugin.cpp" +NET_SO="$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so" +for token in 'parseBtScanDevices' 'queryBtDevices(const std::string& scanRaw' \ + 'queryBtDevices(scanRaw)' 'bluetoothctl power on' \ + 'scan on 2>/dev/null'; do + if ! grep -qF "$token" "$NET_SRC"; then + fail "networks_plugin.cpp is missing the Bluetooth scan fix: $token" + fi +done +if ! strings "$NET_SO" 2>/dev/null | \ + grep -qF 'timeout 16 bluetoothctl --timeout 15 scan on'; then + fail "shipped networks.so is stale: rebuild with scripts/build-sxmo-x11.sh" +fi +if [ ! -x "$BASE_DIR/scripts/test-bluetooth-scan.py" ]; then + fail "missing host unit test scripts/test-bluetooth-scan.py" +fi +if command -v g++ >/dev/null 2>&1 && \ + ! "$BASE_DIR/scripts/test-bluetooth-scan.py" >/dev/null 2>&1; then + fail "host Bluetooth scan parser test failed" +fi + if [ "$FAILURES" -ne 0 ]; then echo "[check] $FAILURES check(s) failed." exit 1 diff --git a/scripts/test-bluetooth-scan.py b/scripts/test-bluetooth-scan.py new file mode 100755 index 0000000..5f9c7f8 --- /dev/null +++ b/scripts/test-bluetooth-scan.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Host unit test for the networks plugin's Bluetooth scan-stream parser. + +The plugin is cross-compiled for armv7; this test extracts the pure parser +functions and compiles them on the host with a stubbed BtDeviceEntry/trimStr, +so a BlueZ discovery stream can be validated without a controller. +""" +import pathlib +import subprocess +import sys +import tempfile + +BASE = pathlib.Path(__file__).resolve().parent.parent +SOURCE = BASE / "src/dwm-plugins/networks_plugin.cpp" +FUNCTIONS = ( + "std::string stripBtAnsi", + "bool isBluetoothMac", + "std::vector parseBtScanDevices", +) + +HEAD = r''' +#include +#include +#include +#include +#include +#include +#include + +struct BtDeviceEntry { + std::string mac; + std::string name; + bool paired = false; + bool connected = false; +}; + +std::string trimStr(const std::string& s) { + size_t a = 0; + size_t b = s.size(); + while (a < b && std::isspace(static_cast(s[a]))) ++a; + while (b > a && std::isspace(static_cast(s[b - 1]))) --b; + return s.substr(a, b - a); +} + +#define CHECK(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); return 1; } \ +} while (0) + +''' + +MAIN = r''' +int main() { + CHECK(isBluetoothMac("AA:BB:CC:DD:EE:01")); + CHECK(isBluetoothMac("de:ad:be:ef:00:01")); + CHECK(!isBluetoothMac("AA-BB-CC-DD-EE-01")); + CHECK(!isBluetoothMac("AA:BB:CC:DD:EE")); + CHECK(!isBluetoothMac("ZZ:BB:CC:DD:EE:01")); + std::string raw = + "\033[0;94m[NEW]\033[0m Device AA:BB:CC:DD:EE:01 Kitchen Speaker\r\n" + "[CHG] Device AA:BB:CC:DD:EE:01 RSSI: -55\n" + "\033[0;93m[CHG]\033[0m Device AA:BB:CC:DD:EE:01 Name: Living Room\n" + "[NEW] Device 11:22:33:44:55:66 11:22:33:44:55:66\n" + "[NEW] Device DE:AD:BE:EF:00:01 Headset\n" + "[DEL] Device 99:88:77:66:55:44 Gone\n" + "[NEW] Device ZZ:BB:CC:DD:EE:01 Broken\n" + "Discovery started\n"; + std::vector found = parseBtScanDevices(raw); + CHECK(found.size() == 3); + CHECK(found[0].mac == "AA:BB:CC:DD:EE:01"); + CHECK(found[0].name == "Living Room"); + CHECK(found[1].mac == "11:22:33:44:55:66"); + CHECK(found[1].name == "11:22:33:44:55:66"); + CHECK(found[2].mac == "DE:AD:BE:EF:00:01"); + CHECK(found[2].name == "Headset"); + CHECK(stripBtAnsi("\033[0;94mOK\033[0m") == "OK"); + std::puts("bluetooth scan parser: ok"); + return 0; +} +''' + + +def extract(name, text): + start = text.find("\n" + name + "(") + if start < 0: + raise SystemExit("missing function %s in networks_plugin.cpp" % name) + start += 1 + depth = 0 + opened = False + for pos in range(start, len(text)): + if text[pos] == "{": + depth += 1 + opened = True + elif text[pos] == "}": + depth -= 1 + if opened and depth == 0: + return text[start:pos + 1] + "\n" + raise SystemExit("unterminated function %s" % name) + + +def main(): + text = SOURCE.read_text(encoding="utf-8") + funcs = "\n".join(extract(name, text) for name in FUNCTIONS) + harness = HEAD + funcs + MAIN + with tempfile.TemporaryDirectory(prefix="bananarchy-bt-scan-") as tmp: + root = pathlib.Path(tmp) + src = root / "bt_scan_test.cpp" + exe = root / "bt_scan_test" + src.write_text(harness, encoding="utf-8") + build = subprocess.run( + ["g++", "-std=c++20", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], + capture_output=True, text=True) + if build.returncode: + sys.stderr.write(build.stderr) + return 1 + probe = subprocess.run([str(exe)], capture_output=True, text=True) + if probe.returncode: + sys.stderr.write(probe.stderr) + return 1 + print(probe.stdout.strip()) + if "queryBtDevices(scanRaw)" not in text or \ + "scan on 2>/dev/null" not in text: + sys.stderr.write("FAIL: scan output is not fed into the device list\n") + return 1 + print("bluetooth scan wiring: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/dwm-plugins/networks_plugin.cpp b/src/dwm-plugins/networks_plugin.cpp index 2ba8390..29923bb 100644 --- a/src/dwm-plugins/networks_plugin.cpp +++ b/src/dwm-plugins/networks_plugin.cpp @@ -245,7 +245,13 @@ bool isWifiEnabledFast() { bool isBtEnabledFast() { if (::access("/run/bluetoothd.pid", F_OK) != 0) { - return false; + // supervise-daemon normally writes /run/bluetoothd.pid, but a manually + // started bluetoothd (or a different OpenRC supervisor) may not. Ask + // BlueZ directly before declaring the controller absent. + std::string show = runCaptureCmd("timeout 2 bluetoothctl show 2>/dev/null"); + if (show.find("Powered:") == std::string::npos || + show.find("Powered: no") != std::string::npos) + return false; } std::string out = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null"); if (out.find("Soft blocked: yes") != std::string::npos || @@ -420,7 +426,87 @@ const char* iconForBtDevice(const BtDeviceEntry& d) { } } -std::vector queryBtDevices() { +// BlueZ discovery is tied to the D-Bus client that called StartDiscovery. +// A short-lived `bluetoothctl scan on` can therefore drop every unpaired +// device as soon as it exits, and a following `bluetoothctl devices` query +// (from a different process) legitimately returns an empty list. Keep the +// scan stream itself: it contains "[NEW] Device AA:BB:... Name" and +// "[CHG] Device AA:BB:... Name: ..." lines for every device seen. +std::string stripBtAnsi(const std::string& in) { + std::string out; + out.reserve(in.size()); + for (size_t i = 0; i < in.size();) { + if (in[i] == '\033' && i + 1 < in.size() && in[i + 1] == '[') { + size_t j = i + 2; + while (j < in.size() && + (std::isdigit(static_cast(in[j])) || in[j] == ';' || + in[j] == '?' || in[j] == '!' || in[j] == '<' || in[j] == '>' || + in[j] == '=')) + ++j; + if (j < in.size()) + ++j; + i = j; + continue; + } + if (in[i] != '\r') + out.push_back(in[i]); + ++i; + } + return out; +} + +bool isBluetoothMac(const std::string& s) { + if (s.size() != 17) + return false; + for (size_t i = 0; i < s.size(); ++i) { + if (i % 3 == 2) { + if (s[i] != ':') + return false; + } else if (!std::isxdigit(static_cast(s[i]))) { + return false; + } + } + return true; +} + +std::vector parseBtScanDevices(const std::string& raw) { + std::vector out; + std::unordered_map byMac; + std::istringstream ss(stripBtAnsi(raw)); + std::string line; + while (std::getline(ss, line)) { + size_t pos = line.find("Device "); + if (pos == std::string::npos) + continue; + std::string mac = trimStr(line.substr(pos + 7, 17)); + if (!isBluetoothMac(mac)) + continue; + bool removed = (line.find("[DEL]") != std::string::npos); + std::string rest = trimStr(line.substr(pos + 7 + 17)); + std::string name; + if (rest.rfind("Name:", 0) == 0 || rest.rfind("Alias:", 0) == 0) { + name = trimStr(rest.substr(rest.find(':') + 1)); + } else if (!rest.empty() && rest.find(':') == std::string::npos && + rest.rfind("RSSI", 0) != 0 && rest.rfind("TxPower", 0) != 0) { + name = rest; + } + auto it = byMac.find(mac); + if (it == byMac.end()) { + if (removed) + continue; + BtDeviceEntry d; + d.mac = mac; + d.name = name.empty() ? mac : name; + byMac[mac] = out.size(); + out.push_back(d); + } else if (!name.empty()) { + out[it->second].name = name; + } + } + return out; +} + +std::vector queryBtDevices(const std::string& scanRaw = "") { std::vector out; std::unordered_set pairedMacs; std::unordered_set connectedMacs; @@ -483,6 +569,21 @@ std::vector queryBtDevices() { if (e.name.size() == 17 && e.name[2] == '-' && e.name[5] == '-') return true; return false; }; + // Merge what the scan actually saw with the persistent device list. BlueZ + // may have dropped unpaired devices when the discovery client exited, so + // the scan stream is the authoritative source for a fresh Scan action. + for (const auto& found : parseBtScanDevices(scanRaw)) { + bool known = false; + for (auto& d : out) { + if (d.mac != found.mac) continue; + known = true; + if (isRawMacName(d) && !isRawMacName(found)) + d.name = found.name; + break; + } + if (!known) + out.push_back(found); + } std::sort(out.begin(), out.end(), [&](const BtDeviceEntry& a, const BtDeviceEntry& b) { if (a.connected != b.connected) return a.connected > b.connected; @@ -802,6 +903,7 @@ int runNetworksApp(int argc, char** argv) { cellInfo = queryCellularInfo(); } else if (activeTab == NetTab::Bluetooth) { btOn = isBtEnabledFast(); + std::string scanRaw; if (btOn) { int obexPid = readIntFile("/tmp/bananarchy_bt_obex.pid"); if (obexPid <= 0 || ::kill(obexPid, 0) != 0) { @@ -809,9 +911,21 @@ int runNetworksApp(int argc, char** argv) { } btRx = readBtRxStatus(); if (forceScan) { - runCaptureCmd("timeout 16 bluetoothctl --timeout 15 scan on >/dev/null 2>&1"); + // Keep the scan output: BlueZ discovery is client-scoped, so a + // separate `bluetoothctl devices` call after the scan can be empty. + // Also power the controller on when bluetoothd left it down, which + // is common on the WCNSS controller of the 2720 Flip. + std::string show = runCaptureCmd( + "timeout 2 bluetoothctl show 2>/dev/null"); + if (show.find("Powered: no") != std::string::npos || + show.find("Powered:") == std::string::npos) { + runCaptureCmd("timeout 2 bluetoothctl power on >/dev/null 2>&1"); + } + scanRaw = runCaptureCmd( + "timeout 16 bluetoothctl --timeout 15 scan on 2>/dev/null || " + "timeout 12 bluetoothctl scan on 2>/dev/null || true"); } - btList = queryBtDevices(); + btList = queryBtDevices(scanRaw); } else { btList.clear(); }