diff --git a/AGENTS.md b/AGENTS.md index 5f8d098..e1964f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -61,6 +61,12 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, ` `bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]`, `bluez5.enable-msbc = false`, `bluez5.enable-lc3-a127 = false`, `bluez5.dummy-avrcp-player = true`, and `bluez5.a2dp.ldac.quality = "auto"` (no `a2dp_source`, `bap_*`, `hsp_ag`, `hfp_ag`, or `lc3` — WCN3620 SCO routes internally at 8 kHz CVSD to QDSP6 `INTERNAL_BT_SCO_RX`/`TX`). + Keep `etc/conf.d/bluetooth` (`supervisor=supervise-daemon`, `retry="TERM/3/KILL/1"`, + `--noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard`), exclude gateway UUIDs + (`0000111f-`/`00001112-`/`0000110a-`) from `ReconnectUUIDs`, keep `duplicate-data off` in `bananarchy-bt-scan.sh`, + cleanly disconnect/`btmgmt power off` in `sxmo_bluetoothtoggle.sh off`, and use `bananarchy-bt-obex`'s single-shot + `ObjectManager` cache (`/run/bananarchy/bt-obex/bt_state.tsv` + `dump-state`, filtering `EPHEMERAL_DEV_PROPS`) in + `networks.so` instead of per-device `bluetoothctl` storms so `bluetoothd` never enters EOF/dual-bearer busy loops. `util-linux-misc` and `bluez-btmgmt` support the live PTY scan wrapper; guard `scripts/test-bluetooth-{hid,scan,live-scan,headset,obex}.py`. - WebKit requires explicit `glib` and `gsettings-desktop-schemas` packages. Because apk uses `--no-scripts`, `apply-bananarchy-overlay.sh` must run `compile-gsettings-schemas.sh`; without `gschemas.compiled`, the WebKit network diff --git a/CHANGELOG.md b/CHANGELOG.md index 60d194e..2e3b4c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeti - **Android OBEX (`0x1105`) recognition, L2CAP `SOCK_SEQPACKET`, and incoming file Accept/Reject + Target Folder UI (`etc/bluetooth/main.conf`, `50-bluetooth.conf`, `bananarchy-bt-le-enable.sh`, `sxmo_bluetoothtoggle.sh`, `bananarchy-bt-obex`, `networks_plugin.cpp`)**: added `Class = 0x5a020c` (`Phone / Smartphone` with `Object Transfer`) in `main.conf`, set `btmgmt -i hci0 class 2 3` at power-on/LE-enable, and removed `a2dp_source` from `50-bluetooth.conf` (`bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]`) so paired Android phones recognize Bananarchy as a phone supporting OBEX Object Push rather than a Bluetooth audio sink; replaced `recv(3)` with `ObexPacketReader` handling full L2CAP `SOCK_SEQPACKET` (GOEP 2.0) datagrams alongside RFCOMM `SOCK_STREAM`; registered BlueZ `OPP_UUID` (`0x1105`) with retries before falling back to raw RFCOMM channel 9 bind; added `/run/bananarchy/bt-obex/{prompt,decision}.tsv` IPC with an interactive `networks.so` prompt (`Accept & Save File`, `Dir: ... [Set]`, `Reject Transfer` returning OBEX `0xC3` Forbidden) and interactive `ObexDirPicker` / `ObexActions` directory chooser (`~/.config/sxmo/bt_obex_dir`, supporting `/media/sdcard`, custom folders, and duress confinement); verified via `scripts/test-bluetooth-obex.py`. - **Dual-bearer BR/EDR audio selection & PipeWire role/codec fixes (`bananarchy-bt-obex`, all four `50-bluetooth.conf` copies)**: kept `ControllerMode = dual` and `PreferredBearer = "le"` for HOGP (`00001812-`) while adding Classic Audio (`0000110b-`/`0000111e-`/`00001108-`/`audio-*`) detection (`set_audio_preferred_bearer()` -> `PreferredBearer = "bredr"`), `public` BR/EDR ranking over `random` BLE beacons in `find_matching_device()`/`scan_for_device()`, and `ConnectProfile` fallback so dual-mode Bluetooth 5.x/6.x earbuds do not stop on a GATT-only BLE link; updated `50-bluetooth.conf` across `/etc/`, `/usr/share/`, `/home/user/`, and `/etc/skel/` to restrict roles to `[ a2dp_sink hsp_hs hfp_hf ]` (removing `a2dp_source`, `bap_sink`/`bap_source`, and `hsp_ag`/`hfp_ag`), disable `msbc` and `lc3-a127`/`lc3` so HFP locks to 8 kHz `cvsd` for QDSP6 `INTERNAL_BT_SCO`, fix `opus_05_dup` -> `opus_05_duplex`, set `bluez5.dummy-avrcp-player = true`, and enable `bluez5.a2dp.ldac.quality = "auto"` (ABR) + `aac.bitratemode = 0` for 2.4 GHz Wi-Fi coexistence. - **SCO keepalive race, missing `pkill` leak, headset `ATA` call pickup, AVRCP media keys, and `nokia-sparkler` haptic guard (`sxmo_audio.sh`, `sxmo_modemaudio.sh`, `callscreen_plugin.cpp`, `networks_plugin.cpp`, `music_plugin.cpp`, `sxmo_vibrate.c`)**: replaced missing `pkill` in `stop_bt_sco_keepalive()` with `/proc` + `ps` teardown and stopped keepalive unconditionally when switching off Bluetooth HFP (even mid-call); added bounded (`25 x 0.1 s` / `15 x 0.1 s`) sink readiness waits and direct `$bt_sink` volume/mute mirroring (`+VGS`/AVRCP); synced `/tmp/sxmo_in_call` and `.pickedupcall` in `callscreen_plugin.cpp` when calls transition active via headset `ATA` so hangup restores A2DP and avoids false Missed Call logs; forwarded BlueZ `(AVRCP)` input keys to `music.so` (`PLAYPAUSE`/`PLAY`/`PAUSE`/`STOP`/`NEXT`/`PREV`) via the 0%-CPU `select()` bridge in `bananarchy-bt-obex` and handled `XF86XK_AudioPlay`/`Pause`/`Stop`/`Next`/`Prev` in `music_plugin.cpp`; refreshed stale `targetBt` after `Pair`/`Connect` in `networks_plugin.cpp` with a 24-device `info` batch cap; added `/tmp/sxmo_bt_sco_mm_active` suppression in `sxmo_vibrate.c` so 157 Hz haptic audio cannot leak over non-call BT SCO on `nokia-sparkler`; and changed `bt_discoverable` defaults across `sxmo_bluetoothtoggle.sh`, `bananarchy-bt-obex`, and `networks_plugin.cpp` to hidden-by-default with a 60 s discoverable timeout. Verified via `scripts/test-bluetooth-headset.py` alongside `test-bluetooth-{hid,scan,live-scan}.py` and `scripts/check-rebuild.sh`. +- **`bluetoothd` 50%-CPU spin & D-Bus refresh storm fixes (`etc/conf.d/bluetooth`, `etc/bluetooth/main.conf`, `bananarchy-bt-scan.sh`, `sxmo_bluetoothtoggle.sh`, `bananarchy-bt-obex`, `networks_plugin.cpp`)**: added `/etc/conf.d/bluetooth` (`supervisor=supervise-daemon`, `retry="TERM/3/KILL/1"`, `--noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard`) to keep `Experimental = true` (`PreferredBearer`) without triggering BlueZ `hfp-hf`/LE Audio `G_IO_IN` EOF `GMainLoop` busy-loops; removed gateway UUIDs (`0000111f-`/`00001112-`/`0000110a-`) from `main.conf` `ReconnectUUIDs`; enabled controller-side duplicate filtering (`duplicate-data off`) in `bananarchy-bt-scan.sh`; updated `sxmo_bluetoothtoggle.sh` to avoid redundant pre-power helper calls on enable and cleanly disconnect/`btmgmt -i hci0 power off` (with `kill -KILL` fallback and cache cleanup) on disable so `adapter_stop()` cannot spin on dual-bearer connections; and added single-shot BlueZ `ObjectManager` state caching (`format_managed_objects_tsv`, `/run/bananarchy/bt-obex/bt_state.tsv`, `dump-state`, `CTRL_READY_FILE`, and `EPHEMERAL_DEV_PROPS` RSSI/advertising suppression) consumed by `networks.so` instead of spawning up to 28 `bluetoothctl` processes per refresh. ### Nokia 8000 4G (`nokia-sparkler`) hardware-verified `lk2nd`, 4-core SMP/`cpufreq`, 157 Hz haptic audio, camera, and EDL bring-up @@ -73,10 +74,10 @@ Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeti ### Image persistence and upcoming `a1120` (`cocojamboo`) release archives - **Verified `a1120` / `cocojamboo` image set (`--mkinitfs`) and packaged archives**: - - `images/bananarchy-nokia-argon.img`: SHA-256 `09c46d21b140b486e21ebed39740b57808f8f1f0045f1801af2a7f8eba72bb4d` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `5a290c236aa85828fb0b8a9bf6e2a7afa8ebe10c9d2819617661e8c0cb53d3ff`, alongside `bootloader/lk2nd-msm8909.img`). - - `images/bananarchy-nokia-beatles.img`: SHA-256 `5d8c50f89e257dbadd9050479d56c46b1902cb38707f6f692e3508b44aa4fd10`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `f6c897f8e5fac17df38ac3d3222279f229b84c53ea73c323d06de5c40b26ccc0`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `a49d0d905af1ea5350bc1197e7970f59296359a913e3a09afc46c06aaf80d891`). - - `images/bananarchy-nokia-coconut.img`: SHA-256 `836331fb3034d0527f8c03eb90aae25bc8c87a84cc56baf24459d2e81e7a28d1`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `6e2fefec812594dc7b4dc322c68b1ab4c10b1c93abee4a0fbd11dfbf2dc59a0b`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `68af7997cbe1227d49e5238cabbbfcb44dcb728e8456b0fd0d416477307074b2`). - - `images/bananarchy-nokia-sparkler.img`: SHA-256 `61a068ca432f064812a96356b0dc49f1a38102a717c8dccd31768f0cbd1d7639`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `4357d48ac069104495629f1f35e220a01cde3412950e73e3e47e5372649fb6a2`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `73951ce01b3ff8f782488333767101d8e83701ae3822b1c7a0bef6ab8e96d1dc`). + - `images/bananarchy-nokia-argon.img`: SHA-256 `0a6760f8ff4a4d2baa6af88ce080898a1e3aff206e15b8474efa3ea4274d6dee` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `e7ccaa6baf3518896b22c60070508ab65f3938f204f0ddb2e7d0d5f2e39d271f`, alongside `bootloader/lk2nd-msm8909.img`). + - `images/bananarchy-nokia-beatles.img`: SHA-256 `7bb47f4e938d412e2e5fed5eb5b766bbbe36c71fa6e7b77d2cda346b48a82e17`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `496890063eda83adafaf5e7796a801100795b825064cf6f7fd967e6565dca325`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `2d94e513332137a93dcd10d6a6db6e7454c96ede2499c314660bb1ece21c7052`). + - `images/bananarchy-nokia-coconut.img`: SHA-256 `d3b385a84c6546d35edca03eac684f3d7ee6de0faab25172b9af5252137c6815`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `0a91c165e370b35a1604d08ddb6b08c46823455e5aee9701807f78221059e26c`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `31f7e7db0aadb09284ad380008701d1d0e765a10048161f02727cc7aba6ed6f2`). + - `images/bananarchy-nokia-sparkler.img`: SHA-256 `a262cb31ddb38e222e5f4bd14d82c82bb7941839a34bb48fa120b74189d319ae`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `affc62ff400c082c29b0d0c11a06bdd2eefdd06e09f1d2e93e7eae6a47a5a7b1`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `d0d44ea6e4f98b71536f7b232bc147ccf508057bbb38c3853d7b3750e5a3aaf3`). --- diff --git a/overlay/rootfs/etc/bluetooth/main.conf b/overlay/rootfs/etc/bluetooth/main.conf index 0bbb747..715cc60 100644 --- a/overlay/rootfs/etc/bluetooth/main.conf +++ b/overlay/rootfs/etc/bluetooth/main.conf @@ -13,7 +13,7 @@ Experimental = true Cache = always [Policy] -ReconnectUUIDs=00001112-0000-1000-8000-00805f9b34fb,0000111f-0000-1000-8000-00805f9b34fb,0000110a-0000-1000-8000-00805f9b34fb,0000110b-0000-1000-8000-00805f9b34fb,00001108-0000-1000-8000-00805f9b34fb,0000111e-0000-1000-8000-00805f9b34fb,00001124-0000-1000-8000-00805f9b34fb,00001812-0000-1000-8000-00805f9b34fb +ReconnectUUIDs=0000110b-0000-1000-8000-00805f9b34fb,00001108-0000-1000-8000-00805f9b34fb,0000111e-0000-1000-8000-00805f9b34fb,00001124-0000-1000-8000-00805f9b34fb,00001812-0000-1000-8000-00805f9b34fb ReconnectAttempts=3 ReconnectIntervals=2,4,8 AutoEnable=false diff --git a/overlay/rootfs/etc/conf.d/bluetooth b/overlay/rootfs/etc/conf.d/bluetooth new file mode 100644 index 0000000..09cb65e --- /dev/null +++ b/overlay/rootfs/etc/conf.d/bluetooth @@ -0,0 +1,5 @@ +supervisor=supervise-daemon +# Keep Experimental=true in main.conf for Device1.PreferredBearer, while excluding +# unused/broken experimental audio, telephony, MIDI, and NFC plugins. +command_args="--noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard" +retry="TERM/3/KILL/1" diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-obex b/overlay/rootfs/usr/bin/bananarchy-bt-obex index 86ee484..666b11a 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-obex +++ b/overlay/rootfs/usr/bin/bananarchy-bt-obex @@ -13,6 +13,8 @@ import signal import subprocess import threading +sys.dont_write_bytecode = True + OPP_UUID = "00001105-0000-1000-8000-00805f9b34fb" RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status" TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status" @@ -26,6 +28,16 @@ PAIR_PROMPT_FILE = "/run/bananarchy/bt-obex/pair_prompt.tsv" PAIR_DECISION_FILE = "/run/bananarchy/bt-obex/pair_decision.tsv" OP_DONE_FILE = "/run/bananarchy/bt-obex/op_done.tsv" AGENT_READY_FILE = "/run/bananarchy/bt-obex/agent_ready" +BT_STATE_FILE = "/run/bananarchy/bt-obex/bt_state.tsv" +CTRL_READY_FILE = "/run/bananarchy/bt-obex/ctrl_ready" +EPHEMERAL_DEV_PROPS = frozenset(( + "RSSI", + "TxPower", + "ManufacturerData", + "ServiceData", + "AdvertisingData", + "AdvertisingFlags", +)) OBEX_PROMPT_LOCK = threading.Lock() PAIR_PROMPT_LOCK = threading.Lock() PAIR_CANCEL_EVENT = threading.Event() @@ -98,11 +110,11 @@ def ensure_obex_ipc_dir(): pass -def write_status(path, text): +def _atomic_write_text(path, content): tmp = f"{path}.{os.getpid()}.tmp" try: with open(tmp, "w", encoding="utf-8") as f: - f.write(text.strip() + "\n") + f.write(content) os.chmod(tmp, 0o644) try: os.chown(tmp, 10000, 10000) @@ -124,6 +136,15 @@ def write_status(path, text): pass +def write_status(path, text): + _atomic_write_text(path, text.strip() + "\n") + + +def write_multiline_atomic(path, content): + text = content if content.endswith("\n") else (content + "\n") + _atomic_write_text(path, text) + + def notify_networks_ui(msg="REFRESH_BT\n"): fifo = "/tmp/dwm_plugin_networks.fifo" if os.path.exists(fifo): @@ -1121,6 +1142,170 @@ def read_cached_bt_device_info(dev_path, bt_root="/var/lib/bluetooth"): return out +def unwrap_dbus_variant(val): + if isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], str): + return val[1] + if (isinstance(val, list) and len(val) == 2 and isinstance(val[0], str) and + len(val[0]) <= 8 and "-" not in val[0]): + return val[1] + return val + + +def unwrap_props_dict(raw): + if not isinstance(raw, dict): + return {} + return {k: unwrap_dbus_variant(v) for k, v in raw.items()} + + +def format_managed_objects_tsv(objs): + """Format BlueZ ObjectManager objects into a compact CTRL/DEV TSV snapshot.""" + if not isinstance(objs, dict): + return "" + + adapter_props = None + if isinstance(objs.get("/org/bluez/hci0"), dict): + a = objs["/org/bluez/hci0"].get("org.bluez.Adapter1") + if isinstance(a, dict): + adapter_props = unwrap_props_dict(a) + + if adapter_props is None: + for opath in sorted(objs.keys()): + if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci"): + continue + ifaces = objs.get(opath) + if isinstance(ifaces, dict) and isinstance(ifaces.get("org.bluez.Adapter1"), dict): + adapter_props = unwrap_props_dict(ifaces["org.bluez.Adapter1"]) + break + + if adapter_props is None: + return "" + + powered = 1 if bool(adapter_props.get("Powered", False)) else 0 + disc = 1 if bool(adapter_props.get("Discoverable", False)) else 0 + alias = ( + str(adapter_props.get("Alias") or adapter_props.get("Name") or "") + .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip() + ) + lines = [f"CTRL\t{powered}\t{disc}\t{alias}"] + + dev_rows = [] + for opath, ifaces in objs.items(): + if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci") or "/dev_" not in opath: + continue + if not isinstance(ifaces, dict) or not isinstance(ifaces.get("org.bluez.Device1"), dict): + continue + dprops = unwrap_props_dict(ifaces["org.bluez.Device1"]) + mac = str(dprops.get("Address") or _extract_dev_mac_from_path(opath) or "").strip().upper() + if not mac: + continue + name = ( + str(dprops.get("Alias") or dprops.get("Name") or mac) + .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip() + ) or mac + paired = 1 if (bool(dprops.get("Paired", False)) or bool(dprops.get("Bonded", False))) else 0 + connected = 1 if bool(dprops.get("Connected", False)) else 0 + icon = ( + str(dprops.get("Icon") or "") + .replace("\t", " ").replace("\n", " ").replace("\r", " ").strip().lower() + ) + cod = dprops.get("Class") + class_hex = f"0x{cod:06x}" if (isinstance(cod, int) and not isinstance(cod, bool)) else "" + batt_pct = -1 + b_raw = ifaces.get("org.bluez.Battery1") + if isinstance(b_raw, dict): + bprops = unwrap_props_dict(b_raw) + pval = bprops.get("Percentage") + if isinstance(pval, (int, float)) and not isinstance(pval, bool): + batt_pct = max(0, min(100, int(pval))) + raw_uuids = dprops.get("UUIDs") or [] + uuids = ";".join( + str(u).replace("\t", "").replace("\n", "").replace("\r", "").strip().lower() + for u in raw_uuids if str(u).strip() + ) + dev_rows.append(( + mac, + opath, + f"DEV\t{mac}\t{name}\t{paired}\t{connected}\t{icon}\t{class_hex}\t{batt_pct}\t{uuids}" + )) + + dev_rows.sort(key=lambda item: (item[0], item[1])) + lines.extend(row[2] for row in dev_rows) + return "\n".join(lines) + "\n" + + +def fetch_managed_objects(conn=None, agent_path="", timeout=2.5): + if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"): + return None + own_conn = None + try: + from jeepney import DBusAddress, MessageType, new_method_call + from jeepney.io.blocking import open_dbus_connection + c = conn + if c is None: + own_conn = open_dbus_connection(bus="SYSTEM") + c = own_conn + om_addr = DBusAddress("/", bus_name="org.bluez", + interface="org.freedesktop.DBus.ObjectManager") + call = new_method_call(om_addr, "GetManagedObjects") + if conn is not None and agent_path: + rep = dbus_call_with_agent(c, call, agent_path, timeout=timeout) + else: + rep = c.send_and_get_reply(call, timeout=timeout) + if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: + objs = rep.body[0] + if isinstance(objs, dict): + return objs + except Exception: + pass + finally: + if own_conn is not None: + try: + own_conn.close() + except Exception: + pass + return None + + +def dump_bluez_state_tsv(conn=None, agent_path=""): + objs = fetch_managed_objects(conn=conn, agent_path=agent_path) + tsv = format_managed_objects_tsv(objs) + if not tsv: + return "" + try: + ensure_obex_ipc_dir() + write_multiline_atomic(BT_STATE_FILE, tsv) + except OSError: + pass + return tsv + + +def is_controller_powered_dbus(timeout=0.5): + if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"): + return False + c = None + try: + from jeepney import DBusAddress, MessageType, new_method_call + from jeepney.io.blocking import open_dbus_connection + c = open_dbus_connection(bus="SYSTEM") + prop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + rep = c.send_and_get_reply( + new_method_call(prop_addr, "Get", "ss", ("org.bluez.Adapter1", "Powered")), + timeout=timeout + ) + if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: + return bool(unwrap_dbus_variant(rep.body[0])) + except Exception: + pass + finally: + if c is not None: + try: + c.close() + except Exception: + pass + return False + + def query_dev_props_fresh(dev_path, timeout=0.6): if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): return {} @@ -1140,10 +1325,7 @@ def query_dev_props_fresh(dev_path, timeout=0.6): if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: raw = rep.body[0] if isinstance(raw, dict): - return { - k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) - for k, v in raw.items() - } + return unwrap_props_dict(raw) except Exception: pass finally: @@ -1527,47 +1709,130 @@ def run_daemon(): opp_registered = False rfcomm_listener = None dev_props_cache = {} + managed_objs = {} + + def write_state_from_cache(): + tsv = format_managed_objects_tsv(managed_objs) + if tsv: + ensure_obex_ipc_dir() + write_multiline_atomic(BT_STATE_FILE, tsv) + + def apply_adapter_settings(dbus_c): + bt_name = "" + try: + if os.path.exists("/home/user/.config/sxmo/bt_name"): + with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf: + bt_name = nf.readline().strip() + except OSError: + pass + if not bt_name: + try: + bt_name = socket.gethostname().strip() + except Exception: + bt_name = "Bananarchy" + + bt_disc = "0" + try: + if os.path.exists("/home/user/.config/sxmo/bt_discoverable"): + with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df: + bt_disc = df.readline().strip() or "0" + except OSError: + pass + disc_on = bt_disc.lower() not in ("0", "off", "no", "false") + + if dbus_c is not None: + try: + aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + if bt_name: + dbus_call_with_agent( + dbus_c, + new_method_call(aprop, "Set", "ssv", + ("org.bluez.Adapter1", "Alias", ("s", bt_name))), + agent_path, + timeout=2.0 + ) + dbus_call_with_agent( + dbus_c, + new_method_call(aprop, "Set", "ssv", + ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))), + agent_path, + timeout=2.0 + ) + dbus_call_with_agent( + dbus_c, + new_method_call(aprop, "Set", "ssv", + ("org.bluez.Adapter1", "Pairable", ("b", True))), + agent_path, + timeout=2.0 + ) + dbus_call_with_agent( + dbus_c, + new_method_call(aprop, "Set", "ssv", + ("org.bluez.Adapter1", "DiscoverableTimeout", ("u", 60))), + agent_path, + timeout=2.0 + ) + dbus_call_with_agent( + dbus_c, + new_method_call(aprop, "Set", "ssv", + ("org.bluez.Adapter1", "Discoverable", ("b", disc_on))), + agent_path, + timeout=2.0 + ) + return + except Exception: + pass + + if bt_name: + subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def refresh_dev_props_cache(dbus_c): if dbus_c is None: return - try: - om_a = DBusAddress("/", bus_name="org.bluez", - interface="org.freedesktop.DBus.ObjectManager") - rep = dbus_call_with_agent( - dbus_c, new_method_call(om_a, "GetManagedObjects"), agent_path, timeout=2.5 - ) - if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: - objs = rep.body[0] - if isinstance(objs, dict): - for opath, ifaces in objs.items(): - if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces: - raw = ifaces["org.bluez.Device1"] - if isinstance(raw, dict): - dev_props_cache[opath] = { - k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) - for k, v in raw.items() - } - except Exception: - pass + objs = fetch_managed_objects(conn=dbus_c, agent_path=agent_path, timeout=2.5) + if not isinstance(objs, dict): + return + dev_props_cache.clear() + managed_objs.clear() + for opath, ifaces in objs.items(): + if not isinstance(opath, str) or not isinstance(ifaces, dict): + continue + mentry = {} + for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"): + raw = ifaces.get(iname) + if isinstance(raw, dict): + unwrapped = unwrap_props_dict(raw) + mentry[iname] = unwrapped + if iname == "org.bluez.Device1": + dev_props_cache[opath] = dict(unwrapped) + if mentry: + managed_objs[opath] = mentry + write_state_from_cache() try: conn = open_dbus_connection(bus="SYSTEM", enable_fds=True) dbus_bus = DBusAddress("/org/freedesktop/DBus", bus_name="org.freedesktop.DBus", interface="org.freedesktop.DBus") - dbus_send_safe(conn, new_method_call( - dbus_bus, "AddMatch", "s", - ("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",) - )) - dbus_send_safe(conn, new_method_call( - dbus_bus, "AddMatch", "s", - ("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",) - )) - dbus_send_safe(conn, new_method_call( - dbus_bus, "AddMatch", "s", - ("type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",) - )) + for match_rule in ( + "type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'", + "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'", + "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Adapter1'", + "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Battery1'", + "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'", + "type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'", + ): + dbus_send_safe(conn, new_method_call(dbus_bus, "AddMatch", "s", (match_rule,))) for _attempt in range(10): if not running: break @@ -1576,7 +1841,6 @@ def run_daemon(): if opp_registered: break time.sleep(0.3) - refresh_dev_props_cache(conn) except Exception: pass @@ -1584,40 +1848,8 @@ def run_daemon(): rfcomm_listener = bind_rfcomm_fallback() prepare_bt_controller() - - bt_name = "" - try: - if os.path.exists("/home/user/.config/sxmo/bt_name"): - with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf: - bt_name = nf.readline().strip() - except OSError: - pass - if not bt_name: - try: - bt_name = socket.gethostname().strip() - except Exception: - bt_name = "Bananarchy" - if bt_name: - subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - - bt_disc = "0" - try: - if os.path.exists("/home/user/.config/sxmo/bt_discoverable"): - with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df: - bt_disc = df.readline().strip() or "0" - except OSError: - pass - disc_on = bt_disc.lower() not in ("0", "off", "no", "false") - - subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + apply_adapter_settings(conn) + refresh_dev_props_cache(conn) gp_thread = threading.Thread(target=run_gamepad_uinput_bridge, args=(lambda: running, wake_r), daemon=True) @@ -1664,46 +1896,101 @@ def run_daemon(): member = msg.header.fields.get(3) if member == "NameOwnerChanged" and msg.body and len(msg.body) >= 3: name, _old_owner, new_owner = msg.body[0], msg.body[1], msg.body[2] - if name == "org.bluez" and new_owner: + if name == "org.bluez": dev_props_cache.clear() - if rfcomm_listener is not None: - try: - rfcomm_listener.close() - except OSError: - pass - rfcomm_listener = None - opp_registered = register_bluez_services(conn, profile_path, agent_path) - if not opp_registered: - rfcomm_listener = bind_rfcomm_fallback() - refresh_dev_props_cache(conn) + managed_objs.clear() + if new_owner: + if rfcomm_listener is not None: + try: + rfcomm_listener.close() + except OSError: + pass + rfcomm_listener = None + opp_registered = register_bluez_services(conn, profile_path, agent_path) + if not opp_registered: + rfcomm_listener = bind_rfcomm_fallback() + apply_adapter_settings(conn) + refresh_dev_props_cache(conn) + else: + for p in (AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass elif member == "InterfacesAdded" and msg.body and len(msg.body) >= 2: opath, ifaces = msg.body[0], msg.body[1] - if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces: - raw = ifaces["org.bluez.Device1"] - if isinstance(raw, dict): - dev_props_cache[opath] = { - k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v) - for k, v in raw.items() - } + if isinstance(opath, str) and isinstance(ifaces, dict): + touched = False + for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"): + raw = ifaces.get(iname) + if isinstance(raw, dict): + unwrapped = unwrap_props_dict(raw) + managed_objs.setdefault(opath, {})[iname] = unwrapped + if iname == "org.bluez.Device1": + dev_props_cache[opath] = dict(unwrapped) + touched = True + if touched: + write_state_from_cache() + elif member == "InterfacesRemoved" and msg.body and len(msg.body) >= 2: + opath, ifaces = msg.body[0], msg.body[1] + if isinstance(opath, str) and isinstance(ifaces, (list, tuple)): + touched = False + entry = managed_objs.get(opath) + if isinstance(entry, dict): + for iname in ifaces: + if iname in entry: + entry.pop(iname, None) + touched = True + if iname == "org.bluez.Device1" and opath in dev_props_cache: + dev_props_cache.pop(opath, None) + touched = True + if not entry: + managed_objs.pop(opath, None) + if touched: + write_state_from_cache() + if "org.bluez.Device1" in ifaces or "org.bluez.Battery1" in ifaces: + notify_networks_ui() elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2: obj_path = msg.header.fields.get(1) iface, changed = msg.body[0], msg.body[1] - if iface == "org.bluez.Device1" and isinstance(changed, dict): - if isinstance(obj_path, str): - entry = dev_props_cache.setdefault(obj_path, {}) + invalidated = msg.body[2] if len(msg.body) >= 3 else () + if (isinstance(obj_path, str) and + iface in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1") and + isinstance(changed, dict)): + mentry = managed_objs.setdefault(obj_path, {}).setdefault(iface, {}) + for k, v in changed.items(): + mentry[k] = unwrap_dbus_variant(v) + if isinstance(invalidated, (list, tuple)): + for ik in invalidated: + mentry.pop(ik, None) + if iface == "org.bluez.Device1": + dentry = dev_props_cache.setdefault(obj_path, {}) for k, v in changed.items(): - entry[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v - if changed.get("Paired"): - try: - if os.path.exists(PAIR_PROMPT_FILE): - with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf: - pln = pf.readline() - if "\tDISPLAY\t" in pln: - clear_pair_prompt_files(notify_cancel=True) - except OSError: - pass - if any(k in changed for k in ("Connected", "Paired", "Bonded")): - notify_networks_ui() + dentry[k] = unwrap_dbus_variant(v) + if isinstance(invalidated, (list, tuple)): + for ik in invalidated: + dentry.pop(ik, None) + if changed.get("Paired"): + try: + if os.path.exists(PAIR_PROMPT_FILE): + with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf: + pln = pf.readline() + if "\tDISPLAY\t" in pln: + clear_pair_prompt_files(notify_cancel=True) + except OSError: + pass + if any(k not in EPHEMERAL_DEV_PROPS for k in changed) or bool(invalidated): + write_state_from_cache() + if any(k in changed for k in ("Connected", "Paired", "Bonded")): + notify_networks_ui() + else: + write_state_from_cache() + if iface == "org.bluez.Battery1" or ( + iface == "org.bluez.Adapter1" and + any(k in changed for k in ("Powered", "Discoverable", "Alias")) + ): + notify_networks_ui() if rfcomm_listener is not None: while running: @@ -1742,7 +2029,7 @@ def run_daemon(): except OSError: pass clear_pair_prompt_files(notify_cancel=True) - for p in (PID_FILE, AGENT_READY_FILE): + for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE): try: if os.path.exists(p): os.unlink(p) @@ -1973,8 +2260,10 @@ def ensure_daemon_running(): time.sleep(0.05) -def prepare_bt_controller(): +def prepare_bt_controller(force=False): """Power the adapter and enable LE before DBus Pair/Connect calls.""" + if not force and os.path.exists(CTRL_READY_FILE) and is_controller_powered_dbus(): + return try: subprocess.run(["timeout", "3", "bluetoothctl", "power", "on"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, @@ -1991,6 +2280,11 @@ def prepare_bt_controller(): stderr=subprocess.DEVNULL, timeout=4) except Exception: pass + try: + ensure_obex_ipc_dir() + write_status(CTRL_READY_FILE, "1") + except OSError: + pass def clear_stale_linkkey(mac): @@ -2274,7 +2568,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): if "key-missing" in err_str: dev_mac = dpath.split("dev_")[-1].replace("_", ":") if clear_stale_linkkey(dev_mac): - prepare_bt_controller() + prepare_bt_controller(force=True) if not use_cli_agent: w_end = time.monotonic() + 2.0 while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE): @@ -2333,7 +2627,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): w_end = time.monotonic() + 2.0 while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE): time.sleep(0.05) - prepare_bt_controller() + prepare_bt_controller(force=True) trust_device_path(conn_new, dpath) set_hog_preferred_bearer(conn_new, dpath, p) set_audio_preferred_bearer(conn_new, dpath, p) @@ -2479,7 +2773,7 @@ def stop_daemon(): except OSError: pass clear_pair_prompt_files(notify_cancel=True) - for p in (PID_FILE, AGENT_READY_FILE): + for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE): try: if os.path.exists(p): os.unlink(p) @@ -2502,6 +2796,12 @@ def main(): elif cmd == "stop": stop_daemon() return 0 + elif cmd == "dump-state": + tsv = dump_bluez_state_tsv() + if tsv: + sys.stdout.write(tsv) + return 0 + return 1 elif cmd in ("connect", "pair"): if len(args) < 2: print(f"Usage: bananarchy-bt-obex {cmd} [name]", file=sys.stderr) diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-scan.sh b/overlay/rootfs/usr/bin/bananarchy-bt-scan.sh index 44649ef..8fe6679 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-scan.sh +++ b/overlay/rootfs/usr/bin/bananarchy-bt-scan.sh @@ -38,7 +38,7 @@ fi printf '%s\n' \ 'menu scan' \ 'transport auto' \ - 'duplicate-data on' \ + 'duplicate-data off' \ 'back' \ 'power on' sleep 1 diff --git a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh index c5d5039..afd740d 100755 --- a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh +++ b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh @@ -25,8 +25,6 @@ on() { if [ -s /etc/bananarchy/bt_mac ] && [ -x /usr/bin/bananarchy-engmenu-ctl ]; then /usr/bin/bananarchy-engmenu-ctl apply-boot >/dev/null 2>&1 || true fi - /usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true - timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true timeout 2 bluetoothctl power on >/dev/null 2>&1 || true /usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true @@ -63,6 +61,8 @@ on() { off() { /usr/bin/bananarchy-bt-obex stop >/dev/null 2>&1 || true + timeout 2 bluetoothctl disconnect >/dev/null 2>&1 || true + timeout 2 /usr/bin/btmgmt -i hci0 power off >/dev/null 2>&1 || true if [ -d /run/systemd/system ]; then systemctl stop bluetooth systemctl disable bluetooth @@ -70,7 +70,12 @@ off() { rc-service bluetooth stop rc-update del bluetooth fi + btpid="$(pidof -s bluetoothd 2>/dev/null || true)" + if [ -n "$btpid" ]; then + kill -KILL $(pidof bluetoothd) 2>/dev/null || true + fi rfkill block bluetooth + rm -f /run/bananarchy/bt-obex/ctrl_ready /run/bananarchy/bt-obex/bt_state.tsv 2>/dev/null || true } case "${1:-toggle}" in diff --git a/overlay/rootfs/usr/lib/dwm/plugins/networks.so b/overlay/rootfs/usr/lib/dwm/plugins/networks.so index 6213a44..6f66185 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 6213a44..6f66185 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/apply-bananarchy-overlay.sh b/scripts/apply-bananarchy-overlay.sh index bc8550c..0f9684d 100755 --- a/scripts/apply-bananarchy-overlay.sh +++ b/scripts/apply-bananarchy-overlay.sh @@ -552,8 +552,10 @@ fi chmod 644 "$TARGET_ROOTFS/etc/pam.d/sshd" \ "$TARGET_ROOTFS/etc/ssh/sshd_config.d/90-bananarchy-access.conf" \ 2>/dev/null || true -chown 0:0 "$TARGET_ROOTFS/etc/doas.d/60-bananarchy-bluetooth.conf" 2>/dev/null || true -chmod 0644 "$TARGET_ROOTFS/etc/doas.d/60-bananarchy-bluetooth.conf" 2>/dev/null || true +chown 0:0 "$TARGET_ROOTFS/etc/doas.d/60-bananarchy-bluetooth.conf" \ + "$TARGET_ROOTFS/etc/conf.d/bluetooth" 2>/dev/null || true +chmod 0644 "$TARGET_ROOTFS/etc/doas.d/60-bananarchy-bluetooth.conf" \ + "$TARGET_ROOTFS/etc/conf.d/bluetooth" 2>/dev/null || true chown 0:0 "$TARGET_ROOTFS/etc/pam.d/sshd" \ "$TARGET_ROOTFS/etc/ssh/sshd_config.d/90-bananarchy-access.conf" \ 2>/dev/null || true diff --git a/scripts/check-rebuild.sh b/scripts/check-rebuild.sh index 33d3ad1..965edb2 100755 --- a/scripts/check-rebuild.sh +++ b/scripts/check-rebuild.sh @@ -557,15 +557,15 @@ fi echo "[check] Known-good flashable image set..." for pair in \ - "09c46d21b140b486e21ebed39740b57808f8f1f0045f1801af2a7f8eba72bb4d images/bananarchy-nokia-argon.img" \ - "5d8c50f89e257dbadd9050479d56c46b1902cb38707f6f692e3508b44aa4fd10 images/bananarchy-nokia-beatles.img" \ - "f6c897f8e5fac17df38ac3d3222279f229b84c53ea73c323d06de5c40b26ccc0 images/boot-bananarchy-nokia-beatles.img" \ + "0a6760f8ff4a4d2baa6af88ce080898a1e3aff206e15b8474efa3ea4274d6dee images/bananarchy-nokia-argon.img" \ + "7bb47f4e938d412e2e5fed5eb5b766bbbe36c71fa6e7b77d2cda346b48a82e17 images/bananarchy-nokia-beatles.img" \ + "496890063eda83adafaf5e7796a801100795b825064cf6f7fd967e6565dca325 images/boot-bananarchy-nokia-beatles.img" \ "b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d images/boot-lk2nd-nokia-beatles-display.img" \ - "836331fb3034d0527f8c03eb90aae25bc8c87a84cc56baf24459d2e81e7a28d1 images/bananarchy-nokia-coconut.img" \ - "6e2fefec812594dc7b4dc322c68b1ab4c10b1c93abee4a0fbd11dfbf2dc59a0b images/boot-bananarchy-nokia-coconut.img" \ + "d3b385a84c6546d35edca03eac684f3d7ee6de0faab25172b9af5252137c6815 images/bananarchy-nokia-coconut.img" \ + "0a91c165e370b35a1604d08ddb6b08c46823455e5aee9701807f78221059e26c images/boot-bananarchy-nokia-coconut.img" \ "e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a images/boot-lk2nd-nokia-coconut-display.img" \ - "61a068ca432f064812a96356b0dc49f1a38102a717c8dccd31768f0cbd1d7639 images/bananarchy-nokia-sparkler.img" \ - "4357d48ac069104495629f1f35e220a01cde3412950e73e3e47e5372649fb6a2 images/boot-bananarchy-nokia-sparkler.img" \ + "a262cb31ddb38e222e5f4bd14d82c82bb7941839a34bb48fa120b74189d319ae images/bananarchy-nokia-sparkler.img" \ + "affc62ff400c082c29b0d0c11a06bdd2eefdd06e09f1d2e93e7eae6a47a5a7b1 images/boot-bananarchy-nokia-sparkler.img" \ "bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f images/boot-lk2nd-nokia-sparkler-display.img"; do set -- $pair want=$1 @@ -1963,12 +1963,15 @@ for token in 'BANANARCHY_REAL_BLUETOOTHCTL' 'BANANARCHY_BT_SCAN_HELPER' \ fail "bluetoothctl wrapper is missing $token" fi done -for token in 'script -q -c' 'transport auto' 'duplicate-data on' \ +for token in 'script -q -c' 'transport auto' 'duplicate-data off' \ 'scan off' 'BANANARCHY_BT_SCAN_SECONDS'; do if ! grep -qF "$token" "$BT_HELPER"; then fail "live Bluetooth scan helper is missing $token" fi done +if grep -qF 'duplicate-data on' "$BT_HELPER"; then + fail "live Bluetooth scan helper must keep duplicate-data off to avoid bluetoothd floods" +fi if ! grep -q '^util-linux-misc$' "$PKGS_FILE"; then fail "rootfs package set is missing util-linux-misc (script)" fi @@ -2059,6 +2062,23 @@ fi if ! "$BT_OBEX_TEST" >/dev/null 2>&1; then fail "host Bluetooth OBEX verification failed" fi +BT_CONFD="$BASE_DIR/overlay/rootfs/etc/conf.d/bluetooth" +NETWORKS_SO="$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so" +if [ ! -f "$BT_CONFD" ] || \ + ! grep -qF 'supervisor=supervise-daemon' "$BT_CONFD" || \ + ! grep -qF -- '--noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard' "$BT_CONFD"; then + fail "overlay/rootfs/etc/conf.d/bluetooth is missing supervise-daemon or --noplugin CPU busy-loop guard" +fi +if grep -qE '^ReconnectUUIDs=.*(0000111f-|00001112-|0000110a-)' "$BT_MAIN_CONF"; then + fail "main.conf ReconnectUUIDs must exclude gateway UUIDs (111f/1112/110a)" +fi +if ! grep -qF 'format_managed_objects_tsv' "$BT_OBEX" || \ + ! grep -qF 'dump-state' "$BT_OBEX" || \ + [ ! -f "$NETWORKS_SO" ] || \ + ! grep -aqF 'bt_state.tsv' "$NETWORKS_SO" || \ + ! grep -aqF 'dump-state' "$NETWORKS_SO"; then + fail "Bluetooth ObjectManager bt_state.tsv / dump-state cache is missing from daemon or networks.so" +fi echo "[check] Charger plug/unplug charge icon..." BATTERY_RULES="$BASE_DIR/overlay/rootfs/etc/udev/rules.d/85-bananarchy-battery.rules" diff --git a/scripts/test-bluetooth-headset.py b/scripts/test-bluetooth-headset.py index e8b6734..7d6c0ca 100755 --- a/scripts/test-bluetooth-headset.py +++ b/scripts/test-bluetooth-headset.py @@ -193,7 +193,35 @@ def test_discoverability_and_power(): require("discoverable-timeout 0" not in net_src and "discoverable-timeout 60" in net_src, "networks_plugin.cpp must use 60s discoverable timeout") - print("[ok] Bounded 60s discoverability and hidden-by-default battery safeguard") + + confd_bt = BASE / "overlay/rootfs/etc/conf.d/bluetooth" + require(confd_bt.is_file(), "missing overlay/rootfs/etc/conf.d/bluetooth") + confd_src = read(confd_bt) + for tok in ( + "supervisor=supervise-daemon", + "--noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard", + 'retry="TERM/3/KILL/1"', + ): + require(tok in confd_src, f"etc/conf.d/bluetooth missing {tok}") + + rec_lines = [ln for ln in main_src.splitlines() if ln.startswith("ReconnectUUIDs=")] + require(len(rec_lines) == 1, "main.conf must define ReconnectUUIDs") + rec_line = rec_lines[0] + for forbidden in ("0000111f-", "00001112-", "0000110a-"): + require(forbidden not in rec_line, + f"main.conf ReconnectUUIDs must exclude gateway UUID {forbidden}") + for keep in ("0000110b-", "00001108-", "0000111e-", "00001124-", "00001812-"): + require(keep in rec_line, f"main.conf ReconnectUUIDs missing {keep}") + + for tok in ( + "bluetoothctl disconnect", + "btmgmt -i hci0 power off", + "kill -KILL", + "/run/bananarchy/bt-obex/ctrl_ready", + "/run/bananarchy/bt-obex/bt_state.tsv", + ): + require(tok in toggle_src, f"sxmo_bluetoothtoggle.sh missing clean stop step {tok}") + print("[ok] Bounded 60s discoverability, BlueZ --noplugin guard, and clean power-off") def test_sco_audio_call_and_haptics(): diff --git a/scripts/test-bluetooth-live-scan.py b/scripts/test-bluetooth-live-scan.py index 344af8f..e022c52 100755 --- a/scripts/test-bluetooth-live-scan.py +++ b/scripts/test-bluetooth-live-scan.py @@ -74,11 +74,13 @@ def main(): if token not in wrapper: raise SystemExit("bluetoothctl wrapper is missing %s" % token) for token in ("script -q -c", "menu scan", "transport auto", - "duplicate-data on", "scan on", "devices", "scan off", + "duplicate-data off", "scan on", "devices", "scan off", "quit", "BANANARCHY_BT_SCAN_SECONDS", "bananarchy-bt-le-enable.sh"): if token not in helper: raise SystemExit("live scan helper is missing %s" % token) + if "duplicate-data on" in helper: + raise SystemExit("live scan helper must keep duplicate-data off to avoid bluetoothd flood") for token in ("usr/local/bin/bluetoothctl", "usr/bin/bananarchy-bt-scan.sh", "usr/bin/bananarchy-bt-le-enable.sh", "etc/doas.d/60-bananarchy-bluetooth.conf"): diff --git a/scripts/test-bluetooth-obex.py b/scripts/test-bluetooth-obex.py index 3213145..02002b2 100755 --- a/scripts/test-bluetooth-obex.py +++ b/scripts/test-bluetooth-obex.py @@ -480,6 +480,9 @@ def test_networks_ui_wiring(): "openObexDirPicker", "tryPresentObexPrompt", "tryPresentPairPrompt", + "bt_state.tsv", + "dump-state", + "parseBtStateTsv", ): require(tok in src, f"networks_plugin.cpp missing OBEX/Pairing UI element {tok}") obex_src = read(BT_OBEX) @@ -490,12 +493,64 @@ def test_networks_ui_wiring(): print("[ok] networks_plugin.cpp OBEX & KeyboardDisplay pairing UI wiring") +def test_managed_objects_state_cache(mod): + require("RSSI" in mod.EPHEMERAL_DEV_PROPS and + "ManufacturerData" in mod.EPHEMERAL_DEV_PROPS, + "EPHEMERAL_DEV_PROPS must suppress RSSI/advertising cache rewrites") + objs = { + "/org/bluez/hci0": { + "org.bluez.Adapter1": { + "Powered": ("b", True), + "Discoverable": ("b", False), + "Alias": ("s", "Bananarchy"), + }, + }, + "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF": { + "org.bluez.Device1": { + "Address": ("s", "AA:BB:CC:DD:EE:FF"), + "Alias": ("s", "Audio Headset"), + "Paired": ("b", True), + "Connected": ("b", True), + "Icon": ("s", "audio-headset"), + "Class": ("u", 0x240404), + "UUIDs": ("as", [ + "0000110B-0000-1000-8000-00805F9B34FB", + "0000111e-0000-1000-8000-00805f9b34fb", + ]), + }, + "org.bluez.Battery1": { + "Percentage": ("y", 85), + }, + }, + "/org/bluez/hci0/dev_11_22_33_44_55_66": { + "org.bluez.Device1": { + "Address": ("s", "11:22:33:44:55:66"), + "Name": ("s", "Pixel Phone"), + "Paired": ("b", True), + "Connected": ("b", False), + "Icon": ("s", "phone"), + "Class": ("u", 0x5a020c), + "UUIDs": ("as", ["00001105-0000-1000-8000-00805f9b34fb"]), + }, + }, + } + lines = mod.format_managed_objects_tsv(objs).splitlines() + expected = [ + "CTRL\t1\t0\tBananarchy", + "DEV\t11:22:33:44:55:66\tPixel Phone\t1\t0\tphone\t0x5a020c\t-1\t00001105-0000-1000-8000-00805f9b34fb", + "DEV\tAA:BB:CC:DD:EE:FF\tAudio Headset\t1\t1\taudio-headset\t0x240404\t85\t0000110b-0000-1000-8000-00805f9b34fb;0000111e-0000-1000-8000-00805f9b34fb", + ] + require(lines == expected, f"unexpected format_managed_objects_tsv output: {lines!r}") + print("[ok] BlueZ ObjectManager bt_state.tsv snapshot formatter & ephemeral property filter") + + def main(): mod = load_obex_module() test_class_and_roles() test_seqpacket_and_stream_reader(mod) test_accept_and_reject_sessions(mod) test_keyboard_display_agent(mod) + test_managed_objects_state_cache(mod) test_networks_ui_wiring() print("bluetooth obex verification: all checks passed") diff --git a/src/dwm-plugins/networks_plugin.cpp b/src/dwm-plugins/networks_plugin.cpp index b5fed9d..4d6a4af 100644 --- a/src/dwm-plugins/networks_plugin.cpp +++ b/src/dwm-plugins/networks_plugin.cpp @@ -206,6 +206,7 @@ constexpr const char* kObexDecisionPath = "/run/bananarchy/bt-obex/decision.tsv" constexpr const char* kPairPromptPath = "/run/bananarchy/bt-obex/pair_prompt.tsv"; constexpr const char* kPairDecisionPath = "/run/bananarchy/bt-obex/pair_decision.tsv"; constexpr const char* kBtOpDonePath = "/run/bananarchy/bt-obex/op_done.tsv"; +constexpr const char* kBtStateTsvPath = "/run/bananarchy/bt-obex/bt_state.tsv"; std::string shortenHomePath(const std::string& p) { if (p.empty()) return "~/Downloads"; @@ -705,62 +706,258 @@ std::vector parseBtScanDevices(const std::string& raw) { return out; } -std::vector queryBtDevices(const std::string& scanRaw = "") { - std::vector out; - std::unordered_set pairedMacs; - std::unordered_set connectedMacs; +struct BtRawDevSnapshot { + std::string mac; + std::string name; + bool paired = false; + bool connected = false; + std::string icon; + unsigned long devClass = 0; + bool hasClass = false; + int batteryPct = -1; + std::string uuidsLow; +}; - auto parseMacSet = [](const std::string& raw, - std::unordered_set& dst) { - std::istringstream ss(raw); - std::string line; - while (std::getline(ss, line)) { - if (line.rfind("Device ", 0) == 0 && line.size() >= 24) { - dst.insert(line.substr(7, 17)); - } +struct BtStateSnapshot { + bool valid = false; + bool powered = false; + bool discoverable = false; + std::string alias; + std::vector devs; +}; + +std::vector splitTabCols(const std::string& line) { + std::vector cols; + size_t start = 0; + while (start <= line.size()) { + size_t pos = line.find('\t', start); + if (pos == std::string::npos) { + cols.push_back(line.substr(start)); + break; } - }; + cols.push_back(line.substr(start, pos - start)); + start = pos + 1; + } + return cols; +} - parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || " - "timeout 2 bluetoothctl paired-devices 2>/dev/null"), - pairedMacs); - parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"), - connectedMacs); - - std::string paRaw = runCaptureCmd( - "pactl list sinks short 2>/dev/null; pactl list sources short 2>/dev/null; " - "pactl list cards 2>/dev/null"); - - std::unordered_map cardActiveProfile; - { - std::istringstream pss(paRaw); - std::string pline; - std::string curCard; - while (std::getline(pss, pline)) { - std::string t = trimStr(pline); - if (t.rfind("Name: bluez_card.", 0) == 0) { - curCard = trimStr(t.substr(6)); - } else if (!curCard.empty() && t.rfind("Active Profile:", 0) == 0) { - cardActiveProfile[curCard] = trimStr(t.substr(15)); - curCard.clear(); +BtStateSnapshot parseBtStateTsv(const std::string& raw) { + BtStateSnapshot snap; + std::istringstream ss(raw); + std::string line; + while (std::getline(ss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty()) continue; + std::vector cols = splitTabCols(line); + if (cols[0] == "CTRL" && cols.size() >= 3) { + snap.valid = true; + snap.powered = (cols[1] == "1"); + snap.discoverable = (cols[2] == "1"); + if (cols.size() >= 4) snap.alias = trimStr(cols[3]); + } else if (cols[0] == "DEV" && cols.size() >= 8) { + std::string mac = trimStr(cols[1]); + if (!isBluetoothMac(mac)) continue; + BtRawDevSnapshot dev; + dev.mac = mac; + dev.name = trimStr(cols[2]); + if (dev.name.empty()) dev.name = mac; + dev.paired = (cols[3] == "1"); + dev.connected = (cols[4] == "1"); + dev.icon = toLowerStr(trimStr(cols[5])); + std::string clsStr = trimStr(cols[6]); + if (!clsStr.empty()) { + char* endp = nullptr; + unsigned long cls = std::strtoul(clsStr.c_str(), &endp, 0); + if (endp != clsStr.c_str() && cls != 0) { + dev.devClass = cls; + dev.hasClass = true; + } } + std::string batStr = trimStr(cols[7]); + if (!batStr.empty()) { + char* endp = nullptr; + long bp = std::strtol(batStr.c_str(), &endp, 10); + if (endp != batStr.c_str() && bp >= 0 && bp <= 100) { + dev.batteryPct = static_cast(bp); + } + } + if (cols.size() >= 9) dev.uuidsLow = toLowerStr(trimStr(cols[8])); + snap.devs.push_back(std::move(dev)); } } + return snap; +} - std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null"); - std::istringstream ss(allRaw); - std::string line; - std::string infoCmd; - int infoCount = 0; +BtStateSnapshot loadBtStateSnapshot(bool forceFresh) { + int obexPid = readIntFile("/tmp/bananarchy_bt_obex.pid"); + bool obexAlive = (obexPid > 0 && (::kill(obexPid, 0) == 0 || errno == EPERM)); + struct stat st = {}; + if (!forceFresh && obexAlive && + ::stat(kBtStateTsvPath, &st) == 0 && st.st_size > 0) { + std::ifstream in(kBtStateTsvPath); + if (in.is_open()) { + std::ostringstream oss; + oss << in.rdbuf(); + BtStateSnapshot parsed = parseBtStateTsv(oss.str()); + if (parsed.valid) return parsed; + } + } + std::string raw = runCaptureCmd( + "timeout 2 /usr/bin/bananarchy-bt-obex dump-state 2>/dev/null"); + return parseBtStateTsv(raw); +} - while (std::getline(ss, line)) { - if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue; - BtDeviceEntry d; - d.mac = line.substr(7, 17); - d.name = (line.size() > 25) ? trimStr(line.substr(25)) : d.mac; - d.paired = (pairedMacs.count(d.mac) > 0); - d.connected = (connectedMacs.count(d.mac) > 0); - out.push_back(d); +const BtStateSnapshot* gCachedBtSnapshot = nullptr; + +void classifyBtDevice( + BtDeviceEntry& d, + const std::string& paRaw, + const std::unordered_map& cardActiveProfile, + const std::string& iconLow, + unsigned long devClass, + bool hasClass, + const std::string& hintsLow) { + std::string macU = d.mac; + for (char& c : macU) { + if (c == ':') c = '_'; + } + bool hasPaSink = (paRaw.find("bluez_output." + macU) != std::string::npos); + bool hasPaSrc = (paRaw.find("bluez_input." + macU) != std::string::npos); + std::string nameLow = toLowerStr(d.name); + + bool hasA2dp = (hintsLow.find("0000110b-") != std::string::npos || + hintsLow.find("audio sink") != std::string::npos); + bool hasHfp = (hintsLow.find("00001108-") != std::string::npos || + hintsLow.find("0000111e-") != std::string::npos); + bool hasHid = (hintsLow.find("00001124-") != std::string::npos || + hintsLow.find("00001812-") != std::string::npos || + hintsLow.find("human interface device") != std::string::npos); + + unsigned long majorClass = hasClass ? (devClass & 0x1F00UL) : 0; + unsigned long minorClass = hasClass ? (devClass & 0x00FFUL) : 0; + bool isCoDPhoneOrPc = + (hasClass && (majorClass == 0x0100UL || majorClass == 0x0200UL)); + bool isCoDAudio = (hasClass && majorClass == 0x0400UL); + bool isCoDGamepad = + (hasClass && majorClass == 0x0500UL && + ((minorClass & 0x3CUL) == 0x04UL || (minorClass & 0x3CUL) == 0x08UL)); + bool isCoDKeyboard = + (hasClass && majorClass == 0x0500UL && (minorClass & 0x40UL) != 0); + bool isCoDMouse = + (hasClass && majorClass == 0x0500UL && (minorClass & 0xC0UL) == 0x80UL); + + bool isPhoneOrPc = + (iconLow == "phone" || iconLow == "computer" || isCoDPhoneOrPc); + + if (iconLow == "input-gaming" || iconLow == "input-joystick" || + isCoDGamepad || + nameLow.find("gamepad") != std::string::npos || + nameLow.find("controller") != std::string::npos || + nameLow.find("joy-con") != std::string::npos || + nameLow.find("dualshock") != std::string::npos || + nameLow.find("dualsense") != std::string::npos || + nameLow.find("8bitdo") != std::string::npos || + nameLow.find("xbox") != std::string::npos) { + d.kind = BtDevKind::Gamepad; + d.profileLabel = "HID Gamepad"; + } else if (iconLow == "input-keyboard" || isCoDKeyboard || + nameLow.find("keyboard") != std::string::npos || + nameLow.find("keychron") != std::string::npos) { + d.kind = BtDevKind::Keyboard; + d.profileLabel = "HID Keyboard"; + } else if (iconLow == "input-mouse" || iconLow == "input-tablet" || + isCoDMouse || + nameLow.find("mouse") != std::string::npos || + nameLow.find("trackpad") != std::string::npos) { + d.kind = BtDevKind::Mouse; + d.profileLabel = "HID Mouse"; + } else if (isPhoneOrPc) { + d.kind = BtDevKind::Phone; + d.profileLabel = "OBEX/PAN"; + } else if (hasPaSink || hasPaSrc || hasA2dp || hasHfp || isCoDAudio || + iconLow.rfind("audio-", 0) == 0) { + d.kind = BtDevKind::Audio; + if (d.connected) { + auto it = cardActiveProfile.find("bluez_card." + macU); + std::string activeProf = + (it != cardActiveProfile.end()) ? toLowerStr(it->second) : ""; + if (activeProf.rfind("headset-head-unit", 0) == 0 || + activeProf.find("hfp") != std::string::npos || + activeProf.find("hsp") != std::string::npos) { + d.profileLabel = "HSP/HFP"; + } else if (activeProf.rfind("a2dp", 0) == 0) { + d.profileLabel = "A2DP"; + } else if (hasPaSrc) { + d.profileLabel = "HSP/HFP"; + } else if (hasPaSink) { + d.profileLabel = "A2DP"; + } else if (hasA2dp) { + d.profileLabel = "A2DP"; + } else if (hasHfp) { + d.profileLabel = "HSP/HFP"; + } else { + d.profileLabel = "A2DP"; + } + } else { + if (hasA2dp && hasHfp) d.profileLabel = "Audio A2DP/HFP"; + else if (hasHfp) d.profileLabel = "Audio HSP/HFP"; + else d.profileLabel = "Audio A2DP"; + } + } else if (hasHid) { + d.kind = BtDevKind::Keyboard; + d.profileLabel = "HID Input"; + } +} + +std::vector queryBtDevices(const std::string& scanRaw = "") { + std::vector out; + std::unordered_map snapByMac; + bool usingSnapshot = (gCachedBtSnapshot && gCachedBtSnapshot->valid); + + if (usingSnapshot) { + for (const auto& rd : gCachedBtSnapshot->devs) { + BtDeviceEntry d; + d.mac = rd.mac; + d.name = rd.name; + d.paired = rd.paired; + d.connected = rd.connected; + d.batteryPct = rd.batteryPct; + out.push_back(d); + snapByMac[rd.mac] = &rd; + } + } else { + std::unordered_set pairedMacs; + std::unordered_set connectedMacs; + + auto parseMacSet = [](const std::string& raw, + std::unordered_set& dst) { + std::istringstream ss(raw); + std::string line; + while (std::getline(ss, line)) { + if (line.rfind("Device ", 0) == 0 && line.size() >= 24) { + dst.insert(line.substr(7, 17)); + } + } + }; + + parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || " + "timeout 2 bluetoothctl paired-devices 2>/dev/null"), + pairedMacs); + parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"), + connectedMacs); + + std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null"); + std::istringstream ss(allRaw); + std::string line; + while (std::getline(ss, line)) { + if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue; + BtDeviceEntry d; + d.mac = line.substr(7, 17); + d.name = (line.size() > 25) ? trimStr(line.substr(25)) : d.mac; + d.paired = (pairedMacs.count(d.mac) > 0); + d.connected = (connectedMacs.count(d.mac) > 0); + out.push_back(d); + } } auto isRawMacName = [](const BtDeviceEntry& e) { @@ -793,109 +990,99 @@ std::vector queryBtDevices(const std::string& scanRaw = "") { return a.name < b.name; }); + bool anyConnected = false; for (const auto& d : out) { - if (infoCount >= 24) break; - if (d.connected || d.paired || !isRawMacName(d)) { - infoCmd += "printf '===BTDEV %s===\\n' " + shellQuote(d.mac) + - "; timeout 1 bluetoothctl info " + shellQuote(d.mac) + - " 2>/dev/null; "; - ++infoCount; + if (d.connected) { + anyConnected = true; + break; + } + } + std::string paRaw; + std::unordered_map cardActiveProfile; + if (anyConnected) { + paRaw = runCaptureCmd( + "pactl list sinks short 2>/dev/null; pactl list sources short 2>/dev/null; " + "pactl list cards 2>/dev/null"); + std::istringstream pss(paRaw); + std::string pline; + std::string curCard; + while (std::getline(pss, pline)) { + std::string t = trimStr(pline); + if (t.rfind("Name: bluez_card.", 0) == 0) { + curCard = trimStr(t.substr(6)); + } else if (!curCard.empty() && t.rfind("Active Profile:", 0) == 0) { + cardActiveProfile[curCard] = trimStr(t.substr(15)); + curCard.clear(); + } } } std::unordered_map infoByMac; - if (!infoCmd.empty()) { - std::string batchInfo = runCaptureCmd(infoCmd); - std::istringstream iss(batchInfo); - std::string iline; - std::string curMac; - while (std::getline(iss, iline)) { - if (iline.rfind("===BTDEV ", 0) == 0 && iline.size() >= 26) { - curMac = iline.substr(9, 17); - } else if (!curMac.empty()) { - infoByMac[curMac] += iline + "\n"; + if (!usingSnapshot) { + std::string infoCmd; + int infoCount = 0; + for (const auto& d : out) { + if (infoCount >= 24) break; + if (d.connected || d.paired || !isRawMacName(d)) { + infoCmd += "printf '===BTDEV %s===\\n' " + shellQuote(d.mac) + + "; timeout 1 bluetoothctl info " + shellQuote(d.mac) + + " 2>/dev/null; "; + ++infoCount; + } + } + if (!infoCmd.empty()) { + std::string batchInfo = runCaptureCmd(infoCmd); + std::istringstream iss(batchInfo); + std::string iline; + std::string curMac; + while (std::getline(iss, iline)) { + if (iline.rfind("===BTDEV ", 0) == 0 && iline.size() >= 26) { + curMac = iline.substr(9, 17); + } else if (!curMac.empty()) { + infoByMac[curMac] += iline + "\n"; + } } } } for (auto& d : out) { - std::string macU = d.mac; - for (char& c : macU) { - if (c == ':') c = '_'; + if (usingSnapshot) { + auto sit = snapByMac.find(d.mac); + if (sit != snapByMac.end() && sit->second) { + const BtRawDevSnapshot* rd = sit->second; + classifyBtDevice(d, paRaw, cardActiveProfile, rd->icon, rd->devClass, + rd->hasClass, rd->uuidsLow); + } else { + classifyBtDevice(d, paRaw, cardActiveProfile, "", 0, false, ""); + } + continue; } - bool hasPaSink = (paRaw.find("bluez_output." + macU) != std::string::npos); - bool hasPaSrc = (paRaw.find("bluez_input." + macU) != std::string::npos); std::string info = infoByMac[d.mac]; std::string infoLow = toLowerStr(info); - std::string nameLow = toLowerStr(d.name); - - bool hasA2dp = (infoLow.find("0000110b-") != std::string::npos || - infoLow.find("audio sink") != std::string::npos); - bool hasHfp = (infoLow.find("00001108-") != std::string::npos || - infoLow.find("0000111e-") != std::string::npos); - bool hasHid = (infoLow.find("00001124-") != std::string::npos || - infoLow.find("00001812-") != std::string::npos || - infoLow.find("human interface device") != std::string::npos); - bool isPhoneOrPc = (infoLow.find("icon: phone") != std::string::npos || - infoLow.find("icon: computer") != std::string::npos); - - if (infoLow.find("icon: input-gaming") != std::string::npos || - infoLow.find("icon: input-joystick") != std::string::npos || - nameLow.find("gamepad") != std::string::npos || - nameLow.find("controller") != std::string::npos || - nameLow.find("joy-con") != std::string::npos || - nameLow.find("dualshock") != std::string::npos || - nameLow.find("dualsense") != std::string::npos || - nameLow.find("8bitdo") != std::string::npos || - nameLow.find("xbox") != std::string::npos) { - d.kind = BtDevKind::Gamepad; - d.profileLabel = "HID Gamepad"; - } else if (infoLow.find("icon: input-keyboard") != std::string::npos || - nameLow.find("keyboard") != std::string::npos || - nameLow.find("keychron") != std::string::npos) { - d.kind = BtDevKind::Keyboard; - d.profileLabel = "HID Keyboard"; - } else if (infoLow.find("icon: input-mouse") != std::string::npos || - infoLow.find("icon: input-tablet") != std::string::npos || - nameLow.find("mouse") != std::string::npos || - nameLow.find("trackpad") != std::string::npos) { - d.kind = BtDevKind::Mouse; - d.profileLabel = "HID Mouse"; - } else if (isPhoneOrPc) { - d.kind = BtDevKind::Phone; - d.profileLabel = "OBEX/PAN"; - } else if (hasPaSink || hasPaSrc || hasA2dp || hasHfp || - infoLow.find("icon: audio-") != std::string::npos) { - d.kind = BtDevKind::Audio; - if (d.connected) { - std::string activeProf = toLowerStr(cardActiveProfile["bluez_card." + macU]); - if (activeProf.rfind("headset-head-unit", 0) == 0 || - activeProf.find("hfp") != std::string::npos || - activeProf.find("hsp") != std::string::npos) { - d.profileLabel = "HSP/HFP"; - } else if (activeProf.rfind("a2dp", 0) == 0) { - d.profileLabel = "A2DP"; - } else if (hasPaSrc) { - d.profileLabel = "HSP/HFP"; - } else if (hasPaSink) { - d.profileLabel = "A2DP"; - } else if (hasA2dp) { - d.profileLabel = "A2DP"; - } else if (hasHfp) { - d.profileLabel = "HSP/HFP"; - } else { - d.profileLabel = "A2DP"; + std::string iconLow; + unsigned long devClass = 0; + bool hasClass = false; + { + std::istringstream issInfo(infoLow); + std::string il; + while (std::getline(issInfo, il)) { + std::string t = trimStr(il); + if (t.rfind("icon:", 0) == 0) { + iconLow = trimStr(t.substr(5)); + } else if (t.rfind("class:", 0) == 0) { + std::string cs = trimStr(t.substr(6)); + char* endp = nullptr; + unsigned long cls = std::strtoul(cs.c_str(), &endp, 0); + if (endp != cs.c_str() && cls != 0) { + devClass = cls; + hasClass = true; + } } - } else { - if (hasA2dp && hasHfp) d.profileLabel = "Audio A2DP/HFP"; - else if (hasHfp) d.profileLabel = "Audio HSP/HFP"; - else d.profileLabel = "Audio A2DP"; } - } else if (hasHid) { - d.kind = BtDevKind::Keyboard; - d.profileLabel = "HID Input"; } + classifyBtDevice(d, paRaw, cardActiveProfile, iconLow, devClass, hasClass, + infoLow); size_t batPos = info.find("Battery Percentage:"); if (batPos != std::string::npos) { @@ -927,20 +1114,29 @@ BtControllerState queryBtController(bool btOn, st.discoverable = readSavedBtDiscoverable(); if (btOn) { - std::string showOut = runCaptureCmd("timeout 2 bluetoothctl show 2>/dev/null"); - std::istringstream ss(showOut); - std::string line; - while (std::getline(ss, line)) { - std::string t = trimStr(line); - if (t.rfind("Discoverable:", 0) == 0) { - std::string v = toLowerStr(trimStr(t.substr(13))); - if (v == "yes") st.discoverable = true; - else if (v == "no") st.discoverable = false; - } else if (t.rfind("Alias:", 0) == 0) { - std::string al = trimStr(t.substr(6)); - if (!al.empty() && al.rfind("BlueZ", 0) != 0 && - ::access((getHomeDirPath() + "/.config/sxmo/bt_name").c_str(), F_OK) != 0) { - st.name = al; + if (gCachedBtSnapshot && gCachedBtSnapshot->valid) { + st.discoverable = gCachedBtSnapshot->discoverable; + const std::string& al = gCachedBtSnapshot->alias; + if (!al.empty() && al.rfind("BlueZ", 0) != 0 && + ::access((getHomeDirPath() + "/.config/sxmo/bt_name").c_str(), F_OK) != 0) { + st.name = al; + } + } else { + std::string showOut = runCaptureCmd("timeout 2 bluetoothctl show 2>/dev/null"); + std::istringstream ss(showOut); + std::string line; + while (std::getline(ss, line)) { + std::string t = trimStr(line); + if (t.rfind("Discoverable:", 0) == 0) { + std::string v = toLowerStr(trimStr(t.substr(13))); + if (v == "yes") st.discoverable = true; + else if (v == "no") st.discoverable = false; + } else if (t.rfind("Alias:", 0) == 0) { + std::string al = trimStr(t.substr(6)); + if (!al.empty() && al.rfind("BlueZ", 0) != 0 && + ::access((getHomeDirPath() + "/.config/sxmo/bt_name").c_str(), F_OK) != 0) { + st.name = al; + } } } } @@ -1061,6 +1257,7 @@ int runNetworksApp(int argc, char** argv) { // Bluetooth target device BtDeviceEntry targetBt; + bool forceFreshBtState = false; // Incoming OBEX confirmation & directory picker state ObexPromptInfo obexPrompt; @@ -1115,32 +1312,46 @@ int runNetworksApp(int argc, char** argv) { } else if (activeTab == NetTab::Bluetooth) { btOn = isBtEnabledFast(); std::string scanRaw; + BtStateSnapshot snap; if (btOn) { int obexPid = readIntFile("/tmp/bananarchy_bt_obex.pid"); if (obexPid <= 0 || (::kill(obexPid, 0) != 0 && errno != EPERM)) { runAsyncCmd("doas -n /usr/bin/bananarchy-bt-obex start >/dev/null 2>&1"); } btRx = readBtRxStatus(); + snap = loadBtStateSnapshot(forceFreshBtState); + forceFreshBtState = false; if (forceScan) { // 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) { + bool needPowerOn = false; + if (snap.valid) { + needPowerOn = !snap.powered; + } else { + std::string show = runCaptureCmd( + "timeout 2 bluetoothctl show 2>/dev/null"); + needPowerOn = (show.find("Powered: no") != std::string::npos || + show.find("Powered:") == std::string::npos); + } + if (needPowerOn) { 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"); + snap = loadBtStateSnapshot(true); } + gCachedBtSnapshot = snap.valid ? &snap : nullptr; btList = queryBtDevices(scanRaw); } else { + forceFreshBtState = false; btList.clear(); + gCachedBtSnapshot = nullptr; } btCtrl = queryBtController(btOn, btList); + gCachedBtSnapshot = nullptr; int maxRow = btOn ? (4 + static_cast(btList.size())) : 2; if (btRowSel > maxRow) btRowSel = maxRow; } @@ -2242,6 +2453,7 @@ int runNetworksApp(int argc, char** argv) { runCaptureCmd("timeout 2 bluetoothctl system-alias " + shellQuote(clean) + " >/dev/null 2>&1"); } + forceFreshBtState = true; refreshCurrentTab(false); setBanner("Bluetooth name: " + clean); }; @@ -2256,6 +2468,7 @@ int runNetworksApp(int argc, char** argv) { "timeout 2 bluetoothctl discoverable " + std::string(nextDisc ? "on" : "off") + " >/dev/null 2>&1"); } + forceFreshBtState = true; refreshCurrentTab(false); setBanner(nextDisc ? "Bluetooth: Visible for 60s" : "Bluetooth: Hidden from discovery"); @@ -2295,6 +2508,7 @@ int runNetworksApp(int argc, char** argv) { runAsyncCmd("sxmo_audio.sh device setinput Mic1 >/dev/null 2>&1; " "sxmo_audio.sh device set Speaker >/dev/null 2>&1"); } + forceFreshBtState = true; refreshCurrentTab(false); setBanner("Disconnected " + targetBt.name); } else if (act == 2) { @@ -2351,6 +2565,7 @@ int runNetworksApp(int argc, char** argv) { } else if (act == 4) { runCaptureCmd("timeout 3 bluetoothctl remove " + shellQuote(targetBt.mac) + " >/dev/null 2>&1", &rc); + forceFreshBtState = true; refreshCurrentTab(false); setBanner("Removed " + targetBt.name); } @@ -2513,6 +2728,7 @@ int runNetworksApp(int argc, char** argv) { render(); runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh " + std::string(btOn ? "off" : "on") + " >/dev/null 2>&1"); + forceFreshBtState = true; refreshCurrentTab(false); setBanner(btOn ? "Bluetooth enabled" : "Bluetooth disabled"); } else if (btRowSel == 1) { @@ -2580,6 +2796,7 @@ int runNetworksApp(int argc, char** argv) { setBanner("Turning Bluetooth ON..."); render(); runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1"); + forceFreshBtState = true; refreshCurrentTab(false); } else { setBanner("Scanning Bluetooth (15s)...", 16000); @@ -3071,6 +3288,7 @@ int runNetworksApp(int argc, char** argv) { ::unlink(kBtOpDonePath); if (!opMac.empty()) targetBt.mac = opMac; if (!opName.empty()) targetBt.name = opName; + forceFreshBtState = true; refreshCurrentTab(false); refreshTargetBtFromList(); if (opMode == "pair") {