Fix A2DP Bluetooth audio routing, stream migration, hotplug monitoring, and q6voice teardown

This commit is contained in:
Luxferre committed 2026-11-04 15:42:58 +02:00
1 parent b2ade2dc42
commit b8dea31b59
34 files changed
+533 -155

No files matched your search

+112 -22
View File
@@ -1006,6 +1006,52 @@ def ensure_daemon_running():
pass
def clear_stale_linkkey(mac):
mac = mac.strip().upper()
if not mac:
return False
if os.geteuid() != 0:
res = subprocess.run(
["doas", "-n", "/usr/bin/bananarchy-bt-obex", "clear-linkkey", mac],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return res.returncode == 0
bt_root = "/var/lib/bluetooth"
changed = False
if os.path.isdir(bt_root):
for adapter in os.listdir(bt_root):
info_path = os.path.join(bt_root, adapter, mac, "info")
if not os.path.isfile(info_path):
continue
try:
with open(info_path, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
out_lines = []
skip_sec = False
for ln in lines:
s = ln.strip()
if s.startswith("[") and s.endswith("]"):
skip_sec = s.lower() in ("[linkkey]", "[longtermkey]", "[peripherallongtermkey]", "[slaveLongtermkey]")
if not skip_sec:
out_lines.append(ln)
if len(out_lines) != len(lines):
with open(info_path, "w", encoding="utf-8") as f:
f.writelines(out_lines)
changed = True
except Exception:
pass
if changed:
subprocess.run(["rc-service", "bluetooth", "restart"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(0.8)
subprocess.run(["bluetoothctl", "power", "on"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(0.4)
return changed
def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
from jeepney import DBusAddress, new_method_call, MessageType
from jeepney.io.blocking import open_dbus_connection
@@ -1026,8 +1072,10 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
interface="org.freedesktop.DBus.ObjectManager")
conn = None
nonlocal_conn = [None]
try:
conn = open_dbus_connection(bus="SYSTEM")
nonlocal_conn[0] = conn
aprop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
interface="org.freedesktop.DBus.Properties")
dbus_call_with_agent(
@@ -1056,9 +1104,9 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
while time.time() < end_t:
rem = max(0.05, min(0.25, end_t - time.time()))
try:
m = conn.receive(timeout=rem)
m = nonlocal_conn[0].receive(timeout=rem)
if m is not None:
handle_agent_method_call(conn, m, cli_agent_path)
handle_agent_method_call(nonlocal_conn[0], m, cli_agent_path)
except TimeoutError:
pass
@@ -1066,7 +1114,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
prop_addr = DBusAddress(dpath, bus_name="org.bluez",
interface="org.freedesktop.DBus.Properties")
rep = dbus_call_with_agent(
conn,
nonlocal_conn[0],
new_method_call(prop_addr, "GetAll", "s", ("org.bluez.Device1",)),
cli_agent_path,
timeout=2.5
@@ -1086,7 +1134,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
return None
t_low = target_name.strip().lower()
rep = dbus_call_with_agent(
conn,
nonlocal_conn[0],
new_method_call(om_addr, "GetManagedObjects"),
cli_agent_path,
timeout=3.0
@@ -1137,11 +1185,11 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
dev_addr = DBusAddress(dpath, bus_name="org.bluez",
interface="org.bluez.Device1")
dbus_call_with_agent(
conn, new_method_call(dev_addr, "Disconnect"), cli_agent_path, timeout=2.0
nonlocal_conn[0], new_method_call(dev_addr, "Disconnect"), cli_agent_path, timeout=2.0
)
def attempt_connect_path(dpath, want_pair):
trust_device_path(conn, dpath)
trust_device_path(nonlocal_conn[0], dpath)
p = get_dev_props(dpath)
if p is None:
return False
@@ -1154,7 +1202,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
interface="org.bluez.Device1")
if want_pair and not (p.get("Paired") or p.get("Bonded")):
rep = dbus_call_with_agent(
conn, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0
nonlocal_conn[0], new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0
)
if rep is None:
cancel_pending_connect(dpath)
@@ -1162,10 +1210,48 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
if not p.get("Connected"):
rep = dbus_call_with_agent(
conn, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
nonlocal_conn[0], new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
)
if rep is None:
cancel_pending_connect(dpath)
elif rep.header.message_type == MessageType.error:
err_str = " ".join(str(x) for x in (rep.body or ())).lower()
if "key-missing" in err_str or "authentication" in err_str:
dev_mac = dpath.split("dev_")[-1].replace("_", ":")
if clear_stale_linkkey(dev_mac):
try:
nonlocal_conn[0].close()
except Exception:
pass
conn_new = open_dbus_connection(bus="SYSTEM")
nonlocal_conn[0] = conn_new
dbus_call_with_agent(
conn_new,
new_method_call(aprop_addr, "Set", "ssv",
("org.bluez.Adapter1", "Pairable", ("b", True))),
cli_agent_path,
timeout=2.0
)
dbus_call_with_agent(
conn_new,
new_method_call(am_addr, "RegisterAgent", "os",
(cli_agent_path, "NoInputNoOutput")),
cli_agent_path,
timeout=2.5
)
dbus_call_with_agent(
conn_new,
new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
cli_agent_path,
timeout=2.5
)
trust_device_path(conn_new, dpath)
dbus_call_with_agent(
conn_new, new_method_call(dev_addr, "Pair"), cli_agent_path, timeout=8.0
)
dbus_call_with_agent(
conn_new, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
)
p = get_dev_props(dpath) or {}
if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")):
@@ -1179,7 +1265,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
def scan_for_device(prefer_path, max_scan=15.0):
dbus_call_with_agent(
conn, new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5
nonlocal_conn[0], new_method_call(adapter_addr, "StartDiscovery"), cli_agent_path, timeout=2.5
)
scan_start = time.time()
scan_deadline = scan_start + max_scan
@@ -1196,11 +1282,11 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
ap = get_dev_props(alt)
if ap and (ap.get("Connected") or ap.get("RSSI") is not None):
discovered_path = alt
trust_device_path(conn, discovered_path)
trust_device_path(nonlocal_conn[0], discovered_path)
if ap.get("Connected") or (time.time() - scan_start) >= 0.8:
break
dbus_call_with_agent(
conn, new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0
nonlocal_conn[0], new_method_call(adapter_addr, "StopDiscovery"), cli_agent_path, timeout=2.0
)
pump_agent(0.15)
return discovered_path
@@ -1215,22 +1301,21 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
dev_path = alt
props = get_dev_props(dev_path)
trust_device_path(conn, dev_path)
trust_device_path(nonlocal_conn[0], dev_path)
# If the device is not currently connected and has no active scan RSSI,
# run a discovery scan (up to 15s, stopping early as soon as seen) so BLE
# peripherals are in the controller cache or caught if they rotated their MAC.
if not (props and (props.get("Connected") or props.get("RSSI") is not None)):
dev_path = scan_for_device(dev_path, max_scan=15.0)
# Try connecting directly first when BlueZ already knows the device (avoids
# blocking 15s in StartDiscovery for paired BR/EDR headsets in Page Scan).
if props is None:
dev_path = scan_for_device(dev_path, max_scan=8.0)
ok = attempt_connect_path(dev_path, do_pair)
if not ok:
discovered_path = scan_for_device(dev_path, max_scan=15.0)
discovered_path = scan_for_device(dev_path, max_scan=8.0)
ok = attempt_connect_path(discovered_path, do_pair)
if ok and discovered_path != orig_path and orig_unbonded:
dbus_call_with_agent(
conn,
nonlocal_conn[0],
new_method_call(adapter_addr, "RemoveDevice", "o", (orig_path,)),
cli_agent_path,
timeout=2.0
@@ -1241,10 +1326,11 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
except Exception:
return 1
finally:
if conn is not None:
c_final = nonlocal_conn[0]
if c_final is not None:
try:
dbus_call_with_agent(
conn,
c_final,
new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)),
cli_agent_path,
timeout=1.5
@@ -1252,7 +1338,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
except Exception:
pass
try:
conn.close()
c_final.close()
except Exception:
pass
@@ -1295,6 +1381,10 @@ def main():
return 1
nm = sys.argv[3] if len(sys.argv) >= 4 else ""
return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=True)
elif cmd == "clear-linkkey":
if len(sys.argv) < 3:
return 1
return 0 if clear_stale_linkkey(sys.argv[2]) else 1
elif cmd == "send":
if len(sys.argv) < 4:
print("Usage: bananarchy-bt-obex send <MAC> <filepath>", file=sys.stderr)