diff --git a/AGENTS.md b/AGENTS.md index c7c86cd..371e934 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,10 +44,20 @@ Keep this file short. Full details live in `README.md`, `MANUAL.md`, `SDK.md`, ` ## Critical invariants -- Bluetooth requires `ControllerMode = dual` in `etc/bluetooth/main.conf`; BlueZ 5.87 rejects LE-only HOGP in `bredr` - mode. Keep `UserspaceHID=true`, `LEAutoSecurity=true`, `ClassicBondedOnly=false`, and `IdleTimeout=0` in `input.conf`. - `bananarchy-bt-obex` must power on, enable LE, select the LE bearer for HID-over-GATT devices, and pair unbonded - devices. `util-linux-misc` and `bluez-btmgmt` support the live PTY scan wrapper. +- Bluetooth requires `ControllerMode = dual` and `Class = 0x5a020c` (`btmgmt -i hci0 class 2 3`) in `etc/bluetooth/main.conf` + and `bananarchy-bt-le-enable.sh`; BlueZ 5.87 rejects LE-only HOGP in `bredr` mode, and `a2dp_source` must stay out + of `50-bluetooth.conf` so paired Android phones recognize Object Push rather than an audio sink. Keep `UserspaceHID=true`, + `LEAutoSecurity=true`, `ClassicBondedOnly=false`, and `IdleTimeout=0` in `input.conf`. `bananarchy-bt-obex` must power on, + enable LE, select the LE bearer (`PreferredBearer = "le"`) for HID-over-GATT devices, select the BR/EDR bearer + (`PreferredBearer = "bredr"`, public address preference, `ConnectProfile` fallback) for Classic Audio / dual-mode + BT 5.x/6.x headsets, pair unbonded devices, forward `(AVRCP)` media keys to `xmusic`, handle both L2CAP `SOCK_SEQPACKET` + and RFCOMM via `ObexPacketReader` with `xnetworks` incoming confirmation / target folder (`~/.config/sxmo/bt_obex_dir`) IPC, + and keep discoverability hidden-by-default with a 60 s timeout (`bt_discoverable=0`, never `discoverable-timeout 0`). + Keep all four `50-bluetooth.conf` copies synced with `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`). `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 process aborts. Keep the Webarchy renderer fallback. diff --git a/CHANGELOG.md b/CHANGELOG.md index 93e1ca5..c8226c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,12 @@ Release versions follow the `
` format (where `2026` is `a`, Upcoming release build (`a1120` / `cocojamboo` via `scripts/version.sh`) targeting **Nokia 8110 4G (`nokia-argon`)**, **Nokia 2720 Flip (`nokia-beatles`)**, **Nokia 800 Tough (`nokia-coconut`)**, and **Nokia 8000 4G (`nokia-sparkler`)** while keeping `a1114` (`carbonara`) as the current published release. +### Bluetooth 5.x/6.x headset support (`A2DP` + `HSP/HFP`), Android OBEX file transfer, AVRCP controls, and power safeguards across all targets + +- **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`. + ### Nokia 8000 4G (`nokia-sparkler`) hardware-verified `lk2nd`, 4-core SMP/`cpufreq`, 157 Hz haptic audio, camera, and EDL bring-up - **Layered `lk2nd` port (`bootloader/lk2nd/nokia-sparkler.patch`)**: added `nokia-sparkler.dtsi` (`msm8909-mtp.dts` `/lk2nd/nokia-sparkler`, matching `androidboot.hw.name=sparkler` without requiring `lk2nd,match-panel;`, GC9307 HLT 15-command and ST7789VX2 CTC 11-command 2.8" SPI init streams on BLSP1 QUP5 `0x078b9000`, `*` on `gpio90` as `KEY_VOLUMEUP` `0x115` alongside `#` `pm8941_resin` and Top Power) plus `"nokia,sparkler"` / `"nokia,leo"` support in `spi-display.c`; added `scripts/build-lk2nd-sparkler.sh`, `scripts/check-lk2nd-sparkler.py`, and `scripts/test-lk2nd-sparkler-port.py`, building `images/boot-lk2nd-nokia-sparkler{,-diagnostic,-display}.img` without altering `nokia-beatles` or `nokia-coconut` `lk2nd` images. @@ -66,10 +72,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 `6b5c17059bf0341fdeb84c85dca08e64eb6b634e71add27fb9b7a93d17fb7ed8` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `5b5c9eb85992a4531e960d3f00e4551366ec9abcf787f521e3400e81e5a8cbc5`, alongside `bootloader/lk2nd-msm8909.img`). - - `images/bananarchy-nokia-beatles.img`: SHA-256 `c6dad8d28ab3ab478869a0adb78dac1af4e19c111ab60a066687656c103e5723`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `4fd4b19d525677b2e2880346b391d9a13447d62f8ad61ee0088421a100ec08dc`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `476dd86e7078488126c08151a586cebc94f52a03d588cb0b18d7589430cee252`). - - `images/bananarchy-nokia-coconut.img`: SHA-256 `77addc7d48e40cdd017dc247969131e9ab7bc87ad590faf879d36c03b66df65c`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `a5869b63de5cbfca3f6d87583aba162023670945f69a57276b597e1a7b85c5b2`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `70b6330654490843c07e9a47b5d509811038f5152d8030fdb8740437485e2df6`). - - `images/bananarchy-nokia-sparkler.img`: SHA-256 `a41a6ed4c2a04d521cf44d5229680f292972a4fc06ff3ad177cc3a13659295d1`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `e950788360e1044d5ef128d1a170b868620aa5c356354aa6ac7178218e4d8e38`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `1e1c1f9f28b8d891b25701a01baeaebb54dee3368f40e6e12564fc53243a76a4`). + - `images/bananarchy-nokia-argon.img`: SHA-256 `92b23d34180c157861c492e7c2ea848ea4580857f3c1674020ae6b9f6fbdd39f` (packaged in `bananarchy-nokia-argon-a1120-cocojamboo.zip`, SHA-256 `f3680c940ba95f063822e033c60fc18faa3fd20faab4dcec558445d6d1d828f0`, alongside `bootloader/lk2nd-msm8909.img`). + - `images/bananarchy-nokia-beatles.img`: SHA-256 `5c284c314a378d09fda37e56ebe745ab557d45c77499206440e8c362c709e7a7`, `images/boot-bananarchy-nokia-beatles.img`: SHA-256 `80485ccf2af4f1d6107965ecde43d888c66ec19006e6feabc7fb63b6a7852391`, and `images/boot-lk2nd-nokia-beatles-display.img`: SHA-256 `b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d` (packaged in `bananarchy-nokia-beatles-a1120-cocojamboo.zip`, SHA-256 `1d2849c73dcf3d0bf8d0e2417778366bd726442556567ab9180e314951a5b993`). + - `images/bananarchy-nokia-coconut.img`: SHA-256 `4e1d4799d42f56423f9cba8e175adf3b1f6c7fcd89965a7bc0b84a4f03ebc6e5`, `images/boot-bananarchy-nokia-coconut.img`: SHA-256 `1e22879fc0533f419dc98c88a1700d75101fda85669837d1457bb15b9ab4ed9c`, and `images/boot-lk2nd-nokia-coconut-display.img`: SHA-256 `e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a` (packaged in `bananarchy-nokia-coconut-a1120-cocojamboo.zip`, SHA-256 `af06ab7bbb3933732f644d24acb03d04ef066d59aae0c2009d0c9cf367bec4d1`). + - `images/bananarchy-nokia-sparkler.img`: SHA-256 `6b40db4674821bdde80d6f7619acc5a6414df684201d3e4e2e7cc3ac6c25dcfd`, `images/boot-bananarchy-nokia-sparkler.img`: SHA-256 `8f41328f0197f5debba92eaffa9df46c530721719309024a4d9cd7bf79a722c7`, and `images/boot-lk2nd-nokia-sparkler-display.img`: SHA-256 `bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f` (packaged in `bananarchy-nokia-sparkler-a1120-cocojamboo.zip`, SHA-256 `0ca08f7a58e517fce283028548ba6d7657c419e823782fe188c75b0fbd93d378`). --- diff --git a/MANUAL.md b/MANUAL.md index 0c73f02..da3b143 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -220,7 +220,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. The scan now drives one interactive `bluetoothctl` client through `script(1)` (`/usr/local/bin/bluetoothctl` -> `/usr/bin/bananarchy-bt-scan.sh`), sets auto transport and duplicate-data, asks the same client for `devices` three times while discovery is active, parses both `[NEW] Device ...` / `[CHG] Device ...` and `Device ` lines, and stops discovery cleanly before the client exits; the controller is also powered on automatically if `bluetoothctl show` reports `Powered: no`. A narrow `doas` helper runs `btmgmt -i hci0 le on` before discovery because this WCNSS controller otherwise starts with LE disabled and only performs BR/EDR inquiry. BlueZ keeps `ControllerMode = dual`: `bredr` mode rejects the LE-only HOGP profile, so BLE HID devices would connect at the GATT level but never create a keyboard or mouse input node. **Connect Device** powers the adapter on, enables LE, selects the LE bearer for HID-over-GATT devices and automatically pairs unpaired peripherals; **Pair & Trust Device** still does this explicitly. 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** (`OFF (Hidden)` by default to avoid continuous Inquiry Scan standby draw, or `ON (Visible for 60s)`, 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), configure the **OBEX File Receiver** (`OBEX Dir: [Set]`, opening actions to **Set Target Directory...** via an interactive folder picker including `/media/sdcard`, **Open Folder in Files**, or **Reset to ~/Downloads**, persisted in `~/.config/sxmo/bt_obex_dir`; `#` quick-opens the folder in `xfiles`), scan nearby devices (`*` or `Scan`, 15-second discovery scan), and manage paired/discovered devices. Incoming OBEX file pushes (over both L2CAP `SOCK_SEQPACKET` and RFCOMM, with Smartphone Class of Device `0x5a020c` and no `a2dp_source` role so paired Android phones recognize OPP rather than a headset) pop up an interactive confirmation dialog showing sender, filename, size, **Accept & Save File**, **Dir: ... [Set]** to pick a different destination folder on the spot, and **Reject Transfer**. The scan now drives one interactive `bluetoothctl` client through `script(1)` (`/usr/local/bin/bluetoothctl` -> `/usr/bin/bananarchy-bt-scan.sh`), sets auto transport and duplicate-data, asks the same client for `devices` three times while discovery is active, parses both `[NEW] Device ...` / `[CHG] Device ...` and `Device ` lines, and stops discovery cleanly before the client exits; the controller is also powered on automatically if `bluetoothctl show` reports `Powered: no`. A narrow `doas` helper runs `btmgmt -i hci0 le on` before discovery because this WCNSS controller otherwise starts with LE disabled and only performs BR/EDR inquiry. BlueZ keeps `ControllerMode = dual`: `bredr` mode rejects the LE-only HOGP profile, so BLE HID devices would connect at the GATT level but never create a keyboard or mouse input node. **Connect Device** and **Pair & Trust Device** power the adapter on, enable LE, select the `le` bearer for HID-over-GATT devices, prefer public BR/EDR entries and the `bredr` bearer (`ConnectProfile` A2DP/HFP fallback) for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets, and automatically pair unpaired peripherals. 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`, `sbc_xq`, `aac`, `ldac` ABR `auto`, `aptx`, `aptx_hd`) with AVRCP hardware volume and Play/Pause/Next/Prev headset button control of `xmusic`, and **HSP/HFP** (`CVSD` 8 kHz over QDSP6 `INTERNAL_BT_SCO`, with `mSBC`/`LC3-A127`/`LC3` and unsupported LE Audio BAP roles disabled, plus headset `ATA` call answer/A2DP restore synchronization), **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 18ac1a8..01c9f83 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,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`. Bluetooth discovery runs through `/usr/local/bin/bluetoothctl` and `bananarchy-bt-scan.sh`, which keeps one interactive `bluetoothctl` PTY client alive, sets auto transport and duplicate-data, queries `devices` during active discovery, and stops discovery cleanly so unpaired peripherals are not dropped when the scan command exits. A narrow `doas` helper runs `btmgmt -i hci0 le on` before each scan because the WCNSS controller otherwise powers up with LE disabled and only performs BR/EDR inquiry. BlueZ runs in `dual` controller mode because `bredr` mode rejects the LE-only HOGP profile, leaving BLE keyboards and mice connected but without a usable input node. Pair/connect actions power the adapter on, enable LE, force the LE bearer for HID-over-GATT devices, and pair unbonded peripherals before connecting. +- **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 reception (advertising Smartphone CoD `0x5a020c` without `a2dp_source` headset spoofing, supporting both L2CAP `SOCK_SEQPACKET` GOEP 2.0 and RFCOMM, presenting an incoming Accept/Reject and folder-selection modal in `xnetworks` alongside configurable persistent target folder in `~/.config/sxmo/bt_obex_dir`) and **Send via Bluetooth** in `xfiles`. Bluetooth discovery runs through `/usr/local/bin/bluetoothctl` and `bananarchy-bt-scan.sh`, which keeps one interactive `bluetoothctl` PTY client alive, sets auto transport and duplicate-data, queries `devices` during active discovery, and stops discovery cleanly so unpaired peripherals are not dropped when the scan command exits. A narrow `doas` helper runs `btmgmt -i hci0 le on` (and sets Smartphone controller class `2 3`) before each scan because the WCNSS controller otherwise powers up with LE disabled and only performs BR/EDR inquiry. BlueZ runs in `dual` controller mode because `bredr` mode rejects the LE-only HOGP profile, leaving BLE keyboards and mice connected but without a usable input node. Pair/connect actions power the adapter on, enable LE, force the LE bearer for HID-over-GATT devices, prefer public BR/EDR bearers and A2DP/HFP `ConnectProfile` fallback for Classic Audio / dual-mode Bluetooth 5.x/6.x headsets, keep controller visibility hidden by default with a 60 s discoverable timeout to save standby battery, and pair unbonded peripherals before connecting. WirePlumber restricts headset roles to `a2dp_sink hsp_hs hfp_hf`, locks HFP to 8 kHz `cvsd` (disabling `msbc` and `lc3-a127`/`lc3` to match QDSP6 `INTERNAL_BT_SCO`), enables LDAC ABR (`quality = "auto"`) and `dummy-avrcp-player` for hardware volume, and forwards headset AVRCP media keys through `bananarchy-bt-obex` to `xmusic`. - **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`, `xquagr`, `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/etc/bluetooth/main.conf b/overlay/rootfs/etc/bluetooth/main.conf index 3aa3eee..fefce67 100644 --- a/overlay/rootfs/etc/bluetooth/main.conf +++ b/overlay/rootfs/etc/bluetooth/main.conf @@ -4,6 +4,7 @@ DiscoverableTimeout = 60 PairableTimeout = 60 ControllerMode = dual +Class = 0x5a020c MultiProfile = multiple JustWorksRepairing = always Experimental = true diff --git a/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf index 3d5c3db..1d67e12 100644 --- a/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf +++ b/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -18,11 +18,15 @@ wireplumber.settings = { } monitor.bluez.properties = { - bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] - bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_duplex ] bluez5.enable-sbc-xq = true bluez5.enable-msbc = false + bluez5.enable-lc3-a127 = false bluez5.enable-hw-volume = true + bluez5.dummy-avrcp-player = true + bluez5.a2dp.ldac.quality = "auto" + bluez5.a2dp.aac.bitratemode = 0 bluez5.hfphsp-backend = "native" bluez5.hfphsp-backend-native-modem = "any" } diff --git a/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf index 3d5c3db..1d67e12 100644 --- a/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf +++ b/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -18,11 +18,15 @@ wireplumber.settings = { } monitor.bluez.properties = { - bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] - bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_duplex ] bluez5.enable-sbc-xq = true bluez5.enable-msbc = false + bluez5.enable-lc3-a127 = false bluez5.enable-hw-volume = true + bluez5.dummy-avrcp-player = true + bluez5.a2dp.ldac.quality = "auto" + bluez5.a2dp.aac.bitratemode = 0 bluez5.hfphsp-backend = "native" bluez5.hfphsp-backend-native-modem = "any" } diff --git a/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf index 3d5c3db..1d67e12 100644 --- a/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf +++ b/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -18,11 +18,15 @@ wireplumber.settings = { } monitor.bluez.properties = { - bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] - bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_duplex ] bluez5.enable-sbc-xq = true bluez5.enable-msbc = false + bluez5.enable-lc3-a127 = false bluez5.enable-hw-volume = true + bluez5.dummy-avrcp-player = true + bluez5.a2dp.ldac.quality = "auto" + bluez5.a2dp.aac.bitratemode = 0 bluez5.hfphsp-backend = "native" bluez5.hfphsp-backend-native-modem = "any" } diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh b/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh index 36338ba..dee6113 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh +++ b/overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh @@ -8,4 +8,5 @@ if [ "$(id -u)" -ne 0 ]; then exit 1 fi +/usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true exec /usr/bin/btmgmt -i hci0 le on diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-obex b/overlay/rootfs/usr/bin/bananarchy-bt-obex index bd65704..f567ad6 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-obex +++ b/overlay/rootfs/usr/bin/bananarchy-bt-obex @@ -18,24 +18,70 @@ RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status" TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status" PID_FILE = "/tmp/bananarchy_bt_obex.pid" DURESS_FLAG = "/tmp/bananarchy_duress_mode" +OBEX_CFG_FILE = "/home/user/.config/sxmo/bt_obex_dir" +OBEX_IPC_DIR = "/run/bananarchy/bt-obex" +OBEX_PROMPT_FILE = "/run/bananarchy/bt-obex/prompt.tsv" +OBEX_DECISION_FILE = "/run/bananarchy/bt-obex/decision.tsv" +OBEX_PROMPT_LOCK = threading.Lock() def is_duress_mode(): return os.path.exists(DURESS_FLAG) -def get_downloads_dir(): +def shorten_obex_dir(path): + if not path: + return "~/Downloads" + if path == "/home/user": + return "~" + if path.startswith("/home/user/"): + return "~/" + path[len("/home/user/"):] + return path + + +def sanitize_obex_target_dir(raw_dir): + duress_base = "/tmp/duress_home" + default_dir = os.path.join(duress_base, "Downloads") if is_duress_mode() else "/home/user/Downloads" + cand = str(raw_dir or "").strip() + if not cand or "\n" in cand or "\r" in cand or "\t" in cand: + cand = default_dir + if not cand.startswith("/"): + cand = default_dir + norm = os.path.normpath(cand) if is_duress_mode(): - base = "/tmp/duress_home" - else: - base = "/home/user" - dl = os.path.join(base, "Downloads") - os.makedirs(dl, exist_ok=True) + if norm != duress_base and not norm.startswith(duress_base + "/"): + norm = default_dir + os.makedirs(norm, exist_ok=True) + if norm.startswith("/home/user") or norm.startswith(duress_base): + try: + os.chown(norm, 10000, 10000) + except OSError: + pass + return norm + + +def get_configured_obex_dir(): + raw = "" + if not is_duress_mode() and os.path.exists(OBEX_CFG_FILE): + try: + with open(OBEX_CFG_FILE, "r", encoding="utf-8") as cf: + raw = cf.readline().strip() + except OSError: + raw = "" + return sanitize_obex_target_dir(raw) + + +def get_downloads_dir(): + return get_configured_obex_dir() + + +def ensure_obex_ipc_dir(): + os.makedirs(OBEX_IPC_DIR, mode=0o755, exist_ok=True) try: - os.chown(dl, 10000, 10000) + os.chmod(OBEX_IPC_DIR, 0o755) + os.chown(OBEX_IPC_DIR, 10000, 10000) except OSError: pass - return dl def write_status(path, text): @@ -49,15 +95,17 @@ def write_status(path, text): pass -def notify_networks_ui(): +def notify_networks_ui(msg="REFRESH_BT\n"): fifo = "/tmp/dwm_plugin_networks.fifo" if os.path.exists(fifo): try: fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK) - os.write(fd, b"REFRESH_BT\n") + os.write(fd, msg.encode("utf-8")) os.close(fd) + return True except OSError: pass + return False def notify_user(title, body): @@ -115,42 +163,212 @@ def unique_dest_path(directory, filename): idx += 1 -def recv_exact(sock, n): - buf = bytearray() - while len(buf) < n: - chunk = sock.recv(n - len(buf)) - if not chunk: - return None - buf.extend(chunk) - return bytes(buf) +class ObexPacketReader: + """Read OBEX PDUs safely over both RFCOMM SOCK_STREAM and L2CAP SOCK_SEQPACKET.""" + + def __init__(self, sock): + self.sock = sock + self.buf = bytearray() + seq_val = getattr(socket, "SOCK_SEQPACKET", 5) + stype = getattr(sock, "type", socket.SOCK_STREAM) + try: + stype = sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE) + except Exception: + pass + self.is_seqpacket = (stype == seq_val) + + def _recv_exact_stream(self, n): + while len(self.buf) < n: + chunk = self.sock.recv(max(4096, n - len(self.buf))) + if not chunk: + return None + self.buf.extend(chunk) + out = bytes(self.buf[:n]) + del self.buf[:n] + return out + + def recv_packet(self): + if self.is_seqpacket and not self.buf: + dat = self.sock.recv(65536) + if not dat or len(dat) < 3: + return None, None + opcode = dat[0] + pkt_len = struct.unpack(">H", dat[1:3])[0] + if pkt_len < 3: + return opcode, b"" + if pkt_len <= len(dat): + return opcode, bytes(dat[3:pkt_len]) + self.buf.extend(dat) + hdr = self._recv_exact_stream(3) + if not hdr: + return None, None + payload = self._recv_exact_stream(pkt_len - 3) + if payload is None: + return None, None + return opcode, payload + + hdr = self._recv_exact_stream(3) + if not hdr: + return None, None + opcode = hdr[0] + pkt_len = struct.unpack(">H", hdr[1:3])[0] + if pkt_len < 3: + return opcode, b"" + payload = self._recv_exact_stream(pkt_len - 3) + if payload is None: + return None, None + return opcode, payload -def recv_obex_packet(sock): - hdr = recv_exact(sock, 3) - if not hdr: - return None, None - opcode = hdr[0] - pkt_len = struct.unpack(">H", hdr[1:3])[0] - if pkt_len < 3: - return opcode, b"" - payload = recv_exact(sock, pkt_len - 3) - if payload is None: - return None, None - return opcode, payload +def recv_obex_packet(sock_or_reader): + if isinstance(sock_or_reader, ObexPacketReader): + return sock_or_reader.recv_packet() + return ObexPacketReader(sock_or_reader).recv_packet() -def handle_obex_rx_session(sock): - sock.settimeout(30.0) +def _sock_peer_aborted(sock): + try: + rlist, _, _ = select.select([sock], [], [], 0.0) + if sock in rlist: + peek = sock.recv(1, socket.MSG_PEEK) + if not peek or peek[0] in (0xFF, 0x7F): + return True + except BlockingIOError: + return False + except OSError: + return True + return False + + +def request_user_obex_confirmation(sock, sender_name, sender_mac, file_name, + total_len, default_dir, timeout_sec=55.0): + with OBEX_PROMPT_LOCK: + ensure_obex_ipc_dir() + for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass + + req_id = f"{os.getpid()}_{int(time.monotonic() * 1000)}" + s_label = str(sender_name or sender_mac or "Bluetooth Device").replace("\t", " ").replace("\n", " ").strip() + s_mac = str(sender_mac or "").replace("\t", " ").replace("\n", " ").strip() + f_label = str(file_name or "file.bin").replace("\t", " ").replace("\n", " ").strip() + d_label = sanitize_obex_target_dir(default_dir).replace("\t", " ").replace("\n", " ").strip() + + tmp_prompt = OBEX_PROMPT_FILE + ".tmp" + with open(tmp_prompt, "w", encoding="utf-8") as pf: + pf.write(f"{req_id}\t{s_label}\t{s_mac}\t{f_label}\t{int(total_len or 0)}\t{d_label}\n") + try: + os.chmod(tmp_prompt, 0o644) + os.chown(tmp_prompt, 10000, 10000) + except OSError: + pass + os.replace(tmp_prompt, OBEX_PROMPT_FILE) + + sz_label = format_size(total_len) if total_len and total_len > 0 else "Unknown size" + write_status(RX_STATUS_FILE, f"PENDING\t{f_label}\t{s_label}\t{sz_label}") + + ui_disabled = (os.environ.get("BANANARCHY_OBEX_NO_UI") == "1") + if not ui_disabled: + try: + if os.path.exists("/usr/bin/bananarchy-lid-gate.sh"): + subprocess.Popen( + ["/usr/bin/bananarchy-lid-gate.sh", "wake"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + if not os.path.exists("/home/user/.config/sxmo/.novibrate"): + try: + if os.geteuid() == 0: + subprocess.Popen( + ["su", "-", "user", "-c", "sxmo_vibrate 180"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + else: + subprocess.Popen( + ["sxmo_vibrate", "180"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + if not notify_networks_ui(f"OBEX_PROMPT {req_id}\n"): + try: + if os.geteuid() == 0: + subprocess.Popen( + ["su", "-", "user", "-c", "DISPLAY=:0 /usr/bin/dwm-plugin networks obex-prompt"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + else: + subprocess.Popen( + ["/usr/bin/dwm-plugin", "networks", "obex-prompt"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + except Exception: + pass + else: + notify_networks_ui(f"OBEX_PROMPT {req_id}\n") + + deadline = time.monotonic() + timeout_sec + try: + while time.monotonic() < deadline: + if os.path.exists(OBEX_DECISION_FILE): + try: + with open(OBEX_DECISION_FILE, "r", encoding="utf-8", errors="replace") as df: + line = df.readline().strip() + parts = line.split("\t") + if len(parts) >= 2 and parts[0] == req_id: + accepted = (parts[1].strip().upper() == "ACCEPT") + chosen = parts[2].strip() if len(parts) >= 3 and parts[2].strip() else d_label + return accepted, sanitize_obex_target_dir(chosen), False + except OSError: + pass + if sock is not None and _sock_peer_aborted(sock): + return False, sanitize_obex_target_dir(d_label), True + time.sleep(0.1) + return False, sanitize_obex_target_dir(d_label), False + finally: + for p in (OBEX_PROMPT_FILE, OBEX_DECISION_FILE): + try: + if os.path.exists(p): + os.unlink(p) + except OSError: + pass + notify_networks_ui() + + +def handle_obex_rx_session(sock, sender_name="Bluetooth Device", sender_mac=""): + sock.settimeout(65.0) + reader = ObexPacketReader(sock) out_file = None out_path = None file_name = "" total_len = 0 rx_bytes = 0 last_ui_notify = 0.0 + awaiting_decision = True + target_dir = get_configured_obex_dir() + + def reset_rx_file_state(): + nonlocal out_file, out_path, file_name, total_len, rx_bytes, awaiting_decision, target_dir + if out_file: + try: + out_file.close() + except Exception: + pass + out_file = None + out_path = None + file_name = "" + total_len = 0 + rx_bytes = 0 + awaiting_decision = True + target_dir = get_configured_obex_dir() try: while True: - opcode, payload = recv_obex_packet(sock) + opcode, payload = recv_obex_packet(reader) if opcode is None: break @@ -167,15 +385,14 @@ def handle_obex_rx_session(sock): break elif opcode in (0xFF, 0x7F): # ABORT - if out_file: - out_file.close() - out_file = None - if out_path and os.path.exists(out_path): + stale_path = out_path + reset_rx_file_state() + if stale_path and os.path.exists(stale_path): try: - os.unlink(out_path) + os.unlink(stale_path) except OSError: pass - write_status(RX_STATUS_FILE, "IDLE\tReady (~/Downloads)") + write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() sock.sendall(struct.pack(">BH", 0xA0, 3)) break @@ -219,11 +436,39 @@ def handle_obex_rx_session(sock): if hi == 0xC3: # Length total_len = val - if body_chunks and out_file is None: + if awaiting_decision and is_final and not body_chunks and not file_name and total_len == 0: + sock.sendall(struct.pack(">BH", 0xC3, 3)) # Disallow empty Delete PUT + reset_rx_file_state() + continue + + if awaiting_decision: if not file_name: file_name = f"bt_rx_{int(time.time())}.bin" - dl_dir = get_downloads_dir() - out_path = unique_dest_path(dl_dir, file_name) + accepted, chosen_dir, remote_aborted = request_user_obex_confirmation( + sock, sender_name, sender_mac, file_name, total_len, get_configured_obex_dir() + ) + if remote_aborted: + write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") + notify_networks_ui() + reset_rx_file_state() + continue + if not accepted: + write_status( + RX_STATUS_FILE, + f"IDLE\tRejected {file_name} ({shorten_obex_dir(get_configured_obex_dir())})" + ) + notify_networks_ui() + sock.sendall(struct.pack(">BH", 0xC3, 3)) # Forbidden (Rejected) + reset_rx_file_state() + continue + awaiting_decision = False + target_dir = chosen_dir + sock.settimeout(30.0) + + if out_file is None: + if not file_name: + file_name = f"bt_rx_{int(time.time())}.bin" + out_path = unique_dest_path(target_dir, file_name) out_file = open(out_path, "wb") try: os.chown(out_path, 10000, 10000) @@ -237,7 +482,7 @@ def handle_obex_rx_session(sock): now = time.time() if not is_final: - if now - last_ui_notify >= 0.4: + if now - last_ui_notify >= 0.4 or rx_bytes == 0: pct = int((rx_bytes * 100) // total_len) if total_len > 0 else 0 write_status( RX_STATUS_FILE, @@ -247,29 +492,27 @@ def handle_obex_rx_session(sock): last_ui_notify = now sock.sendall(struct.pack(">BH", 0x90, 3)) # Continue else: - if out_file: - out_file.flush() - out_file.close() - out_file = None - try: - os.chown(out_path, 10000, 10000) - os.chmod(out_path, 0o644) - except OSError: - pass - saved_base = os.path.basename(out_path) - sz_str = format_size(rx_bytes) - write_status( - RX_STATUS_FILE, - f"RECEIVED\t{saved_base}\t{sz_str}\t{out_path}" - ) - notify_networks_ui() - notify_user("Bluetooth File Received", - f"{saved_base} ({sz_str}) saved to Downloads") + saved_base = os.path.basename(out_path) + saved_full = out_path + saved_dir_short = shorten_obex_dir(target_dir) + out_file.flush() + out_file.close() + out_file = None + try: + os.chown(saved_full, 10000, 10000) + os.chmod(saved_full, 0o644) + except OSError: + pass + sz_str = format_size(rx_bytes) + write_status( + RX_STATUS_FILE, + f"RECEIVED\t{saved_base}\t{sz_str}\t{saved_full}" + ) + notify_networks_ui() + notify_user("Bluetooth File Received", + f"{saved_base} ({sz_str}) saved to {saved_dir_short}") sock.sendall(struct.pack(">BH", 0xA0, 3)) # Success - out_path = None - file_name = "" - total_len = 0 - rx_bytes = 0 + reset_rx_file_state() elif op_base == 0x05: # SETPATH sock.sendall(struct.pack(">BH", 0xA0, 3)) @@ -277,12 +520,19 @@ def handle_obex_rx_session(sock): else: sock.sendall(struct.pack(">BH", 0xD1, 3)) # Not Implemented except Exception: + stale_path = out_path + reset_rx_file_state() + if stale_path and os.path.exists(stale_path): + try: + os.unlink(stale_path) + except OSError: + pass + finally: if out_file: try: out_file.close() except Exception: pass - finally: try: sock.close() except Exception: @@ -311,6 +561,84 @@ def open_input_inotify_fd(): return -1 +CLASSIC_AUDIO_UUID_PREFIXES = ( + "00001108-", # Headset (HSP) + "0000110a-", # Audio Source + "0000110b-", # Audio Sink (A2DP) + "0000110c-", # A/V Remote Control Target + "0000110e-", # A/V Remote Control + "00001112-", # Headset Audio Gateway + "0000111e-", # Handsfree (HFP) + "0000111f-", # Handsfree Audio Gateway +) + + +def is_hog_device_props(props): + if not isinstance(props, dict): + return False + uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] + return any(u.startswith("00001812-") for u in uuids) + + +def is_classic_audio_props(props): + if not isinstance(props, dict) or is_hog_device_props(props): + return False + uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] + if any(any(u.startswith(p) for p in CLASSIC_AUDIO_UUID_PREFIXES) for u in uuids): + return True + icon = str(props.get("Icon") or "").strip().lower() + if icon.startswith("audio-"): + return True + cod = props.get("Class") + if isinstance(cod, int) and (cod & 0x1F00) == 0x0400: + return True + return False + + +def avrcp_fifo_command_for_key(code): + mapping = { + 164: "PLAYPAUSE", # KEY_PLAYPAUSE + 200: "PLAY", # KEY_PLAYCD + 207: "PLAY", # KEY_PLAY + 201: "PAUSE", # KEY_PAUSECD + 119: "PAUSE", # KEY_PAUSE + 166: "STOP", # KEY_STOPCD + 128: "STOP", # KEY_STOP + 163: "NEXT", # KEY_NEXTSONG + 165: "PREV", # KEY_PREVIOUSSONG + } + return mapping.get(code) + + +def dispatch_avrcp_key(code): + cmd = avrcp_fifo_command_for_key(code) + if not cmd: + return False + if cmd != "PAUSE" and ( + os.path.exists("/tmp/sxmo_in_call") or + os.path.exists("/tmp/sxmo_call_ringing") + ): + return False + fifo = "/tmp/dwm_plugin_music.fifo" + if os.path.exists(fifo): + try: + fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK) + os.write(fd, (cmd + "\n").encode("ascii")) + os.close(fd) + return True + except OSError: + pass + if cmd == "PAUSE": + try: + env = os.environ.copy() + env.setdefault("XDG_RUNTIME_DIR", "/run/user/10000") + subprocess.Popen(["sxmo_playerctl.sh", "pause_all"], + env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except Exception: + pass + return True + + def run_gamepad_uinput_bridge(is_running, wake_r=-1): ev_fmt = "llHHi" ev_size = struct.calcsize(ev_fmt) @@ -348,6 +676,7 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): uinput_fd = None gamepads = {} # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}} + avrcp_devs = {} # path -> fd last_scan = 0.0 last_input_mtime = 0 inotify_fd = open_input_inotify_fd() @@ -427,9 +756,10 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): if not entry.startswith("event"): continue dev_path = f"/dev/input/{entry}" - if dev_path in gamepads: + if dev_path in gamepads or dev_path in avrcp_devs: continue sys_name_path = f"/sys/class/input/{entry}/device/name" + dname = "" try: with open(sys_name_path, "r", encoding="utf-8") as nf: dname = nf.read().strip() @@ -443,11 +773,22 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): fcntl.ioctl(fd, eviocgbit_key, buf, True) has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1) has_qwerty = bool((buf[16 // 8] >> (16 % 8)) & 1) and bool((buf[30 // 8] >> (30 % 8)) & 1) + has_avrcp_keys = any( + bool((buf[k // 8] >> (k % 8)) & 1) + for k in (163, 164, 165, 166, 200, 201) + ) + dlow = dname.lower() + is_avrcp_dev = ("(avrcp)" in dlow) or ( + has_avrcp_keys and not has_qwerty and not has_gamepad and + not any(w in dlow for w in ("gpio", "pm8941", "keypad", "pwrkey")) + ) if has_gamepad and not has_qwerty: ensure_uinput() gamepads[dev_path] = { "fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {} } + elif is_avrcp_dev: + avrcp_devs[dev_path] = fd else: os.close(fd) except Exception: @@ -456,7 +797,8 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): pass fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())} - wait_fds = list(fd_map.keys()) + avrcp_map = {fd: path for path, fd in list(avrcp_devs.items())} + wait_fds = list(fd_map.keys()) + list(avrcp_map.keys()) if inotify_fd >= 0: wait_fds.append(inotify_fd) if wake_r >= 0: @@ -487,6 +829,26 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): need_scan = True for rfd in rlist: + if rfd in avrcp_map: + apath = avrcp_map[rfd] + try: + data = os.read(rfd, ev_size * 16) + if not data: + raise OSError("EOF") + except OSError: + try: + os.close(rfd) + except OSError: + pass + avrcp_devs.pop(apath, None) + continue + offset = 0 + while offset + ev_size <= len(data): + _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset) + offset += ev_size + if ev_type == 0x01 and ev_val == 1: + dispatch_avrcp_key(ev_code) + continue path, info = fd_map.get(rfd, (None, None)) if not path: continue @@ -573,6 +935,11 @@ def run_gamepad_uinput_bridge(is_running, wake_r=-1): os.close(info["fd"]) except OSError: pass + for afd in avrcp_devs.values(): + try: + os.close(afd) + except OSError: + pass if uinput_fd is not None: try: fcntl.ioctl(uinput_fd, ui_dev_destroy) @@ -617,6 +984,23 @@ def set_hog_preferred_bearer(conn, dev_path, props=None): pass +def set_audio_preferred_bearer(conn, dev_path, props=None): + """Force BR/EDR bearer for Classic A2DP/HFP audio headsets before Pair/Connect.""" + if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"): + return + if not is_classic_audio_props(props): + return + try: + from jeepney import DBusAddress, new_method_call + prop_addr = DBusAddress(dev_path, bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + conn.send(new_method_call(prop_addr, "Set", "ssv", + ("org.bluez.Device1", "PreferredBearer", + ("s", "bredr")))) + except Exception: + pass + + def handle_agent_method_call(conn, msg, agent_path): from jeepney import new_method_return, MessageType if msg is None or msg.header.message_type != MessageType.method_call: @@ -675,14 +1059,14 @@ def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0): def register_bluez_services(conn, profile_path, agent_path): - from jeepney import DBusAddress, new_method_call + from jeepney import DBusAddress, MessageType, new_method_call try: aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez", interface="org.freedesktop.DBus.Properties") dbus_call_with_agent( conn, new_method_call(aprop, "Set", "ssv", - ("org.bluez.Adapter1", "PairableTimeout", ("u", 0))), + ("org.bluez.Adapter1", "PairableTimeout", ("u", 60))), agent_path, timeout=2.0 ) @@ -716,23 +1100,68 @@ def register_bluez_services(conn, profile_path, agent_path): try: pm = DBusAddress("/org/bluez", bus_name="org.bluez", interface="org.bluez.ProfileManager1") - opts = { + opts_v = { + "Name": ("s", "OBEX Object Push"), + "Role": ("s", "server"), + "Channel": ("q", 9), + "Version": ("q", 0x0102), + "RequireAuthentication": ("b", False), + "RequireAuthorization": ("b", False), + } + opts_basic = { "Name": ("s", "OBEX Object Push"), "Role": ("s", "server"), "Channel": ("q", 9), "RequireAuthentication": ("b", False), "RequireAuthorization": ("b", False), - "AutoConnect": ("b", True), } - dbus_call_with_agent( - conn, - new_method_call(pm, "RegisterProfile", "osa{sv}", - (profile_path, OPP_UUID, opts)), - agent_path, - timeout=3.0 - ) + for opts in (opts_v, opts_basic): + rep = dbus_call_with_agent( + conn, + new_method_call(pm, "RegisterProfile", "osa{sv}", + (profile_path, OPP_UUID, opts)), + agent_path, + timeout=3.0 + ) + if rep is None: + continue + if rep.header.message_type == MessageType.method_return: + return True + err_str = " ".join(str(x) for x in (rep.body or ())).lower() + if "already" in err_str: + return True except Exception: pass + return False + + +def lookup_bt_device_label(conn, dev_path, agent_path): + mac = "" + if isinstance(dev_path, str) and "dev_" in dev_path: + mac = dev_path.split("dev_")[-1].replace("_", ":").upper() + if conn is not None and isinstance(dev_path, str) and dev_path.startswith("/org/bluez/"): + try: + from jeepney import DBusAddress, MessageType, new_method_call + prop_addr = DBusAddress(dev_path, bus_name="org.bluez", + interface="org.freedesktop.DBus.Properties") + rep = dbus_call_with_agent( + conn, + new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)), + agent_path, + timeout=0.8 + ) + if rep is not None and rep.header.message_type == MessageType.method_return and rep.body: + raw = rep.body[0] + if isinstance(raw, dict): + for key in ("Alias", "Name"): + val = raw.get(key) + if isinstance(val, (tuple, list)) and len(val) == 2: + val = val[1] + if isinstance(val, str) and val.strip(): + return val.strip(), mac + except Exception: + pass + return (mac or "Bluetooth Device"), mac def run_daemon(): @@ -742,7 +1171,7 @@ def run_daemon(): with open(PID_FILE, "w", encoding="utf-8") as pf: pf.write(f"{os.getpid()}\n") - write_status(RX_STATUS_FILE, "IDLE\tReady (~/Downloads)") + write_status(RX_STATUS_FILE, f"IDLE\tReady ({shorten_obex_dir(get_configured_obex_dir())})") notify_networks_ui() running = True @@ -779,29 +1208,55 @@ def run_daemon(): subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - bt_disc = "1" + if os.geteuid() == 0: + try: + subprocess.run(["timeout", "2", "/usr/bin/btmgmt", "-i", "hci0", "class", "2", "3"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except Exception: + pass + + 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 "1" + 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", "discoverable-timeout", "0"], + 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) - subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + if disc_on: + subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) gp_thread = threading.Thread(target=run_gamepad_uinput_bridge, args=(lambda: running, wake_r), daemon=True) gp_thread.start() + def bind_rfcomm_fallback(): + s = None + try: + s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) + s.bind(("00:00:00:00:00:00", 9)) + s.listen(2) + s.setblocking(False) + return s + except OSError: + if s: + try: + s.close() + except OSError: + pass + return None + profile_path = "/org/bananarchy/obex_opp" agent_path = "/org/bananarchy/bt_agent" conn = None + opp_registered = False + rfcomm_listener = None try: conn = open_dbus_connection(bus="SYSTEM", enable_fds=True) dbus_bus = DBusAddress("/org/freedesktop/DBus", @@ -815,22 +1270,18 @@ def run_daemon(): dbus_bus, "AddMatch", "s", ("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",) )) - register_bluez_services(conn, profile_path, agent_path) + for _attempt in range(10): + if not running: + break + opp_registered = register_bluez_services(conn, profile_path, agent_path) + if opp_registered: + break + time.sleep(0.4) except Exception: pass - # Also bind a direct RFCOMM listener fallback on channel 9 if BlueZ didn't bind it - rfcomm_listener = None - try: - s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) - s.bind(("00:00:00:00:00:00", 9)) - s.listen(2) - s.setblocking(False) - rfcomm_listener = s - except OSError: - if rfcomm_listener: - rfcomm_listener.close() - rfcomm_listener = None + if running and not opp_registered: + rfcomm_listener = bind_rfcomm_fallback() while running: try: @@ -862,8 +1313,9 @@ def run_daemon(): raw_fd = os.dup(fd_obj.fileno()) fd_obj.close() client_sock = socket.socket(fileno=raw_fd) + s_name, s_mac = lookup_bt_device_label(conn, dev_path, agent_path) t = threading.Thread(target=handle_obex_rx_session, - args=(client_sock,), daemon=True) + args=(client_sock, s_name, s_mac), daemon=True) t.start() elif path == profile_path and member in ("RequestDisconnection", "Release"): reply = new_method_return(msg) @@ -873,7 +1325,15 @@ def run_daemon(): 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: - register_bluez_services(conn, profile_path, agent_path) + 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() elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2: iface, changed = msg.body[0], msg.body[1] if iface == "org.bluez.Device1" and isinstance(changed, dict): @@ -883,9 +1343,12 @@ def run_daemon(): if rfcomm_listener is not None: while running: try: - csock, _addr = rfcomm_listener.accept() + csock, addr = rfcomm_listener.accept() + rmac = addr[0].upper() if isinstance(addr, (tuple, list)) and addr else "" + dpath = ("/org/bluez/hci0/dev_" + rmac.replace(":", "_")) if rmac else "" + s_name, s_mac = lookup_bt_device_label(conn, dpath, agent_path) t = threading.Thread(target=handle_obex_rx_session, - args=(csock,), daemon=True) + args=(csock, s_name, s_mac or rmac), daemon=True) t.start() except BlockingIOError: break @@ -903,6 +1366,11 @@ def run_daemon(): if running: time.sleep(0.5) + if rfcomm_listener is not None: + try: + rfcomm_listener.close() + except OSError: + pass for fd in (wake_r, wake_w): try: os.close(fd) @@ -1004,10 +1472,11 @@ def send_file_obex(mac, filepath): try: sock.settimeout(20.0) + reader = ObexPacketReader(sock) # 1. OBEX CONNECT conn_pkt = struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000) sock.sendall(conn_pkt) - resp_op, resp_body = recv_obex_packet(sock) + resp_op, resp_body = recv_obex_packet(reader) if resp_op != 0xA0 or resp_body is None or len(resp_body) < 4: write_status(TX_STATUS_FILE, "ERROR\tOBEX Connect rejected") notify_user("Bluetooth Send Failed", "Remote rejected OBEX connection") @@ -1045,7 +1514,7 @@ def send_file_obex(mac, filepath): pct = int((sent_bytes * 100) // filesize) if filesize > 0 else 100 write_status(TX_STATUS_FILE, f"SENDING\t{filename}\t{pct}%") - r_op, _r_body = recv_obex_packet(sock) + r_op, _r_body = recv_obex_packet(reader) if eof: if r_op == 0xA0: write_status(TX_STATUS_FILE, f"SENT\t{filename}\t{format_size(filesize)}") @@ -1064,7 +1533,7 @@ def send_file_obex(mac, filepath): # 3. OBEX DISCONNECT try: sock.sendall(struct.pack(">BH", 0x81, 3)) - recv_obex_packet(sock) + recv_obex_packet(reader) except Exception: pass return 0 @@ -1280,10 +1749,19 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): for k, v in dprops_raw.items() } nm = str(dprops.get("Name") or dprops.get("Alias") or "").strip().lower() - if nm == t_low: - score = 0 + exact = (nm == t_low) + le_alias = (nm == f"{t_low} le" or f"{nm} le" == t_low) + if exact or le_alias: + score = 0 if exact else -25 + addr_type = str(dprops.get("AddressType") or "").strip().lower() if dprops.get("Connected"): score += 100 + if is_classic_audio_props(dprops): + score += 60 + if addr_type == "public": + score += 40 + elif addr_type == "random" and not is_hog_device_props(dprops): + score -= 40 if "RSSI" in dprops and dprops.get("RSSI") is not None: score += 50 if opath == prefer_path: @@ -1294,6 +1772,52 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): candidates.sort(key=lambda x: x[0], reverse=True) return candidates[0][1] + def has_media_transport(dpath): + rep = dbus_call_with_agent( + nonlocal_conn[0], + new_method_call(om_addr, "GetManagedObjects"), + cli_agent_path, + timeout=2.5 + ) + if rep is None or rep.header.message_type != MessageType.method_return or not rep.body: + return False + objs = rep.body[0] + if not isinstance(objs, dict): + return False + prefix = dpath + "/" + for opath, ifaces in objs.items(): + if isinstance(opath, str) and opath.startswith(prefix) and isinstance(ifaces, dict): + if "org.bluez.MediaTransport1" in ifaces: + return True + return False + + def connect_classic_audio_profiles(dpath, props): + if not is_classic_audio_props(props): + return + set_audio_preferred_bearer(nonlocal_conn[0], dpath, props) + uuids = [str(v).lower() for v in (props.get("UUIDs") or [])] + dev_addr = DBusAddress(dpath, bus_name="org.bluez", + interface="org.bluez.Device1") + profiles = [] + if any(u.startswith("0000110b-") for u in uuids): + profiles.append("0000110b-0000-1000-8000-00805f9b34fb") + if any(u.startswith("0000111e-") for u in uuids): + profiles.append("0000111e-0000-1000-8000-00805f9b34fb") + if any(u.startswith("00001108-") for u in uuids): + profiles.append("00001108-0000-1000-8000-00805f9b34fb") + if not profiles: + profiles = [ + "0000110b-0000-1000-8000-00805f9b34fb", + "0000111e-0000-1000-8000-00805f9b34fb", + ] + for prof_uuid in profiles: + dbus_call_with_agent( + nonlocal_conn[0], + new_method_call(dev_addr, "ConnectProfile", "s", (prof_uuid,)), + cli_agent_path, + timeout=6.0 + ) + def wait_for_bond_if_connected(dpath, max_wait=3.5): deadline = time.time() + max_wait while time.time() < deadline: @@ -1315,10 +1839,15 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): def attempt_connect_path(dpath, want_pair): p = get_dev_props(dpath) set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) + set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) trust_device_path(nonlocal_conn[0], dpath) if p is None: return False if p.get("Connected"): + if is_classic_audio_props(p) and not has_media_transport(dpath): + connect_classic_audio_profiles(dpath, p) + pump_agent(0.4) + p = get_dev_props(dpath) or p p = wait_for_bond_if_connected(dpath, 3.5) or p if p.get("Connected") and (not want_pair or p.get("Paired") or p.get("Bonded")): return True @@ -1332,6 +1861,8 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): if rep is None: cancel_pending_connect(dpath) p = get_dev_props(dpath) or {} + set_hog_preferred_bearer(nonlocal_conn[0], dpath, p) + set_audio_preferred_bearer(nonlocal_conn[0], dpath, p) if not p.get("Connected"): rep = dbus_call_with_agent( @@ -1371,6 +1902,8 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): timeout=2.5 ) trust_device_path(conn_new, dpath) + set_hog_preferred_bearer(conn_new, dpath, p) + set_audio_preferred_bearer(conn_new, dpath, p) dbus_call_with_agent( conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0 ) @@ -1379,6 +1912,11 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): ) p = get_dev_props(dpath) or {} + if is_classic_audio_props(p) and (not p.get("Connected") or not has_media_transport(dpath)): + connect_classic_audio_profiles(dpath, p) + pump_agent(0.4) + p = get_dev_props(dpath) or p + if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")): p = wait_for_bond_if_connected(dpath, 4.0) or p @@ -1388,6 +1926,18 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): return True return False + def is_tentative_ble_non_hog(dprops): + if not isinstance(dprops, dict): + return False + addr_type = str(dprops.get("AddressType") or "").strip().lower() + return ( + addr_type == "random" and + not is_hog_device_props(dprops) and + not is_classic_audio_props(dprops) and + not dprops.get("Paired") and + not dprops.get("Bonded") + ) + def scan_for_device(prefer_path, max_scan=15.0): dbus_call_with_agent( nonlocal_conn[0], new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5 @@ -1397,8 +1947,9 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): discovered_path = prefer_path while time.time() < scan_deadline: pump_agent(0.35) + elapsed = time.time() - scan_start p = get_dev_props(prefer_path) - if p and (p.get("Connected") or (p.get("RSSI") is not None and (time.time() - scan_start) >= 0.8)): + if p and p.get("Connected"): discovered_path = prefer_path break if dev_name: @@ -1408,8 +1959,14 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False): if ap and (ap.get("Connected") or ap.get("RSSI") is not None): discovered_path = alt trust_device_path(nonlocal_conn[0], discovered_path) - if ap.get("Connected") or (time.time() - scan_start) >= 0.8: + min_wait = 3.5 if is_tentative_ble_non_hog(ap) else 0.8 + if ap.get("Connected") or elapsed >= min_wait: break + if p and p.get("RSSI") is not None: + min_wait = 3.5 if is_tentative_ble_non_hog(p) else 0.8 + if elapsed >= min_wait: + discovered_path = prefer_path + break dbus_call_with_agent( nonlocal_conn[0], new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0 ) diff --git a/overlay/rootfs/usr/bin/sxmo_audio.sh b/overlay/rootfs/usr/bin/sxmo_audio.sh index d091a6b..5a84e50 100755 --- a/overlay/rootfs/usr/bin/sxmo_audio.sh +++ b/overlay/rootfs/usr/bin/sxmo_audio.sh @@ -70,28 +70,91 @@ is_bt_hfp() { esac } -start_bt_sco_keepalive() { - bt_sink="$(find_bt_sink)" - [ -z "$bt_sink" ] && return 0 +launch_bt_sco_pacat() { + bt_sink="$1" + [ -n "$bt_sink" ] || return 1 if [ -r /tmp/sxmo_bt_sco_keepalive.pid ]; then read -r kpid < /tmp/sxmo_bt_sco_keepalive.pid 2>/dev/null || kpid="" - if [ -n "$kpid" ] && kill -0 "$kpid" 2>/dev/null; then + if [ -n "$kpid" ] && kill -0 "$kpid" 2>/dev/null && \ + grep -qa 'pacat' "/proc/$kpid/cmdline" 2>/dev/null; then return 0 fi fi - if command -v pacat >/dev/null 2>&1; then - pacat --playback --device="$bt_sink" --rate=8000 --channels=1 --format=s16le /dev/zero >/dev/null 2>&1 & - printf "%d\n" "$!" > /tmp/sxmo_bt_sco_keepalive.pid 2>/dev/null || true + command -v pacat >/dev/null 2>&1 || return 1 + pacat --playback --device="$bt_sink" --rate=8000 --channels=1 --format=s16le /dev/zero >/dev/null 2>&1 & + printf "%d\n" "$!" > /tmp/sxmo_bt_sco_keepalive.pid 2>/dev/null || true + return 0 +} + +apply_bt_sink_volume() { + pct="$1" + bt_sink="$(find_bt_sink)" + if [ "$pct" -gt 0 ]; then + if [ -n "$bt_sink" ]; then + pactl set-sink-mute "$bt_sink" 0 >/dev/null 2>&1 || true + pactl set-sink-volume "$bt_sink" "${pct}%" >/dev/null 2>&1 || true + fi + pactl set-sink-mute @DEFAULT_SINK@ 0 >/dev/null 2>&1 || true + pactl set-sink-volume @DEFAULT_SINK@ "${pct}%" >/dev/null 2>&1 || true + else + if [ -n "$bt_sink" ]; then + if is_bt_hfp && [ -r /tmp/sxmo_bt_sco_keepalive.want ]; then + pactl set-sink-volume "$bt_sink" 0% >/dev/null 2>&1 || true + else + pactl set-sink-mute "$bt_sink" 1 >/dev/null 2>&1 || true + fi + fi + pactl set-sink-mute @DEFAULT_SINK@ 1 >/dev/null 2>&1 || true fi } +start_bt_sco_keepalive() { + printf "1\n" > /tmp/sxmo_bt_sco_keepalive.want 2>/dev/null || true + bt_sink="$(find_bt_sink)" + if [ -n "$bt_sink" ]; then + launch_bt_sco_pacat "$bt_sink" || true + return 0 + fi + if [ -r /tmp/sxmo_bt_sco_wait.pid ]; then + read -r wpid < /tmp/sxmo_bt_sco_wait.pid 2>/dev/null || wpid="" + if [ -n "$wpid" ] && kill -0 "$wpid" 2>/dev/null; then + return 0 + fi + fi + ( + _n=0 + while [ "$_n" -lt 25 ]; do + sleep 0.1 + [ -r /tmp/sxmo_bt_sco_keepalive.want ] || break + _sink="$(find_bt_sink)" + if [ -n "$_sink" ]; then + launch_bt_sco_pacat "$_sink" || true + _v="$(read_dev_vol Bluetooth)" + apply_bt_sink_volume "$(clamp_pct "${_v:-80}" 80)" + break + fi + _n=$(( _n + 1 )) + done + rm -f /tmp/sxmo_bt_sco_wait.pid 2>/dev/null || true + ) >/dev/null 2>&1 & + printf "%d\n" "$!" > /tmp/sxmo_bt_sco_wait.pid 2>/dev/null || true +} + stop_bt_sco_keepalive() { + rm -f /tmp/sxmo_bt_sco_keepalive.want 2>/dev/null || true + if [ -r /tmp/sxmo_bt_sco_wait.pid ]; then + read -r wpid < /tmp/sxmo_bt_sco_wait.pid 2>/dev/null || wpid="" + rm -f /tmp/sxmo_bt_sco_wait.pid 2>/dev/null || true + [ -n "$wpid" ] && kill -TERM "$wpid" 2>/dev/null || true + fi if [ -r /tmp/sxmo_bt_sco_keepalive.pid ]; then read -r kpid < /tmp/sxmo_bt_sco_keepalive.pid 2>/dev/null || kpid="" rm -f /tmp/sxmo_bt_sco_keepalive.pid 2>/dev/null || true [ -n "$kpid" ] && kill -TERM "$kpid" 2>/dev/null || true fi - pkill -TERM -f "pacat --playback --device=bluez_output" 2>/dev/null || true + for _bpid in $(ps 2>/dev/null | awk '/pacat --playback --device=bluez_output/ && !/awk/ {print $1}'); do + kill -TERM "$_bpid" 2>/dev/null || true + done } find_bt_sink() { @@ -467,6 +530,16 @@ EOF esac fi + if [ "$dev" = "Bluetooth" ]; then + if [ "$eff_pct" -gt 0 ]; then + printf "0\n" > /tmp/sxmo_pw_sink_muted 2>/dev/null || true + else + printf "1\n" > /tmp/sxmo_pw_sink_muted 2>/dev/null || true + fi + apply_bt_sink_volume "$eff_pct" + return 0 + fi + if [ "$eff_pct" -gt 0 ]; then printf "0\n" > /tmp/sxmo_pw_sink_muted 2>/dev/null || true pactl set-sink-mute @DEFAULT_SINK@ 0 >/dev/null 2>&1 || true @@ -523,15 +596,13 @@ apply_vol_out() { if [ "$eff_pct" -gt 0 ]; then if [ "$pw_muted" != "0" ]; then printf "0\n" > /tmp/sxmo_pw_sink_muted 2>/dev/null || true - pactl set-sink-mute @DEFAULT_SINK@ 0 >/dev/null 2>&1 || true fi - pactl set-sink-volume @DEFAULT_SINK@ "${eff_pct}%" >/dev/null 2>&1 || true else if [ "$pw_muted" != "1" ]; then printf "1\n" > /tmp/sxmo_pw_sink_muted 2>/dev/null || true fi - pactl set-sink-mute @DEFAULT_SINK@ 1 >/dev/null 2>&1 || true fi + apply_bt_sink_volume "$eff_pct" return 0 fi @@ -706,7 +777,7 @@ sync_pipewire_profile() { elif [ "$in_dev" = "Bluetooth" ] && is_bt_hfp; then start_bt_sco_keepalive [ ! -r /tmp/sxmo_in_call ] && want_sco_mm=1 - elif [ ! -r /tmp/sxmo_in_call ]; then + else stop_bt_sco_keepalive fi diff --git a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh index 677ab1b..f9b626f 100755 --- a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh +++ b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh @@ -25,7 +25,9 @@ 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 + 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 + timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true bt_name="" if [ -r /home/user/.config/sxmo/bt_name ]; then @@ -38,18 +40,18 @@ on() { timeout 2 bluetoothctl system-alias "$bt_name" >/dev/null 2>&1 || true fi - bt_disc="1" + bt_disc="0" if [ -r /home/user/.config/sxmo/bt_discoverable ]; then IFS= read -r bt_disc < /home/user/.config/sxmo/bt_discoverable 2>/dev/null || true fi - timeout 2 bluetoothctl discoverable-timeout 0 >/dev/null 2>&1 || true - timeout 2 bluetoothctl pairable on >/dev/null 2>&1 || true + timeout 2 bluetoothctl discoverable-timeout 60 >/dev/null 2>&1 || true case "$bt_disc" in - 0|off|OFF|no|NO|false|FALSE) - timeout 2 bluetoothctl discoverable off >/dev/null 2>&1 || true + 1|on|ON|yes|YES|true|TRUE) + timeout 2 bluetoothctl pairable on >/dev/null 2>&1 || true + timeout 2 bluetoothctl discoverable on >/dev/null 2>&1 || true ;; *) - timeout 2 bluetoothctl discoverable on >/dev/null 2>&1 || true + timeout 2 bluetoothctl discoverable off >/dev/null 2>&1 || true ;; esac diff --git a/overlay/rootfs/usr/bin/sxmo_modemaudio.sh b/overlay/rootfs/usr/bin/sxmo_modemaudio.sh index 6f499a8..ac58bb7 100755 --- a/overlay/rootfs/usr/bin/sxmo_modemaudio.sh +++ b/overlay/rootfs/usr/bin/sxmo_modemaudio.sh @@ -17,6 +17,14 @@ switch_bt_card_hfp() { pactl set-card-profile "$bt_card" headset-head-unit-cvsd >/dev/null 2>&1 || \ pactl set-card-profile "$bt_card" headset-head-unit >/dev/null 2>&1 || \ pactl set-card-profile "$bt_card" headset-head-unit-msbc >/dev/null 2>&1 || return 1 + _w=0 + while [ "$_w" -lt 15 ]; do + if pactl list short sinks 2>/dev/null | grep -q 'bluez_output\.'; then + break + fi + sleep 0.1 + _w=$(( _w + 1 )) + done return 0 } diff --git a/overlay/rootfs/usr/bin/sxmo_vibrate b/overlay/rootfs/usr/bin/sxmo_vibrate index 92ea47e..6aa978a 100755 Binary files a/overlay/rootfs/usr/bin/sxmo_vibrate and b/overlay/rootfs/usr/bin/sxmo_vibrate differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so index 4b43403..f53a490 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so and b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/music.so b/overlay/rootfs/usr/lib/dwm/plugins/music.so index 6f0993a..c4af599 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/music.so and b/overlay/rootfs/usr/lib/dwm/plugins/music.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/networks.so b/overlay/rootfs/usr/lib/dwm/plugins/networks.so index b692ec7..7de2cbb 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/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf index 3d5c3db..1d67e12 100644 --- a/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf +++ b/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -18,11 +18,15 @@ wireplumber.settings = { } monitor.bluez.properties = { - bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] - bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_duplex ] bluez5.enable-sbc-xq = true bluez5.enable-msbc = false + bluez5.enable-lc3-a127 = false bluez5.enable-hw-volume = true + bluez5.dummy-avrcp-player = true + bluez5.a2dp.ldac.quality = "auto" + bluez5.a2dp.aac.bitratemode = 0 bluez5.hfphsp-backend = "native" bluez5.hfphsp-backend-native-modem = "any" } diff --git a/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate b/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate index 92ea47e..6aa978a 100755 Binary files a/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate and b/prebuilt/sxmo-x11/usr/bin/sxmo_vibrate differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so index 4b43403..f53a490 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so index 6f0993a..c4af599 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.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 b692ec7..7de2cbb 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 b37dccb..8acf8b1 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 \ - "6b5c17059bf0341fdeb84c85dca08e64eb6b634e71add27fb9b7a93d17fb7ed8 images/bananarchy-nokia-argon.img" \ - "c6dad8d28ab3ab478869a0adb78dac1af4e19c111ab60a066687656c103e5723 images/bananarchy-nokia-beatles.img" \ - "4fd4b19d525677b2e2880346b391d9a13447d62f8ad61ee0088421a100ec08dc images/boot-bananarchy-nokia-beatles.img" \ + "92b23d34180c157861c492e7c2ea848ea4580857f3c1674020ae6b9f6fbdd39f images/bananarchy-nokia-argon.img" \ + "5c284c314a378d09fda37e56ebe745ab557d45c77499206440e8c362c709e7a7 images/bananarchy-nokia-beatles.img" \ + "80485ccf2af4f1d6107965ecde43d888c66ec19006e6feabc7fb63b6a7852391 images/boot-bananarchy-nokia-beatles.img" \ "b5549698c20f4de7603fc746d32bb5baa96ec377e41e74407823c98506fc185d images/boot-lk2nd-nokia-beatles-display.img" \ - "77addc7d48e40cdd017dc247969131e9ab7bc87ad590faf879d36c03b66df65c images/bananarchy-nokia-coconut.img" \ - "a5869b63de5cbfca3f6d87583aba162023670945f69a57276b597e1a7b85c5b2 images/boot-bananarchy-nokia-coconut.img" \ + "4e1d4799d42f56423f9cba8e175adf3b1f6c7fcd89965a7bc0b84a4f03ebc6e5 images/bananarchy-nokia-coconut.img" \ + "1e22879fc0533f419dc98c88a1700d75101fda85669837d1457bb15b9ab4ed9c images/boot-bananarchy-nokia-coconut.img" \ "e876424b38b0782f589756b4107337b24f27f7c37d624cc7d3907a5331df050a images/boot-lk2nd-nokia-coconut-display.img" \ - "a41a6ed4c2a04d521cf44d5229680f292972a4fc06ff3ad177cc3a13659295d1 images/bananarchy-nokia-sparkler.img" \ - "e950788360e1044d5ef128d1a170b868620aa5c356354aa6ac7178218e4d8e38 images/boot-bananarchy-nokia-sparkler.img" \ + "6b40db4674821bdde80d6f7619acc5a6414df684201d3e4e2e7cc3ac6c25dcfd images/bananarchy-nokia-sparkler.img" \ + "8f41328f0197f5debba92eaffa9df46c530721719309024a4d9cd7bf79a722c7 images/boot-bananarchy-nokia-sparkler.img" \ "bc41c2ddd1079246a7e91a40222fcafb82b0b52965c8ee8081872767d006748f images/boot-lk2nd-nokia-sparkler-display.img"; do set -- $pair want=$1 @@ -2034,6 +2034,24 @@ if ! "$BT_HID_TEST" >/dev/null 2>&1; then fail "host Bluetooth HID connection test failed" fi +echo "[check] Bluetooth 5.x/6.x headset A2DP/HFP, AVRCP, SCO, and power policy..." +BT_HEADSET_TEST="$BASE_DIR/scripts/test-bluetooth-headset.py" +if [ ! -x "$BT_HEADSET_TEST" ]; then + fail "missing host unit test scripts/test-bluetooth-headset.py" +fi +if ! "$BT_HEADSET_TEST" >/dev/null 2>&1; then + fail "host Bluetooth headset verification failed" +fi + +echo "[check] Bluetooth OBEX phone CoD, L2CAP SEQPACKET, and confirmation dialog..." +BT_OBEX_TEST="$BASE_DIR/scripts/test-bluetooth-obex.py" +if [ ! -x "$BT_OBEX_TEST" ]; then + fail "missing host unit test scripts/test-bluetooth-obex.py" +fi +if ! "$BT_OBEX_TEST" >/dev/null 2>&1; then + fail "host Bluetooth OBEX verification failed" +fi + echo "[check] Charger plug/unplug charge icon..." BATTERY_RULES="$BASE_DIR/overlay/rootfs/etc/udev/rules.d/85-bananarchy-battery.rules" CHARGE_EVENT="$BASE_DIR/overlay/rootfs/usr/bin/bananarchy-battery-charge-event.sh" diff --git a/scripts/test-bluetooth-headset.py b/scripts/test-bluetooth-headset.py new file mode 100755 index 0000000..388e407 --- /dev/null +++ b/scripts/test-bluetooth-headset.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Host regression tests for Bluetooth 5.x/6.x headset support (A2DP + HSP/HFP). + +Covers: + - WirePlumber 50-bluetooth.conf consistency across all overlay/user templates + (cvsd-only HFP without mSBC/lc3-a127/lc3_swb/bap/hfp_ag, dummy-avrcp-player, + LDAC auto ABR and AAC CBR defaults). + - Dual-mode BR/EDR vs BLE bearer selection in bananarchy-bt-obex without + regressing LE HOGP keyboards/mice/gamepads, plus AVRCP media key dispatch. + - SCO keepalive race handling, zero pkill dependency, hardware volume routing, + headset ATA call pickup synchronization, and n-sparkler SCO haptic guard. + - Off-by-default discoverability with bounded 60s timeout across toggle, + daemon, and xnetworks UI. + - All four target DTBs (argon, beatles, coconut, sparkler) exposing WCNSS-BT + and QDSP6 INTERNAL_BT_SCO DAIs. +""" +import ast +import pathlib +import shutil +import subprocess +import sys + +BASE = pathlib.Path(__file__).resolve().parent.parent + +WP_CONFS = ( + BASE / "overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf", + BASE / "overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf", + BASE / "overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf", + BASE / "overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf", +) + +BT_OBEX = BASE / "overlay/rootfs/usr/bin/bananarchy-bt-obex" +BT_TOGGLE = BASE / "overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh" +AUDIO_SH = BASE / "overlay/rootfs/usr/bin/sxmo_audio.sh" +MODEMAUDIO_SH = BASE / "overlay/rootfs/usr/bin/sxmo_modemaudio.sh" +CALLSCREEN_CPP = BASE / "src/dwm-plugins/callscreen_plugin.cpp" +NETWORKS_CPP = BASE / "src/dwm-plugins/networks_plugin.cpp" +MUSIC_CPP = BASE / "src/dwm-plugins/music_plugin.cpp" +VIBRATE_C = BASE / "src/dwm-plugins/sxmo_vibrate.c" + +TARGET_DTBS = ( + BASE / "prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8905-nokia-argon.dtb", + BASE / "prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8905-nokia-beatles.dtb", + BASE / "prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8905-nokia-coconut.dtb", + BASE / "prebuilt/kernel-6.12.1-msm8916/dtbs/qcom-msm8909-nokia-sparkler.dtb", +) + + +def require(cond, msg): + if not cond: + raise SystemExit("FAIL: " + msg) + + +def read(path): + return path.read_text(encoding="utf-8") + + +def load_obex_pure_helpers(): + src = read(BT_OBEX) + tree = ast.parse(src, filename=str(BT_OBEX)) + wanted_assigns = {"CLASSIC_AUDIO_UUID_PREFIXES"} + wanted_defs = { + "is_hog_device_props", + "is_classic_audio_props", + "avrcp_fifo_command_for_key", + } + selected = [] + for node in tree.body: + if isinstance(node, ast.Assign): + names = [t.id for t in node.targets if isinstance(t, ast.Name)] + if any(n in wanted_assigns for n in names): + selected.append(ast.get_source_segment(src, node)) + elif isinstance(node, ast.FunctionDef) and node.name in wanted_defs: + selected.append(ast.get_source_segment(src, node)) + require(len(selected) == len(wanted_assigns) + len(wanted_defs), + "missing pure audio/AVRCP helpers in bananarchy-bt-obex") + ns = {} + exec("\n\n".join(selected), ns) + return ns + + +def test_wireplumber_config(): + texts = [read(p) for p in WP_CONFS] + for idx, t in enumerate(texts[1:], 1): + require(t == texts[0], + f"50-bluetooth.conf copy {WP_CONFS[idx]} drifted from etc/wireplumber copy") + cfg = texts[0] + for forbidden in ("bap_sink", "bap_source", "a2dp_source", "hsp_ag", "hfp_ag", + "opus_05_dup ", "opus_05_51", "opus_05_71", "opus_05_pro", + " lc3 "): + require(forbidden not in cfg, + f"50-bluetooth.conf still contains incompatible token {forbidden!r}") + for required in ( + "bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]", + "opus_05_duplex", + "bluez5.enable-msbc = false", + "bluez5.enable-lc3-a127 = false", + "bluez5.enable-hw-volume = true", + "bluez5.dummy-avrcp-player = true", + 'bluez5.a2dp.ldac.quality = "auto"', + "bluez5.a2dp.aac.bitratemode = 0", + 'bluez5.hfphsp-backend = "native"', + ): + require(required in cfg, f"50-bluetooth.conf missing {required!r}") + print("[ok] WirePlumber 50-bluetooth.conf profiles, codecs, AVRCP, and CVSD lock") + + +def test_obex_bearer_and_avrcp(): + ns = load_obex_pure_helpers() + is_hog = ns["is_hog_device_props"] + is_audio = ns["is_classic_audio_props"] + map_avrcp = ns["avrcp_fifo_command_for_key"] + + hog_kbd = {"UUIDs": ["00001812-0000-1000-8000-00805f9b34fb"]} + bt5_dual_buds = { + "AddressType": "public", + "UUIDs": [ + "0000110b-0000-1000-8000-00805f9b34fb", + "0000111e-0000-1000-8000-00805f9b34fb", + "0000184e-0000-1000-8000-00805f9b34fb", + ], + "Icon": "audio-headset", + "Class": 0x240404, + } + ble_beacon = {"AddressType": "random", "UUIDs": ["00001800-0000-1000-8000-00805f9b34fb"]} + cod_only_speaker = {"Class": 0x200414} + + require(is_hog(hog_kbd) and not is_audio(hog_kbd), + "HOGP keyboard misclassified as Classic Audio") + require(is_audio(bt5_dual_buds) and not is_hog(bt5_dual_buds), + "Dual-mode BT 5.x/6.x headset not recognized for BR/EDR bearer selection") + require(is_audio({"Icon": "audio-headphones"}), + "audio-headphones Icon not recognized as Classic Audio") + require(is_audio(cod_only_speaker), + "Audio CoD speaker not recognized as Classic Audio") + require(not is_audio(ble_beacon), + "Generic BLE beacon falsely matched Classic Audio") + + require(map_avrcp(164) == "PLAYPAUSE", "KEY_PLAYPAUSE mapping wrong") + require(map_avrcp(200) == "PLAY", "KEY_PLAYCD mapping wrong") + require(map_avrcp(201) == "PAUSE", "KEY_PAUSECD mapping wrong") + require(map_avrcp(166) == "STOP", "KEY_STOPCD mapping wrong") + require(map_avrcp(163) == "NEXT", "KEY_NEXTSONG mapping wrong") + require(map_avrcp(165) == "PREV", "KEY_PREVIOUSSONG mapping wrong") + require(map_avrcp(30) is None, "unrelated key mapped as AVRCP") + + obex_src = read(BT_OBEX) + for tok in ( + "set_hog_preferred_bearer(", + "set_audio_preferred_bearer(", + '("s", "bredr")', + "ConnectProfile", + "has_media_transport(", + "is_tentative_ble_non_hog(", + "avrcp_devs", + "dispatch_avrcp_key(", + ): + require(tok in obex_src, f"bananarchy-bt-obex missing {tok}") + print("[ok] Dual-bearer BR/EDR headset selection, HOGP preservation, and AVRCP bridge") + + +def test_discoverability_and_power(): + obex_src = read(BT_OBEX) + toggle_src = read(BT_TOGGLE) + net_src = read(NETWORKS_CPP) + + require('discoverable-timeout 0' not in toggle_src, + "sxmo_bluetoothtoggle.sh still sets infinite discoverable-timeout 0") + require('discoverable-timeout 60' in toggle_src and 'bt_disc="0"' in toggle_src, + "sxmo_bluetoothtoggle.sh must default bt_disc=0 and timeout=60") + require('"discoverable-timeout", "0"' not in obex_src and + '("org.bluez.Adapter1", "PairableTimeout", ("u", 0))' not in obex_src, + "bananarchy-bt-obex still forces infinite discoverable/pairable timeout 0") + require('"discoverable-timeout", "60"' in obex_src and 'bt_disc = "0"' in obex_src, + "bananarchy-bt-obex must default bt_disc='0' and timeout=60") + 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") + + +def test_sco_audio_call_and_haptics(): + audio_src = read(AUDIO_SH) + maudio_src = read(MODEMAUDIO_SH) + cs_src = read(CALLSCREEN_CPP) + net_src = read(NETWORKS_CPP) + music_src = read(MUSIC_CPP) + vib_src = read(VIBRATE_C) + + require("pkill" not in audio_src, + "sxmo_audio.sh must not invoke missing pkill binary") + require("launch_bt_sco_pacat" in audio_src and + "/tmp/sxmo_bt_sco_wait.pid" in audio_src and + "apply_bt_sink_volume" in audio_src, + "sxmo_audio.sh missing bounded SCO keepalive retry or $bt_sink volume control") + require("elif [ ! -r /tmp/sxmo_in_call ]; then\n stop_bt_sco_keepalive" not in audio_src, + "sxmo_audio.sh leaks SCO pacat keepalive when switching off BT mid-call") + require("bluez_output\\." in maudio_src and "switch_bt_card_hfp" in maudio_src, + "sxmo_modemaudio.sh missing synchronous BT SCO sink readiness wait") + require('.pickedupcall' in cs_src and + 'writeIntFile("/tmp/sxmo_in_call", 1)' in cs_src, + "callscreen_plugin.cpp missing headset ATA .pickedupcall / sxmo_in_call sync") + require("refreshTargetBtFromList" in net_src and "infoCount >= 24" in net_src, + "networks_plugin.cpp missing stale targetBt refresh or info cap bump") + for tok in ("XF86XK_AudioPlay", "XF86XK_AudioNext", "XF86XK_AudioPrev", + 'cmd == "PLAYPAUSE"', 'cmd == "NEXT"', 'cmd == "PREV"'): + require(tok in music_src, f"music_plugin.cpp missing AVRCP handler {tok}") + require("/tmp/sxmo_bt_sco_mm_active" in vib_src, + "sxmo_vibrate.c missing /tmp/sxmo_bt_sco_mm_active haptic suppression") + print("[ok] SCO keepalive, ATA call sync, AVRCP music control, and Sparkler SCO haptic guard") + + +def test_target_dtbs(): + dtc = shutil.which("dtc") + if not dtc: + print("[skip] dtc not installed; skipping DTB inspection") + return + for dtb in TARGET_DTBS: + require(dtb.is_file(), f"missing shipped DTB: {dtb}") + dts = subprocess.check_output( + [dtc, "-q", "-I", "dtb", "-O", "dts", str(dtb)], + text=True, + stderr=subprocess.DEVNULL, + ) + for node in ('compatible = "qcom,wcnss-bt"', "dai@136", "dai@137", + 'link-name = "Internal BT-SCO RX"', + 'link-name = "Internal BT-SCO TX"'): + require(node in dts, f"{dtb.name} missing BT/QDSP6 node {node!r}") + print("[ok] All 4 target DTBs include WCNSS-BT and INTERNAL_BT_SCO DAIs") + + +def main(): + test_wireplumber_config() + test_obex_bearer_and_avrcp() + test_discoverability_and_power() + test_sco_audio_call_and_haptics() + test_target_dtbs() + print("bluetooth headset verification: all checks passed") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-bluetooth-obex.py b/scripts/test-bluetooth-obex.py new file mode 100755 index 0000000..90bbf7c --- /dev/null +++ b/scripts/test-bluetooth-obex.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Host tests for Bluetooth OBEX OPP recognition, L2CAP SEQPACKET & confirmation UI. + +Covers: + - Smartphone Class of Device (0x5a020c in main.conf, btmgmt class 2 3 in + LE/toggle helpers) and absence of a2dp_source role in 50-bluetooth.conf so + Android phones recognize Bananarchy as a phone capable of OPP transfers. + - ObexPacketReader over both AF_UNIX SOCK_SEQPACKET (simulating L2CAP GOEP 2.0) + and SOCK_STREAM (RFCOMM GOEP 1.1) without packet truncation. + - End-to-end handle_obex_rx_session() over SOCK_SEQPACKET verifying user ACCEPT + into a custom target directory and user REJECT returning 0xC3 without writing. + - Reliable RegisterProfile before RFCOMM channel 9 fallback and NeoUI dialog + wiring in networks_plugin.cpp. +""" +import os +import pathlib +import socket +import struct +import sys +import tempfile +import threading +import time +import types + +sys.dont_write_bytecode = True + +BASE = pathlib.Path(__file__).resolve().parent.parent +MAIN_CONF = BASE / "overlay/rootfs/etc/bluetooth/main.conf" +LE_HELPER = BASE / "overlay/rootfs/usr/bin/bananarchy-bt-le-enable.sh" +BT_TOGGLE = BASE / "overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh" +BT_OBEX = BASE / "overlay/rootfs/usr/bin/bananarchy-bt-obex" +NETWORKS_CPP = BASE / "src/dwm-plugins/networks_plugin.cpp" +WP_CONF = BASE / "overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf" + + +def require(cond, msg): + if not cond: + raise SystemExit("FAIL: " + msg) + + +def read(path): + return path.read_text(encoding="utf-8") + + +def load_obex_module(): + src = read(BT_OBEX) + mod = types.ModuleType("bananarchy_bt_obex") + mod.__file__ = str(BT_OBEX) + exec(compile(src, str(BT_OBEX), "exec"), mod.__dict__) + return mod + + +def test_class_and_roles(): + main_conf = read(MAIN_CONF) + require("ControllerMode = dual" in main_conf, "main.conf must keep ControllerMode = dual") + require("Class = 0x5a020c" in main_conf, "main.conf missing Smartphone Class = 0x5a020c") + require("btmgmt -i hci0 class 2 3" in read(LE_HELPER), + "bananarchy-bt-le-enable.sh missing btmgmt class 2 3") + require("btmgmt -i hci0 class 2 3" in read(BT_TOGGLE), + "sxmo_bluetoothtoggle.sh missing btmgmt class 2 3") + wp = read(WP_CONF) + require("a2dp_source" not in wp and "bluez5.roles = [ a2dp_sink hsp_hs hfp_hf ]" in wp, + "50-bluetooth.conf must omit a2dp_source so phones do not treat us as an audio sink") + print("[ok] Smartphone Class-of-Device and Phone/OPP SDP profile role gate") + + +def build_obex_put_headers(filename, total_len): + name_utf16 = filename.encode("utf-16-be") + b"\x00\x00" + name_hdr = struct.pack(">BH", 0x01, 3 + len(name_utf16)) + name_utf16 + len_hdr = struct.pack(">BI", 0xC3, total_len) + return name_hdr + len_hdr + + +def build_obex_body(chunk, is_final): + hi = 0x49 if is_final else 0x48 + return struct.pack(">BH", hi, 3 + len(chunk)) + chunk + + +def recv_raw_pkt(sock): + dat = sock.recv(4096) + require(len(dat) >= 3, "short OBEX response packet") + return dat[0], dat[3:] + + +def test_seqpacket_and_stream_reader(mod): + # 1. SOCK_SEQPACKET (Android L2CAP GOEP 2.0): full PDU arrived in one recv() + a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + try: + payload = build_obex_put_headers("android_photo_test.jpg", 12345) + build_obex_body(b"ABCD1234", False) + pkt = struct.pack(">BH", 0x02, 3 + len(payload)) + payload + a.sendall(pkt) + reader = mod.ObexPacketReader(b) + op, got = mod.recv_obex_packet(reader) + require(op == 0x02 and got == payload, + f"SOCK_SEQPACKET packet truncated or corrupted (got {len(got or b'')} vs {len(payload)})") + finally: + a.close() + b.close() + + # 2. SOCK_STREAM (RFCOMM): split headers across fragments + a, b = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) + try: + payload = build_obex_put_headers("rfcomm_test.txt", 5) + build_obex_body(b"hello", True) + pkt = struct.pack(">BH", 0x82, 3 + len(payload)) + payload + a.sendall(pkt[:2]) + a.sendall(pkt[2:9]) + a.sendall(pkt[9:]) + reader = mod.ObexPacketReader(b) + op, got = mod.recv_obex_packet(reader) + require(op == 0x82 and got == payload, "SOCK_STREAM reassembly failed") + finally: + a.close() + b.close() + print("[ok] ObexPacketReader framing over SOCK_SEQPACKET and SOCK_STREAM") + + +def test_accept_and_reject_sessions(mod): + old_no_ui = os.environ.get("BANANARCHY_OBEX_NO_UI") + os.environ["BANANARCHY_OBEX_NO_UI"] = "1" + orig_vals = ( + mod.OBEX_CFG_FILE, + mod.OBEX_IPC_DIR, + mod.OBEX_PROMPT_FILE, + mod.OBEX_DECISION_FILE, + mod.RX_STATUS_FILE, + mod.TX_STATUS_FILE, + ) + try: + with tempfile.TemporaryDirectory(prefix="bananarchy-obex-test-") as tmp: + root = pathlib.Path(tmp) + ipc_dir = root / "ipc" + default_dir = root / "downloads" + custom_dir = root / "sdcard_custom" + default_dir.mkdir() + custom_dir.mkdir() + cfg_file = root / "bt_obex_dir" + cfg_file.write_text(str(default_dir) + "\n", encoding="utf-8") + + mod.OBEX_CFG_FILE = str(cfg_file) + mod.OBEX_IPC_DIR = str(ipc_dir) + mod.OBEX_PROMPT_FILE = str(ipc_dir / "prompt.tsv") + mod.OBEX_DECISION_FILE = str(ipc_dir / "decision.tsv") + mod.RX_STATUS_FILE = str(root / "rx.status") + mod.TX_STATUS_FILE = str(root / "tx.status") + + # --- Case A: Accept and save to custom folder over SOCK_SEQPACKET --- + cli, srv = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + t = threading.Thread( + target=mod.handle_obex_rx_session, + args=(srv, "Pixel Test", "AA:BB:CC:DD:EE:11"), + daemon=True, + ) + t.start() + try: + cli.sendall(struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)) + op, _ = recv_raw_pkt(cli) + require(op == 0xA0, f"expected CONNECT OK (0xA0), got {hex(op)}") + + hdrs = build_obex_put_headers("greeting.txt", 12) + build_obex_body(b"hello ", False) + cli.sendall(struct.pack(">BH", 0x02, 3 + len(hdrs)) + hdrs) + + prompt_path = pathlib.Path(mod.OBEX_PROMPT_FILE) + deadline = time.monotonic() + 3.0 + while not prompt_path.exists() and time.monotonic() < deadline: + time.sleep(0.02) + require(prompt_path.exists(), "OBEX prompt file was never created") + fields = prompt_path.read_text(encoding="utf-8").strip().split("\t") + require(len(fields) == 6 and fields[1] == "Pixel Test" and fields[3] == "greeting.txt", + f"unexpected prompt TSV: {fields}") + req_id = fields[0] + pathlib.Path(mod.OBEX_DECISION_FILE).write_text( + f"{req_id}\tACCEPT\t{custom_dir}\n", encoding="utf-8" + ) + + op, _ = recv_raw_pkt(cli) + require(op == 0x90, f"expected Continue (0x90) after ACCEPT, got {hex(op)}") + + tail = build_obex_body(b"world!", True) + cli.sendall(struct.pack(">BH", 0x82, 3 + len(tail)) + tail) + op, _ = recv_raw_pkt(cli) + require(op == 0xA0, f"expected OK (0xA0) after PUT-Final, got {hex(op)}") + + cli.sendall(struct.pack(">BH", 0x81, 3)) + op, _ = recv_raw_pkt(cli) + require(op == 0xA0, "expected DISCONNECT OK (0xA0)") + finally: + cli.close() + t.join(timeout=3.0) + + saved_file = custom_dir / "greeting.txt" + require(saved_file.is_file() and saved_file.read_bytes() == b"hello world!", + "accepted file missing or corrupted in custom target folder") + require(not pathlib.Path(mod.OBEX_PROMPT_FILE).exists(), + "stale OBEX prompt file was not removed") + + # --- Case B: Reject inline PUT-Final over SOCK_SEQPACKET --- + cli, srv = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET) + t = threading.Thread( + target=mod.handle_obex_rx_session, + args=(srv, "Unknown Phone", "AA:BB:CC:DD:EE:22"), + daemon=True, + ) + t.start() + try: + cli.sendall(struct.pack(">BHBBH", 0x80, 7, 0x10, 0x00, 0x8000)) + op, _ = recv_raw_pkt(cli) + require(op == 0xA0, "expected CONNECT OK") + + one_shot = build_obex_put_headers("rejected.bin", 4) + build_obex_body(b"NOPE", True) + cli.sendall(struct.pack(">BH", 0x82, 3 + len(one_shot)) + one_shot) + + prompt_path = pathlib.Path(mod.OBEX_PROMPT_FILE) + deadline = time.monotonic() + 3.0 + while not prompt_path.exists() and time.monotonic() < deadline: + time.sleep(0.02) + require(prompt_path.exists(), "OBEX prompt file not created for reject case") + req_id = prompt_path.read_text(encoding="utf-8").strip().split("\t")[0] + pathlib.Path(mod.OBEX_DECISION_FILE).write_text( + f"{req_id}\tREJECT\t{custom_dir}\n", encoding="utf-8" + ) + + op, _ = recv_raw_pkt(cli) + require(op == 0xC3, f"expected Forbidden (0xC3) on REJECT, got {hex(op)}") + finally: + cli.close() + t.join(timeout=3.0) + + require(not (custom_dir / "rejected.bin").exists() and not (default_dir / "rejected.bin").exists(), + "rejected file must never be written to disk") + finally: + ( + mod.OBEX_CFG_FILE, + mod.OBEX_IPC_DIR, + mod.OBEX_PROMPT_FILE, + mod.OBEX_DECISION_FILE, + mod.RX_STATUS_FILE, + mod.TX_STATUS_FILE, + ) = orig_vals + if old_no_ui is None: + os.environ.pop("BANANARCHY_OBEX_NO_UI", None) + else: + os.environ["BANANARCHY_OBEX_NO_UI"] = old_no_ui + print("[ok] Incoming OBEX Accept/Reject & custom target directory loopback sessions") + + +def test_networks_ui_wiring(): + src = read(NETWORKS_CPP) + for tok in ( + "ObexActions", + "ObexDirPicker", + "ObexIncomingPrompt", + "OBEX_PROMPT", + "bt_obex_dir", + "writeObexDecision", + "readObexPromptFile", + "openObexDirPicker", + "tryPresentObexPrompt", + ): + require(tok in src, f"networks_plugin.cpp missing OBEX UI element {tok}") + obex_src = read(BT_OBEX) + require("if running and not opp_registered:\n rfcomm_listener = bind_rfcomm_fallback()" in obex_src, + "bananarchy-bt-obex must register BlueZ OPP profile before fallback channel 9 bind") + print("[ok] networks_plugin.cpp OBEX confirmation & directory picker UI wiring") + + +def main(): + mod = load_obex_module() + test_class_and_roles() + test_seqpacket_and_stream_reader(mod) + test_accept_and_reject_sessions(mod) + test_networks_ui_wiring() + print("bluetooth obex verification: all checks passed") + + +if __name__ == "__main__": + main() diff --git a/src/dwm-plugins/callscreen_plugin.cpp b/src/dwm-plugins/callscreen_plugin.cpp index 15bfd9e..ff72352 100644 --- a/src/dwm-plugins/callscreen_plugin.cpp +++ b/src/dwm-plugins/callscreen_plugin.cpp @@ -1469,6 +1469,9 @@ int callscreen_run_main(int argc, char** argv) { writeActiveStateFiles(); stopRingingJobs(); notifyCoverCall("active", callNumber, contactName, activeSimSlot); + if (!isVoipCallId(cid)) { + writeIntFile("/tmp/sxmo_in_call", 1); + } setSpeakerRoute(false, hasBtAudioCard()); render(); @@ -2063,6 +2066,18 @@ int callscreen_run_main(int argc, char** argv) { if (callState != CallState::Outgoing) { speakerOn = false; btAudioOn = hasBtAudioCard(); + if (!isVoipCallId(callId)) { + writeIntFile("/tmp/sxmo_in_call", 1); + if (!callId.empty() && callId != "-") { + std::string callsDir = getRuntimeFile("sxmo_calls"); + ::mkdir(callsDir.c_str(), 0755); + std::string pickPath = callsDir + "/" + callId + ".pickedupcall"; + int pfd = ::open(pickPath.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + if (pfd >= 0) ::close(pfd); + } + } + } else if (!isVoipCallId(callId) && ::access("/tmp/sxmo_in_call", F_OK) != 0) { + writeIntFile("/tmp/sxmo_in_call", 1); } callState = CallState::Active; callStartMs = nowMs(); @@ -2396,6 +2411,18 @@ int callscreen_run_main(int argc, char** argv) { if (!wasOutgoing) { speakerOn = false; btAudioOn = hasBtAudioCard(); + if (!isVoipCallId(callId)) { + writeIntFile("/tmp/sxmo_in_call", 1); + if (!callId.empty() && callId != "-") { + std::string callsDir = getRuntimeFile("sxmo_calls"); + ::mkdir(callsDir.c_str(), 0755); + std::string pickPath = callsDir + "/" + callId + ".pickedupcall"; + int pfd = ::open(pickPath.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, 0644); + if (pfd >= 0) ::close(pfd); + } + } + } else if (!isVoipCallId(callId) && ::access("/tmp/sxmo_in_call", F_OK) != 0) { + writeIntFile("/tmp/sxmo_in_call", 1); } } ringMuted = false; diff --git a/src/dwm-plugins/music_plugin.cpp b/src/dwm-plugins/music_plugin.cpp index 4d15d42..29a1204 100644 --- a/src/dwm-plugins/music_plugin.cpp +++ b/src/dwm-plugins/music_plugin.cpp @@ -1327,6 +1327,31 @@ int runMusicApp(int argc, char** argv) { continue; } + if (sym == XF86XK_AudioPlay || sym == XF86XK_AudioPause) { + if (queue.empty()) populateDefaultQueue(); + togglePlayPause(); + render(); + continue; + } + if (sym == XF86XK_AudioStop) { + stopPlayback(); + setBanner("Playback stopped"); + render(); + continue; + } + if (sym == XF86XK_AudioNext) { + if (queue.empty()) populateDefaultQueue(); + stepTrack(1); + render(); + continue; + } + if (sym == XF86XK_AudioPrev) { + if (queue.empty()) populateDefaultQueue(); + stepTrack(-1); + render(); + continue; + } + char dch = mapDialKey(sym, kc, ev.xkey.state); if (dch == '1') { activeTab = TabId::Player; @@ -1540,6 +1565,22 @@ int runMusicApp(int argc, char** argv) { } else if (cmd == "PAUSE") { pausePlayback(); if (visible) render(); + } else if (cmd == "PLAYPAUSE") { + if (queue.empty()) populateDefaultQueue(); + togglePlayPause(); + if (visible) render(); + } else if (cmd == "PLAY") { + if (queue.empty()) populateDefaultQueue(); + if (!isPlaying || isPaused) togglePlayPause(); + if (visible) render(); + } else if (cmd == "NEXT") { + if (queue.empty()) populateDefaultQueue(); + stepTrack(1); + if (visible) render(); + } else if (cmd == "PREV") { + if (queue.empty()) populateDefaultQueue(); + stepTrack(-1); + if (visible) render(); } else if (cmd == "STOP") { stopPlayback(); if (visible) render(); diff --git a/src/dwm-plugins/networks_plugin.cpp b/src/dwm-plugins/networks_plugin.cpp index 29923bb..c752069 100644 --- a/src/dwm-plugins/networks_plugin.cpp +++ b/src/dwm-plugins/networks_plugin.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include #include #include @@ -39,6 +41,9 @@ enum class NetModal { ApnEditor = 3, BtActions = 4, BtNameEditor = 5, + ObexActions = 6, + ObexDirPicker = 7, + ObexIncomingPrompt = 8, }; constexpr const char* kIconHeadphones = "\xef\x80\xa5"; // U+F025 headphones @@ -176,12 +181,12 @@ bool readSavedBtDiscoverable() { std::string line; if (in.is_open() && std::getline(in, line)) { std::string v = toLowerStr(trimStr(line)); - if (v == "0" || v == "off" || v == "no" || v == "false") { - return false; + if (v == "1" || v == "on" || v == "yes" || v == "true") { + return true; } - if (!v.empty()) return true; + if (!v.empty()) return false; } - return true; + return false; } void writeSavedBtDiscoverable(bool disc) { @@ -193,6 +198,143 @@ void writeSavedBtDiscoverable(bool disc) { } } +constexpr const char* kObexIpcDir = "/run/bananarchy/bt-obex"; +constexpr const char* kObexPromptPath = "/run/bananarchy/bt-obex/prompt.tsv"; +constexpr const char* kObexDecisionPath = "/run/bananarchy/bt-obex/decision.tsv"; + +std::string shortenHomePath(const std::string& p) { + if (p.empty()) return "~/Downloads"; + std::string home = getHomeDir(); + if (p == home) return "~"; + if (p.rfind(home + "/", 0) == 0) { + return "~/" + p.substr(home.size() + 1); + } + return p; +} + +std::string readSavedObexDir() { + std::string fallback = getHomeDir() + "/Downloads"; + if (!isDuressMode()) { + std::string cfgPath = getHomeDirPath() + "/.config/sxmo/bt_obex_dir"; + std::ifstream in(cfgPath); + std::string line; + if (in.is_open() && std::getline(in, line)) { + line = trimStr(line); + if (!line.empty() && line[0] == '/' && + line.find('\t') == std::string::npos && + line.find("..") == std::string::npos) { + return line; + } + } + } + ::mkdir(fallback.c_str(), 0755); + return fallback; +} + +void writeSavedObexDir(const std::string& rawDir) { + std::string dir = trimStr(rawDir); + if (dir.empty() || dir[0] != '/') { + dir = getHomeDir() + "/Downloads"; + } + ::mkdir(dir.c_str(), 0755); + if (isDuressMode()) return; + std::string cfgDir = getHomeDirPath() + "/.config/sxmo"; + ::mkdir(cfgDir.c_str(), 0755); + std::ofstream out(cfgDir + "/bt_obex_dir", std::ios::trunc); + if (out.is_open()) { + out << dir << "\n"; + } +} + +std::string formatBytesShort(int64_t b) { + if (b <= 0) return "Unknown size"; + char buf[48]; + if (b >= 1024LL * 1024LL) { + std::snprintf(buf, sizeof(buf), "%.1f MB", static_cast(b) / (1024.0 * 1024.0)); + } else if (b >= 1024) { + std::snprintf(buf, sizeof(buf), "%.1f KB", static_cast(b) / 1024.0); + } else { + std::snprintf(buf, sizeof(buf), "%lld B", static_cast(b)); + } + return buf; +} + +struct ObexPromptInfo { + bool active = false; + std::string reqId; + std::string senderName; + std::string senderMac; + std::string fileName; + int64_t fileBytes = 0; + std::string targetDir; +}; + +ObexPromptInfo readObexPromptFile() { + ObexPromptInfo p; + std::ifstream in(kObexPromptPath); + std::string line; + if (!in.is_open() || !std::getline(in, line)) return p; + line = trimStr(line); + if (line.empty()) return p; + std::vector cols; + std::stringstream ss(line); + std::string c; + while (std::getline(ss, c, '\t')) { + cols.push_back(c); + } + if (cols.size() < 4 || cols[0].empty()) return p; + p.active = true; + p.reqId = cols[0]; + p.senderName = cols[1]; + p.senderMac = cols[2]; + p.fileName = cols[3]; + p.fileBytes = (cols.size() >= 5) ? std::atoll(cols[4].c_str()) : 0; + p.targetDir = (cols.size() >= 6 && !cols[5].empty()) ? cols[5] : readSavedObexDir(); + return p; +} + +void writeObexDecision(const std::string& reqId, bool accept, const std::string& targetDir) { + if (reqId.empty()) return; + ::mkdir("/run/bananarchy", 0755); + ::mkdir(kObexIpcDir, 0755); + std::string tmpPath = std::string(kObexDecisionPath) + ".tmp"; + { + std::ofstream out(tmpPath, std::ios::trunc); + if (out.is_open()) { + out << reqId << "\t" << (accept ? "ACCEPT" : "REJECT") << "\t" << targetDir << "\n"; + } + } + ::rename(tmpPath.c_str(), kObexDecisionPath); +} + +bool isLidClosedState() { + std::ifstream in("/run/bananarchy/lid-state"); + std::string line; + if (in.is_open() && std::getline(in, line)) { + std::string low = toLowerStr(trimStr(line)); + if (low.rfind("closed", 0) == 0) return true; + } + return false; +} + +void wakeDisplayForObex(Display* dpy) { + if (isLidClosedState()) { + runAsyncArgv("/usr/bin/bananarchy-lid-gate.sh", "wake"); + return; + } + int saved = readIntFile("/tmp/sxmo_saved_brightness", -1); + if (saved <= 1) { + saved = readIntFile("/sys/class/backlight/backlight/max_brightness", 14); + if (saved <= 1) saved = 14; + } + writeIntFile("/sys/class/backlight/backlight/bl_power", 0); + writeIntFile("/sys/class/backlight/backlight/brightness", saved); + writeIntFile("/sys/class/leds/white:kbd_backlight/brightness", 255); + if (dpy) { + XForceScreenSaver(dpy, ScreenSaverReset); + } +} + struct BtRxStatus { std::string state = "IDLE"; std::string fileName; @@ -203,6 +345,7 @@ struct BtRxStatus { BtRxStatus readBtRxStatus() { BtRxStatus st; + st.detail = "Ready (" + shortenHomePath(readSavedObexDir()) + ")"; std::ifstream in("/tmp/bananarchy_bt_rx.status"); std::string line; if (!in.is_open() || !std::getline(in, line)) { @@ -217,7 +360,10 @@ BtRxStatus readBtRxStatus() { cols.push_back(c); } if (!cols.empty()) st.state = cols[0]; - if (st.state == "RECEIVING" && cols.size() >= 5) { + if (st.state == "PENDING" && cols.size() >= 4) { + st.fileName = cols[1]; + st.detail = cols[2] + " (" + cols[3] + ")"; + } else if (st.state == "RECEIVING" && cols.size() >= 5) { st.fileName = cols[1]; st.detail = cols[4]; st.pct = std::clamp(std::atoi(cols[4].c_str()), 0, 100); @@ -595,7 +741,7 @@ std::vector queryBtDevices(const std::string& scanRaw = "") { }); for (const auto& d : out) { - if (infoCount >= 12) break; + 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) + @@ -868,6 +1014,16 @@ int runNetworksApp(int argc, char** argv) { // Bluetooth target device BtDeviceEntry targetBt; + // Incoming OBEX confirmation & directory picker state + ObexPromptInfo obexPrompt; + int obexPromptSel = 0; + bool openedForObexPrompt = false; + bool pendingDeferredObexPrompt = false; + std::string obexPickerDir; + std::vector> obexPickerEntries; + int obexPickerSel = 0; + bool obexPickerForPrompt = false; + // Multi-tap state for text inputs TextMode textMode = TextMode::Lower; int lastTapDigit = -1; @@ -935,10 +1091,98 @@ int runNetworksApp(int argc, char** argv) { } }; + auto loadObexPickerDir = [&](const std::string& rawDir) { + std::string target = trimStr(rawDir); + if (target.empty() || target[0] != '/') { + target = readSavedObexDir(); + } + ::mkdir(target.c_str(), 0755); + char resolved[4096]; + if (::realpath(target.c_str(), resolved) != nullptr) { + target = resolved; + } + if (isDuressMode()) { + std::string root = kDuressHomeDirPath; + if (target != root && target.rfind(root + "/", 0) != 0) { + target = root + "/Downloads"; + ::mkdir(target.c_str(), 0755); + } + } + obexPickerDir = target; + obexPickerEntries.clear(); + obexPickerEntries.push_back({"[Use This Folder]", obexPickerDir}); + + std::string minRoot = isDuressMode() ? std::string(kDuressHomeDirPath) : "/"; + if (obexPickerDir != minRoot && obexPickerDir != "/") { + size_t sl = obexPickerDir.rfind('/'); + std::string parent = (sl == 0 || sl == std::string::npos) ? "/" : obexPickerDir.substr(0, sl); + obexPickerEntries.push_back({".. (Parent Folder)", parent}); + } + + if (!isDuressMode()) { + std::string home = getHomeDirPath(); + if (obexPickerDir == home) { + for (const char* sub : {"Downloads", "Pictures", "Music", "Documents"}) { + std::string p = home + "/" + sub; + ::mkdir(p.c_str(), 0755); + } + } + struct stat sdSt {}; + if (::stat("/media/sdcard", &sdSt) == 0 && S_ISDIR(sdSt.st_mode) && + obexPickerDir != "/media/sdcard") { + obexPickerEntries.push_back({"[SD Card] /media/sdcard", "/media/sdcard"}); + } + } + + std::vector subNames; + DIR* dir = ::opendir(obexPickerDir.c_str()); + if (dir) { + struct dirent* ent; + while ((ent = ::readdir(dir)) != nullptr) { + std::string nm = ent->d_name; + if (nm.empty() || nm[0] == '.') continue; + std::string full = (obexPickerDir == "/") ? ("/" + nm) : (obexPickerDir + "/" + nm); + struct stat st {}; + if (::stat(full.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) { + subNames.push_back(nm); + } + } + ::closedir(dir); + } + std::sort(subNames.begin(), subNames.end(), + [](const std::string& a, const std::string& b) { + return toLowerStr(a) < toLowerStr(b); + }); + for (const auto& nm : subNames) { + std::string full = (obexPickerDir == "/") ? ("/" + nm) : (obexPickerDir + "/" + nm); + obexPickerEntries.push_back({"/ " + nm, full}); + } + obexPickerSel = 0; + }; + + auto openObexDirPicker = [&](const std::string& initialDir, bool forPrompt) { + obexPickerForPrompt = forPrompt; + loadObexPickerDir(initialDir.empty() ? readSavedObexDir() : initialDir); + modal = NetModal::ObexDirPicker; + }; + + auto commitObexPickerSelection = [&]() { + writeSavedObexDir(obexPickerDir); + if (obexPickerForPrompt) { + obexPrompt.targetDir = obexPickerDir; + modal = NetModal::ObexIncomingPrompt; + obexPromptSel = 0; + } else { + btRx = readBtRxStatus(); + modal = NetModal::None; + setBanner("OBEX folder: " + shortenHomePath(obexPickerDir)); + } + }; + auto applyOpenArg = [&](const std::string& arg) { std::string a = toLowerStr(trimStr(arg)); modal = NetModal::None; - if (a == "bluetooth" || a == "bt") { + if (a == "bluetooth" || a == "bt" || a == "obex-prompt") { activeTab = NetTab::Bluetooth; } else if (a == "cell" || a == "cellular" || a == "apn" || a == "hotspot") { activeTab = NetTab::Cellular; @@ -1222,21 +1466,25 @@ int runNetworksApp(int argc, char** argv) { drawPango(layoutIcon, btRx.state == "RECEIVED" ? &colGreen - : (btRx.state == "RECEIVING" ? &colYellow : &colBlue), + : ((btRx.state == "RECEIVING" || btRx.state == "PENDING") ? &colYellow : &colBlue), 10, rxY, 22, btRx.state == "RECEIVED" ? kIconCheck : kIconFolderOpen); - if (btRx.state == "RECEIVING") { + if (btRx.state == "PENDING") { + drawPango(layoutSmall, &colYellow, 28, rxY, 22, + "Incoming: " + btRx.fileName + " [Prompt]", + kWinWidth - 34); + } else if (btRx.state == "RECEIVING") { drawPango(layoutSmall, &colYellow, 28, rxY, 22, "Rx: " + btRx.fileName + " (" + btRx.detail + ")", kWinWidth - 34); } else if (btRx.state == "RECEIVED") { drawPango(layoutSmall, sel4 ? &colWhite : &colGreen, 28, rxY, 22, - "Received: " + btRx.fileName + " [Open]", + "Rx OK: " + btRx.fileName + " [Menu]", kWinWidth - 34); } else { drawPango(layoutSmall, sel4 ? &colWhite : &colMuted, 28, rxY, 22, - "OBEX Receive: ~/Downloads [Open]", + "OBEX Dir: " + shortenHomePath(readSavedObexDir()) + " [Set]", kWinWidth - 34); } @@ -1472,6 +1720,88 @@ int runNetworksApp(int argc, char** argv) { "Independent from system hostname"); drawSoftkeyBar("Save", "Save", "Cancel"); + } else if (modal == NetModal::ObexActions) { + XSetForeground(dpy, gc, pt.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 10, 52, kWinWidth - 20, 162); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 10, 52, kWinWidth - 21, 161); + + drawPango(layoutMain, &colYellow, 18, 56, 22, "OBEX Target Folder", kWinWidth - 36); + drawPango(layoutSmall, &colMuted, 18, 78, 18, + tailFitPangoText(layoutSmall, shortenHomePath(readSavedObexDir()), kWinWidth - 36), + kWinWidth - 36); + const char* acts[3] = { + "Set Target Directory...", + "Open Folder in Files", + "Reset to ~/Downloads", + }; + for (int i = 0; i < 3; ++i) { + int ry = 102 + i * 34; + bool isSel = (actionSel == i); + XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton); + XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 30); + drawPango(layoutSmall, isSel ? &colWhite : &colLight, + 22, ry, 30, acts[i], kWinWidth - 44); + } + drawSoftkeyBar("Select", "OK", "Back"); + } else if (modal == NetModal::ObexDirPicker) { + XSetForeground(dpy, gc, pt.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 8, 28, kWinWidth - 16, 234); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 8, 28, kWinWidth - 17, 233); + + drawPango(layoutMain, &colYellow, 16, 32, 22, "Select Target Folder", kWinWidth - 32); + drawPango(layoutSmall, &colBlue, 16, 54, 18, + tailFitPangoText(layoutSmall, shortenHomePath(obexPickerDir), kWinWidth - 32), + kWinWidth - 32); + + const int listY = 76; + const int rowH = 30; + const int maxVis = 6; + int startIdx = std::clamp(obexPickerSel - maxVis / 2, 0, + std::max(0, static_cast(obexPickerEntries.size()) - maxVis)); + for (int i = 0; i < maxVis && (startIdx + i) < static_cast(obexPickerEntries.size()); ++i) { + int idx = startIdx + i; + int ry = listY + i * rowH; + bool isSel = (obexPickerSel == idx); + XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton); + XFillRectangle(dpy, pix, gc, 14, ry, kWinWidth - 28, rowH - 2); + XftColor* fg = isSel ? &colWhite : ((idx == 0) ? &colGreen : &colLight); + drawPango(layoutSmall, fg, 20, ry, rowH - 2, + obexPickerEntries[idx].first, kWinWidth - 40); + } + drawSoftkeyBar("Use Here", "Open", "Back"); + } else if (modal == NetModal::ObexIncomingPrompt) { + XSetForeground(dpy, gc, pt.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 8, 30, kWinWidth - 16, 230); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 8, 30, kWinWidth - 17, 229); + + drawPango(layoutMain, &colYellow, 16, 34, 22, "Incoming Bluetooth File", kWinWidth - 32); + std::string fromLbl = "From: " + (obexPrompt.senderName.empty() ? obexPrompt.senderMac : obexPrompt.senderName); + drawPango(layoutSmall, &colLight, 16, 58, 18, + tailFitPangoText(layoutSmall, fromLbl, kWinWidth - 32), kWinWidth - 32); + drawPango(layoutMain, &colWhite, 16, 78, 22, + tailFitPangoText(layoutMain, obexPrompt.fileName, kWinWidth - 32), kWinWidth - 32); + drawPango(layoutSmall, &colMuted, 16, 102, 18, + "Size: " + formatBytesShort(obexPrompt.fileBytes), kWinWidth - 32); + + std::string dirLabel = "Dir: " + shortenHomePath(obexPrompt.targetDir) + " [Set]"; + std::string pRows[3] = { + "Accept & Save File", + tailFitPangoText(layoutSmall, dirLabel, kWinWidth - 44), + "Reject Transfer", + }; + for (int i = 0; i < 3; ++i) { + int ry = 126 + i * 38; + bool isSel = (obexPromptSel == i); + XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton); + XFillRectangle(dpy, pix, gc, 14, ry, kWinWidth - 28, 34); + XftColor* fg = isSel ? &colWhite + : ((i == 0) ? &colGreen : ((i == 2) ? &colOrange : &colBlue)); + drawPango(layoutSmall, fg, 20, ry, 34, pRows[i], kWinWidth - 40); + } + drawSoftkeyBar("Accept", "Select", "Reject"); } if (!statusBanner.empty() && nowMs() < statusBannerUntilMs) { @@ -1516,6 +1846,11 @@ int runNetworksApp(int argc, char** argv) { auto hideWindow = [&]() { if (!visible) return; + if (modal == NetModal::ObexIncomingPrompt && obexPrompt.active) { + writeObexDecision(obexPrompt.reqId, false, obexPrompt.targetDir); + obexPrompt.active = false; + } + openedForObexPrompt = false; int xfdLocal = ConnectionNumber(dpy); int64_t drainDeadline = nowMs() + 180; while (nowMs() < drainDeadline && querySoftkeysDown(dpy) != 0) { @@ -1537,6 +1872,54 @@ int runNetworksApp(int argc, char** argv) { ::unlink(activePidPath.c_str()); }; + auto resolveObexPrompt = [&](bool accept) { + if (obexPrompt.active) { + std::string dest = obexPrompt.targetDir.empty() ? readSavedObexDir() : obexPrompt.targetDir; + writeObexDecision(obexPrompt.reqId, accept, dest); + obexPrompt.active = false; + } + modal = NetModal::None; + if (openedForObexPrompt) { + openedForObexPrompt = false; + hideWindow(); + } else { + btRx = readBtRxStatus(); + setBanner(accept ? ("Receiving to " + shortenHomePath(obexPrompt.targetDir)) + : "Transfer rejected"); + render(); + } + }; + + auto tryPresentObexPrompt = [&](bool forceMarkOpened = false) { + ObexPromptInfo p = readObexPromptFile(); + if (!p.active) { + pendingDeferredObexPrompt = false; + return; + } + if (isPhonePasscodeLocked() || isPidFileAlive(getRuntimeFile("xlocker.pid")) || + isCallActiveOrRingingFast() || isLidClosedState()) { + pendingDeferredObexPrompt = true; + return; + } + pendingDeferredObexPrompt = false; + bool wasVisible = visible; + obexPrompt = p; + if (obexPrompt.targetDir.empty()) { + obexPrompt.targetDir = readSavedObexDir(); + } + obexPromptSel = 0; + if (!wasVisible) { + openedForObexPrompt = true; + showWindow("bluetooth"); + } else { + if (forceMarkOpened) openedForObexPrompt = true; + activeTab = NetTab::Bluetooth; + } + wakeDisplayForObex(dpy); + modal = NetModal::ObexIncomingPrompt; + render(); + }; + auto connectWifiNow = [&](const std::string& ssid, const std::string& pass) { modal = NetModal::None; setBanner("Connecting to " + ssid + "..."); @@ -1648,15 +2031,32 @@ int runNetworksApp(int argc, char** argv) { writeSavedBtDiscoverable(nextDisc); btCtrl.discoverable = nextDisc; if (btOn) { - runCaptureCmd("timeout 2 bluetoothctl discoverable-timeout 0 >/dev/null 2>&1; " + runCaptureCmd("timeout 2 bluetoothctl discoverable-timeout 60 >/dev/null 2>&1; " + + std::string(nextDisc ? "timeout 2 bluetoothctl pairable on >/dev/null 2>&1; " : "") + "timeout 2 bluetoothctl discoverable " + std::string(nextDisc ? "on" : "off") + " >/dev/null 2>&1"); } refreshCurrentTab(false); - setBanner(nextDisc ? "Bluetooth: Visible to nearby devices" + setBanner(nextDisc ? "Bluetooth: Visible for 60s" : "Bluetooth: Hidden from discovery"); }; + auto refreshTargetBtFromList = [&]() { + const BtDeviceEntry* best = nullptr; + for (const auto& d : btList) { + bool macMatch = (d.mac == targetBt.mac); + bool nameMatch = (!targetBt.name.empty() && d.name == targetBt.name); + if (!macMatch && !nameMatch) continue; + if (!best || (d.connected && !best->connected) || + (d.connected == best->connected && d.kind == BtDevKind::Audio && + best->kind != BtDevKind::Audio) || + (macMatch && best->mac != targetBt.mac && !d.connected)) { + best = &d; + } + } + if (best) targetBt = *best; + }; + auto executeBtAction = [&](int act) { modal = NetModal::None; int rc = 0; @@ -1667,13 +2067,8 @@ int runNetworksApp(int argc, char** argv) { shellQuote(targetBt.mac) + " " + shellQuote(targetBt.name) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); - bool isConn = (rc == 0); - for (const auto& d : btList) { - if ((d.mac == targetBt.mac || d.name == targetBt.name) && d.connected) { - isConn = true; - break; - } - } + refreshTargetBtFromList(); + bool isConn = (rc == 0) || targetBt.connected; if (isConn && targetBt.kind == BtDevKind::Audio) { std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); if (ofs) ofs << "Bluetooth\n"; @@ -1698,14 +2093,8 @@ int runNetworksApp(int argc, char** argv) { shellQuote(targetBt.mac) + " " + shellQuote(targetBt.name) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); - bool isPairedOrConn = (rc == 0); - for (const auto& d : btList) { - if ((d.mac == targetBt.mac || d.name == targetBt.name) && - (d.connected || d.paired)) { - isPairedOrConn = true; - break; - } - } + refreshTargetBtFromList(); + bool isPairedOrConn = (rc == 0) || targetBt.connected || targetBt.paired; if (isPairedOrConn && targetBt.kind == BtDevKind::Audio) { std::ofstream ofs("/tmp/sxmo_audio_out_device", std::ios::trunc); if (ofs) ofs << "Bluetooth\n"; @@ -1791,6 +2180,45 @@ int runNetworksApp(int argc, char** argv) { saveBtDeviceName(); return; } + if (modal == NetModal::ObexActions) { + if (actionSel == 0) { + openObexDirPicker(readSavedObexDir(), false); + } else if (actionSel == 1) { + std::string target = (!btRx.savedPath.empty()) ? btRx.savedPath : readSavedObexDir(); + ::mkdir(readSavedObexDir().c_str(), 0755); + modal = NetModal::None; + hideWindow(); + if (!sendPluginCommand("files", "OPEN " + target)) { + runAsyncArgv("xfiles", target.c_str()); + } + } else { + std::string defDir = getHomeDir() + "/Downloads"; + writeSavedObexDir(defDir); + btRx = readBtRxStatus(); + modal = NetModal::None; + setBanner("OBEX folder reset to ~/Downloads"); + } + return; + } + if (modal == NetModal::ObexDirPicker) { + if (obexPickerSel == 0) { + commitObexPickerSelection(); + } else if (obexPickerSel >= 0 && + obexPickerSel < static_cast(obexPickerEntries.size())) { + loadObexPickerDir(obexPickerEntries[obexPickerSel].second); + } + return; + } + if (modal == NetModal::ObexIncomingPrompt) { + if (obexPromptSel == 0) { + resolveObexPrompt(true); + } else if (obexPromptSel == 1) { + openObexDirPicker(obexPrompt.targetDir, true); + } else { + resolveObexPrompt(false); + } + return; + } if (activeTab == NetTab::Wifi) { if (wifiRowSel == 0) { @@ -1890,13 +2318,11 @@ int runNetworksApp(int argc, char** argv) { refreshCurrentTab(true); setBanner("Found " + std::to_string(btList.size()) + " device(s)"); } else if (btRowSel == 4 && btOn) { - std::string target = (!btRx.savedPath.empty()) - ? btRx.savedPath - : (getHomeDirPath() + "/Downloads"); - ::mkdir((getHomeDirPath() + "/Downloads").c_str(), 0755); - hideWindow(); - if (!sendPluginCommand("files", "OPEN " + target)) { - runAsyncArgv("xfiles", target.c_str()); + if (readObexPromptFile().active) { + tryPresentObexPrompt(); + } else { + actionSel = 0; + modal = NetModal::ObexActions; } } else if (btOn && btRowSel - 5 >= 0 && btRowSel - 5 < static_cast(btList.size())) { @@ -1916,6 +2342,14 @@ int runNetworksApp(int argc, char** argv) { saveBtDeviceName(); return; } + if (modal == NetModal::ObexDirPicker) { + commitObexPickerSelection(); + return; + } + if (modal == NetModal::ObexIncomingPrompt) { + resolveObexPrompt(true); + return; + } if (modal != NetModal::None) { handleEnterKey(); return; @@ -1944,6 +2378,14 @@ int runNetworksApp(int argc, char** argv) { }; auto handleRightSoftkey = [&]() { + if (modal == NetModal::ObexIncomingPrompt) { + resolveObexPrompt(false); + return; + } + if (modal == NetModal::ObexDirPicker) { + modal = obexPickerForPrompt ? NetModal::ObexIncomingPrompt : NetModal::ObexActions; + return; + } if (modal != NetModal::None) { modal = NetModal::None; return; @@ -1953,6 +2395,9 @@ int runNetworksApp(int argc, char** argv) { if (!isPreload) { showWindow(openArg); + if (toLowerStr(trimStr(openArg)) == "obex-prompt") { + tryPresentObexPrompt(true); + } } int xfd = ConnectionNumber(dpy); @@ -2012,7 +2457,11 @@ int runNetworksApp(int argc, char** argv) { } if (sym == XF86XK_HangupPhone || sym == XK_Cancel) { - hideWindow(); + if (modal == NetModal::ObexIncomingPrompt) { + resolveObexPrompt(false); + } else { + hideWindow(); + } continue; } @@ -2074,8 +2523,10 @@ int runNetworksApp(int argc, char** argv) { continue; } - if (modal == NetModal::WifiActions || modal == NetModal::BtActions) { - int actCount = (modal == NetModal::BtActions) ? 5 : 4; + if (modal == NetModal::WifiActions || modal == NetModal::BtActions || + modal == NetModal::ObexActions) { + int actCount = (modal == NetModal::BtActions) ? 5 + : ((modal == NetModal::ObexActions) ? 3 : 4); if (sym == XK_Up || sym == XK_KP_Up) { actionSel = (actionSel + actCount - 1) % actCount; render(); @@ -2089,8 +2540,65 @@ int runNetworksApp(int argc, char** argv) { continue; } + if (modal == NetModal::ObexDirPicker) { + int total = static_cast(obexPickerEntries.size()); + if ((sym == XK_Up || sym == XK_KP_Up) && total > 0) { + obexPickerSel = (obexPickerSel + total - 1) % total; + render(); + } else if ((sym == XK_Down || sym == XK_KP_Down) && total > 0) { + obexPickerSel = (obexPickerSel + 1) % total; + render(); + } else if (sym == XK_Left || sym == XK_KP_Left || sym == XK_BackSpace) { + std::string minRoot = isDuressMode() ? std::string(kDuressHomeDirPath) : "/"; + if (obexPickerDir != minRoot && obexPickerDir != "/") { + size_t sl = obexPickerDir.rfind('/'); + std::string parent = (sl == 0 || sl == std::string::npos) ? "/" : obexPickerDir.substr(0, sl); + loadObexPickerDir(parent); + render(); + } + } else if (sym == XK_Right || sym == XK_KP_Right) { + if (obexPickerSel > 0 && obexPickerSel < total) { + loadObexPickerDir(obexPickerEntries[obexPickerSel].second); + render(); + } + } else if (sym == XK_Return || sym == XK_KP_Enter) { + handleEnterKey(); + render(); + } + continue; + } + + if (modal == NetModal::ObexIncomingPrompt) { + char pdch = mapDialKey(sym, kc, ev.xkey.state); + if (sym == XK_Up || sym == XK_KP_Up) { + obexPromptSel = (obexPromptSel + 2) % 3; + render(); + } else if (sym == XK_Down || sym == XK_KP_Down) { + obexPromptSel = (obexPromptSel + 1) % 3; + render(); + } else if ((sym == XK_Left || sym == XK_KP_Left || + sym == XK_Right || sym == XK_KP_Right || pdch == '*') && + obexPromptSel == 1) { + openObexDirPicker(obexPrompt.targetDir, true); + render(); + } else if (sym == XK_Return || sym == XK_KP_Enter) { + handleEnterKey(); + render(); + } + continue; + } + // Main View Tab & Row Navigation char dch = mapDialKey(sym, kc, ev.xkey.state); + if (dch == '#' && activeTab == NetTab::Bluetooth && btOn) { + std::string target = (!btRx.savedPath.empty()) ? btRx.savedPath : readSavedObexDir(); + ::mkdir(readSavedObexDir().c_str(), 0755); + hideWindow(); + if (!sendPluginCommand("files", "OPEN " + target)) { + runAsyncArgv("xfiles", target.c_str()); + } + continue; + } if (dch == '1') { activeTab = NetTab::Wifi; refreshCurrentTab(false); @@ -2190,6 +2698,29 @@ int runNetworksApp(int argc, char** argv) { } } + if (pendingDeferredObexPrompt) { + tryPresentObexPrompt(); + if (pendingDeferredObexPrompt && (timeoutMs < 0 || timeoutMs > 300)) { + timeoutMs = 300; + } + } + if (modal == NetModal::ObexIncomingPrompt) { + if (!readObexPromptFile().active) { + obexPrompt.active = false; + modal = NetModal::None; + if (openedForObexPrompt) { + openedForObexPrompt = false; + hideWindow(); + } else { + btRx = readBtRxStatus(); + setBanner("Transfer timed out or cancelled"); + render(); + } + } else if (timeoutMs < 0 || timeoutMs > 300) { + timeoutMs = 300; + } + } + struct pollfd pfds[2]; pfds[0].fd = xfd; pfds[0].events = POLLIN; @@ -2210,12 +2741,17 @@ int runNetworksApp(int argc, char** argv) { refreshCurrentTab(false); } if (visible) render(); + } else if (cmd.rfind("OBEX_PROMPT", 0) == 0) { + tryPresentObexPrompt(); } else if (cmd == "TOGGLE") { if (visible) hideWindow(); else showWindow(); } else if (cmd.rfind("OPEN", 0) == 0) { std::string arg = (cmd.size() > 5) ? trimStr(cmd.substr(5)) : ""; showWindow(arg); + if (toLowerStr(arg) == "obex-prompt") { + tryPresentObexPrompt(true); + } } } } diff --git a/src/dwm-plugins/sxmo_vibrate.c b/src/dwm-plugins/sxmo_vibrate.c index 9baf85d..fd934fb 100644 --- a/src/dwm-plugins/sxmo_vibrate.c +++ b/src/dwm-plugins/sxmo_vibrate.c @@ -197,6 +197,15 @@ static int is_non_speaker_name(const char* s) { } static int is_non_speaker_audio_route(void) { + FILE* sco_fp = fopen("/tmp/sxmo_bt_sco_mm_active", "r"); + if (sco_fp) { + int ch = fgetc(sco_fp); + fclose(sco_fp); + if (ch == '1') { + return 1; + } + } + char buf[128]; const char* paths[2]; char cfg_dir[448];