Fix bluetoothd CPU busy-loops, cache BT state, and refresh a1120 images
- Add /etc/conf.d/bluetooth (supervise-daemon, retry=TERM/3/KILL/1, --noplugin=hfp,bap,bass,mcp,vcp,micp,csip,ccp,tmap,gmap,asha,midi,neard) and drop gateway UUIDs (111f/1112/110a) from main.conf ReconnectUUIDs so Experimental = true keeps PreferredBearer without BlueZ hfp-hf/ATT EOF GMainLoop spins. - Set duplicate-data off in bananarchy-bt-scan.sh and update sxmo_bluetoothtoggle.sh to disconnect, btmgmt power off, and clean state files on disable so adapter_stop() never busy-loops on dual-bearer links. - Add single-shot BlueZ ObjectManager state caching (bt_state.tsv, dump-state, CTRL_READY_FILE, EPHEMERAL_DEV_PROPS filter) in bananarchy-bt-obex and consume it in networks.so instead of per-device bluetoothctl refresh storms. - Extend Bluetooth host tests and check-rebuild.sh, update docs, and rebuild/pin a1120 (cocojamboo) images and release archives for nokia-argon, nokia-beatles, nokia-coconut, and nokia-sparkler.
This commit is contained in:
1 parent
1e1fe7c317
commit
1e7077e314
15 files changed
+924
-282
No files matched your search
@@ -13,6 +13,8 @@ import signal
|
||||
import subprocess
|
||||
import threading
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
OPP_UUID = "00001105-0000-1000-8000-00805f9b34fb"
|
||||
RX_STATUS_FILE = "/tmp/bananarchy_bt_rx.status"
|
||||
TX_STATUS_FILE = "/tmp/bananarchy_bt_tx.status"
|
||||
@@ -26,6 +28,16 @@ PAIR_PROMPT_FILE = "/run/bananarchy/bt-obex/pair_prompt.tsv"
|
||||
PAIR_DECISION_FILE = "/run/bananarchy/bt-obex/pair_decision.tsv"
|
||||
OP_DONE_FILE = "/run/bananarchy/bt-obex/op_done.tsv"
|
||||
AGENT_READY_FILE = "/run/bananarchy/bt-obex/agent_ready"
|
||||
BT_STATE_FILE = "/run/bananarchy/bt-obex/bt_state.tsv"
|
||||
CTRL_READY_FILE = "/run/bananarchy/bt-obex/ctrl_ready"
|
||||
EPHEMERAL_DEV_PROPS = frozenset((
|
||||
"RSSI",
|
||||
"TxPower",
|
||||
"ManufacturerData",
|
||||
"ServiceData",
|
||||
"AdvertisingData",
|
||||
"AdvertisingFlags",
|
||||
))
|
||||
OBEX_PROMPT_LOCK = threading.Lock()
|
||||
PAIR_PROMPT_LOCK = threading.Lock()
|
||||
PAIR_CANCEL_EVENT = threading.Event()
|
||||
@@ -98,11 +110,11 @@ def ensure_obex_ipc_dir():
|
||||
pass
|
||||
|
||||
|
||||
def write_status(path, text):
|
||||
def _atomic_write_text(path, content):
|
||||
tmp = f"{path}.{os.getpid()}.tmp"
|
||||
try:
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
f.write(text.strip() + "\n")
|
||||
f.write(content)
|
||||
os.chmod(tmp, 0o644)
|
||||
try:
|
||||
os.chown(tmp, 10000, 10000)
|
||||
@@ -124,6 +136,15 @@ def write_status(path, text):
|
||||
pass
|
||||
|
||||
|
||||
def write_status(path, text):
|
||||
_atomic_write_text(path, text.strip() + "\n")
|
||||
|
||||
|
||||
def write_multiline_atomic(path, content):
|
||||
text = content if content.endswith("\n") else (content + "\n")
|
||||
_atomic_write_text(path, text)
|
||||
|
||||
|
||||
def notify_networks_ui(msg="REFRESH_BT\n"):
|
||||
fifo = "/tmp/dwm_plugin_networks.fifo"
|
||||
if os.path.exists(fifo):
|
||||
@@ -1121,6 +1142,170 @@ def read_cached_bt_device_info(dev_path, bt_root="/var/lib/bluetooth"):
|
||||
return out
|
||||
|
||||
|
||||
def unwrap_dbus_variant(val):
|
||||
if isinstance(val, tuple) and len(val) == 2 and isinstance(val[0], str):
|
||||
return val[1]
|
||||
if (isinstance(val, list) and len(val) == 2 and isinstance(val[0], str) and
|
||||
len(val[0]) <= 8 and "-" not in val[0]):
|
||||
return val[1]
|
||||
return val
|
||||
|
||||
|
||||
def unwrap_props_dict(raw):
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
return {k: unwrap_dbus_variant(v) for k, v in raw.items()}
|
||||
|
||||
|
||||
def format_managed_objects_tsv(objs):
|
||||
"""Format BlueZ ObjectManager objects into a compact CTRL/DEV TSV snapshot."""
|
||||
if not isinstance(objs, dict):
|
||||
return ""
|
||||
|
||||
adapter_props = None
|
||||
if isinstance(objs.get("/org/bluez/hci0"), dict):
|
||||
a = objs["/org/bluez/hci0"].get("org.bluez.Adapter1")
|
||||
if isinstance(a, dict):
|
||||
adapter_props = unwrap_props_dict(a)
|
||||
|
||||
if adapter_props is None:
|
||||
for opath in sorted(objs.keys()):
|
||||
if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci"):
|
||||
continue
|
||||
ifaces = objs.get(opath)
|
||||
if isinstance(ifaces, dict) and isinstance(ifaces.get("org.bluez.Adapter1"), dict):
|
||||
adapter_props = unwrap_props_dict(ifaces["org.bluez.Adapter1"])
|
||||
break
|
||||
|
||||
if adapter_props is None:
|
||||
return ""
|
||||
|
||||
powered = 1 if bool(adapter_props.get("Powered", False)) else 0
|
||||
disc = 1 if bool(adapter_props.get("Discoverable", False)) else 0
|
||||
alias = (
|
||||
str(adapter_props.get("Alias") or adapter_props.get("Name") or "")
|
||||
.replace("\t", " ").replace("\n", " ").replace("\r", " ").strip()
|
||||
)
|
||||
lines = [f"CTRL\t{powered}\t{disc}\t{alias}"]
|
||||
|
||||
dev_rows = []
|
||||
for opath, ifaces in objs.items():
|
||||
if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci") or "/dev_" not in opath:
|
||||
continue
|
||||
if not isinstance(ifaces, dict) or not isinstance(ifaces.get("org.bluez.Device1"), dict):
|
||||
continue
|
||||
dprops = unwrap_props_dict(ifaces["org.bluez.Device1"])
|
||||
mac = str(dprops.get("Address") or _extract_dev_mac_from_path(opath) or "").strip().upper()
|
||||
if not mac:
|
||||
continue
|
||||
name = (
|
||||
str(dprops.get("Alias") or dprops.get("Name") or mac)
|
||||
.replace("\t", " ").replace("\n", " ").replace("\r", " ").strip()
|
||||
) or mac
|
||||
paired = 1 if (bool(dprops.get("Paired", False)) or bool(dprops.get("Bonded", False))) else 0
|
||||
connected = 1 if bool(dprops.get("Connected", False)) else 0
|
||||
icon = (
|
||||
str(dprops.get("Icon") or "")
|
||||
.replace("\t", " ").replace("\n", " ").replace("\r", " ").strip().lower()
|
||||
)
|
||||
cod = dprops.get("Class")
|
||||
class_hex = f"0x{cod:06x}" if (isinstance(cod, int) and not isinstance(cod, bool)) else ""
|
||||
batt_pct = -1
|
||||
b_raw = ifaces.get("org.bluez.Battery1")
|
||||
if isinstance(b_raw, dict):
|
||||
bprops = unwrap_props_dict(b_raw)
|
||||
pval = bprops.get("Percentage")
|
||||
if isinstance(pval, (int, float)) and not isinstance(pval, bool):
|
||||
batt_pct = max(0, min(100, int(pval)))
|
||||
raw_uuids = dprops.get("UUIDs") or []
|
||||
uuids = ";".join(
|
||||
str(u).replace("\t", "").replace("\n", "").replace("\r", "").strip().lower()
|
||||
for u in raw_uuids if str(u).strip()
|
||||
)
|
||||
dev_rows.append((
|
||||
mac,
|
||||
opath,
|
||||
f"DEV\t{mac}\t{name}\t{paired}\t{connected}\t{icon}\t{class_hex}\t{batt_pct}\t{uuids}"
|
||||
))
|
||||
|
||||
dev_rows.sort(key=lambda item: (item[0], item[1]))
|
||||
lines.extend(row[2] for row in dev_rows)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def fetch_managed_objects(conn=None, agent_path="", timeout=2.5):
|
||||
if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"):
|
||||
return None
|
||||
own_conn = None
|
||||
try:
|
||||
from jeepney import DBusAddress, MessageType, new_method_call
|
||||
from jeepney.io.blocking import open_dbus_connection
|
||||
c = conn
|
||||
if c is None:
|
||||
own_conn = open_dbus_connection(bus="SYSTEM")
|
||||
c = own_conn
|
||||
om_addr = DBusAddress("/", bus_name="org.bluez",
|
||||
interface="org.freedesktop.DBus.ObjectManager")
|
||||
call = new_method_call(om_addr, "GetManagedObjects")
|
||||
if conn is not None and agent_path:
|
||||
rep = dbus_call_with_agent(c, call, agent_path, timeout=timeout)
|
||||
else:
|
||||
rep = c.send_and_get_reply(call, timeout=timeout)
|
||||
if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
|
||||
objs = rep.body[0]
|
||||
if isinstance(objs, dict):
|
||||
return objs
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if own_conn is not None:
|
||||
try:
|
||||
own_conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def dump_bluez_state_tsv(conn=None, agent_path=""):
|
||||
objs = fetch_managed_objects(conn=conn, agent_path=agent_path)
|
||||
tsv = format_managed_objects_tsv(objs)
|
||||
if not tsv:
|
||||
return ""
|
||||
try:
|
||||
ensure_obex_ipc_dir()
|
||||
write_multiline_atomic(BT_STATE_FILE, tsv)
|
||||
except OSError:
|
||||
pass
|
||||
return tsv
|
||||
|
||||
|
||||
def is_controller_powered_dbus(timeout=0.5):
|
||||
if not os.environ.get("DBUS_SYSTEM_BUS_ADDRESS") and not os.path.exists("/run/dbus/system_bus_socket"):
|
||||
return False
|
||||
c = None
|
||||
try:
|
||||
from jeepney import DBusAddress, MessageType, new_method_call
|
||||
from jeepney.io.blocking import open_dbus_connection
|
||||
c = open_dbus_connection(bus="SYSTEM")
|
||||
prop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
|
||||
interface="org.freedesktop.DBus.Properties")
|
||||
rep = c.send_and_get_reply(
|
||||
new_method_call(prop_addr, "Get", "ss", ("org.bluez.Adapter1", "Powered")),
|
||||
timeout=timeout
|
||||
)
|
||||
if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
|
||||
return bool(unwrap_dbus_variant(rep.body[0]))
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if c is not None:
|
||||
try:
|
||||
c.close()
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def query_dev_props_fresh(dev_path, timeout=0.6):
|
||||
if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
|
||||
return {}
|
||||
@@ -1140,10 +1325,7 @@ def query_dev_props_fresh(dev_path, timeout=0.6):
|
||||
if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
|
||||
raw = rep.body[0]
|
||||
if isinstance(raw, dict):
|
||||
return {
|
||||
k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
|
||||
for k, v in raw.items()
|
||||
}
|
||||
return unwrap_props_dict(raw)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
@@ -1527,47 +1709,130 @@ def run_daemon():
|
||||
opp_registered = False
|
||||
rfcomm_listener = None
|
||||
dev_props_cache = {}
|
||||
managed_objs = {}
|
||||
|
||||
def write_state_from_cache():
|
||||
tsv = format_managed_objects_tsv(managed_objs)
|
||||
if tsv:
|
||||
ensure_obex_ipc_dir()
|
||||
write_multiline_atomic(BT_STATE_FILE, tsv)
|
||||
|
||||
def apply_adapter_settings(dbus_c):
|
||||
bt_name = ""
|
||||
try:
|
||||
if os.path.exists("/home/user/.config/sxmo/bt_name"):
|
||||
with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf:
|
||||
bt_name = nf.readline().strip()
|
||||
except OSError:
|
||||
pass
|
||||
if not bt_name:
|
||||
try:
|
||||
bt_name = socket.gethostname().strip()
|
||||
except Exception:
|
||||
bt_name = "Bananarchy"
|
||||
|
||||
bt_disc = "0"
|
||||
try:
|
||||
if os.path.exists("/home/user/.config/sxmo/bt_discoverable"):
|
||||
with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df:
|
||||
bt_disc = df.readline().strip() or "0"
|
||||
except OSError:
|
||||
pass
|
||||
disc_on = bt_disc.lower() not in ("0", "off", "no", "false")
|
||||
|
||||
if dbus_c is not None:
|
||||
try:
|
||||
aprop = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
|
||||
interface="org.freedesktop.DBus.Properties")
|
||||
if bt_name:
|
||||
dbus_call_with_agent(
|
||||
dbus_c,
|
||||
new_method_call(aprop, "Set", "ssv",
|
||||
("org.bluez.Adapter1", "Alias", ("s", bt_name))),
|
||||
agent_path,
|
||||
timeout=2.0
|
||||
)
|
||||
dbus_call_with_agent(
|
||||
dbus_c,
|
||||
new_method_call(aprop, "Set", "ssv",
|
||||
("org.bluez.Adapter1", "PairableTimeout", ("u", 0))),
|
||||
agent_path,
|
||||
timeout=2.0
|
||||
)
|
||||
dbus_call_with_agent(
|
||||
dbus_c,
|
||||
new_method_call(aprop, "Set", "ssv",
|
||||
("org.bluez.Adapter1", "Pairable", ("b", True))),
|
||||
agent_path,
|
||||
timeout=2.0
|
||||
)
|
||||
dbus_call_with_agent(
|
||||
dbus_c,
|
||||
new_method_call(aprop, "Set", "ssv",
|
||||
("org.bluez.Adapter1", "DiscoverableTimeout", ("u", 60))),
|
||||
agent_path,
|
||||
timeout=2.0
|
||||
)
|
||||
dbus_call_with_agent(
|
||||
dbus_c,
|
||||
new_method_call(aprop, "Set", "ssv",
|
||||
("org.bluez.Adapter1", "Discoverable", ("b", disc_on))),
|
||||
agent_path,
|
||||
timeout=2.0
|
||||
)
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if bt_name:
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
def refresh_dev_props_cache(dbus_c):
|
||||
if dbus_c is None:
|
||||
return
|
||||
try:
|
||||
om_a = DBusAddress("/", bus_name="org.bluez",
|
||||
interface="org.freedesktop.DBus.ObjectManager")
|
||||
rep = dbus_call_with_agent(
|
||||
dbus_c, new_method_call(om_a, "GetManagedObjects"), agent_path, timeout=2.5
|
||||
)
|
||||
if rep is not None and rep.header.message_type == MessageType.method_return and rep.body:
|
||||
objs = rep.body[0]
|
||||
if isinstance(objs, dict):
|
||||
for opath, ifaces in objs.items():
|
||||
if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces:
|
||||
raw = ifaces["org.bluez.Device1"]
|
||||
if isinstance(raw, dict):
|
||||
dev_props_cache[opath] = {
|
||||
k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
|
||||
for k, v in raw.items()
|
||||
}
|
||||
except Exception:
|
||||
pass
|
||||
objs = fetch_managed_objects(conn=dbus_c, agent_path=agent_path, timeout=2.5)
|
||||
if not isinstance(objs, dict):
|
||||
return
|
||||
dev_props_cache.clear()
|
||||
managed_objs.clear()
|
||||
for opath, ifaces in objs.items():
|
||||
if not isinstance(opath, str) or not isinstance(ifaces, dict):
|
||||
continue
|
||||
mentry = {}
|
||||
for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"):
|
||||
raw = ifaces.get(iname)
|
||||
if isinstance(raw, dict):
|
||||
unwrapped = unwrap_props_dict(raw)
|
||||
mentry[iname] = unwrapped
|
||||
if iname == "org.bluez.Device1":
|
||||
dev_props_cache[opath] = dict(unwrapped)
|
||||
if mentry:
|
||||
managed_objs[opath] = mentry
|
||||
write_state_from_cache()
|
||||
|
||||
try:
|
||||
conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
|
||||
dbus_bus = DBusAddress("/org/freedesktop/DBus",
|
||||
bus_name="org.freedesktop.DBus",
|
||||
interface="org.freedesktop.DBus")
|
||||
dbus_send_safe(conn, new_method_call(
|
||||
dbus_bus, "AddMatch", "s",
|
||||
("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",)
|
||||
))
|
||||
dbus_send_safe(conn, new_method_call(
|
||||
dbus_bus, "AddMatch", "s",
|
||||
("type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",)
|
||||
))
|
||||
dbus_send_safe(conn, new_method_call(
|
||||
dbus_bus, "AddMatch", "s",
|
||||
("type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",)
|
||||
))
|
||||
for match_rule in (
|
||||
"type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",
|
||||
"type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Device1'",
|
||||
"type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Adapter1'",
|
||||
"type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.bluez.Battery1'",
|
||||
"type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesAdded'",
|
||||
"type='signal',interface='org.freedesktop.DBus.ObjectManager',member='InterfacesRemoved'",
|
||||
):
|
||||
dbus_send_safe(conn, new_method_call(dbus_bus, "AddMatch", "s", (match_rule,)))
|
||||
for _attempt in range(10):
|
||||
if not running:
|
||||
break
|
||||
@@ -1576,7 +1841,6 @@ def run_daemon():
|
||||
if opp_registered:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
refresh_dev_props_cache(conn)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1584,40 +1848,8 @@ def run_daemon():
|
||||
rfcomm_listener = bind_rfcomm_fallback()
|
||||
|
||||
prepare_bt_controller()
|
||||
|
||||
bt_name = ""
|
||||
try:
|
||||
if os.path.exists("/home/user/.config/sxmo/bt_name"):
|
||||
with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf:
|
||||
bt_name = nf.readline().strip()
|
||||
except OSError:
|
||||
pass
|
||||
if not bt_name:
|
||||
try:
|
||||
bt_name = socket.gethostname().strip()
|
||||
except Exception:
|
||||
bt_name = "Bananarchy"
|
||||
if bt_name:
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
bt_disc = "0"
|
||||
try:
|
||||
if os.path.exists("/home/user/.config/sxmo/bt_discoverable"):
|
||||
with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df:
|
||||
bt_disc = df.readline().strip() or "0"
|
||||
except OSError:
|
||||
pass
|
||||
disc_on = bt_disc.lower() not in ("0", "off", "no", "false")
|
||||
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "pairable-timeout", "0"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "60"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
apply_adapter_settings(conn)
|
||||
refresh_dev_props_cache(conn)
|
||||
|
||||
gp_thread = threading.Thread(target=run_gamepad_uinput_bridge,
|
||||
args=(lambda: running, wake_r), daemon=True)
|
||||
@@ -1664,46 +1896,101 @@ def run_daemon():
|
||||
member = msg.header.fields.get(3)
|
||||
if member == "NameOwnerChanged" and msg.body and len(msg.body) >= 3:
|
||||
name, _old_owner, new_owner = msg.body[0], msg.body[1], msg.body[2]
|
||||
if name == "org.bluez" and new_owner:
|
||||
if name == "org.bluez":
|
||||
dev_props_cache.clear()
|
||||
if rfcomm_listener is not None:
|
||||
try:
|
||||
rfcomm_listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
rfcomm_listener = None
|
||||
opp_registered = register_bluez_services(conn, profile_path, agent_path)
|
||||
if not opp_registered:
|
||||
rfcomm_listener = bind_rfcomm_fallback()
|
||||
refresh_dev_props_cache(conn)
|
||||
managed_objs.clear()
|
||||
if new_owner:
|
||||
if rfcomm_listener is not None:
|
||||
try:
|
||||
rfcomm_listener.close()
|
||||
except OSError:
|
||||
pass
|
||||
rfcomm_listener = None
|
||||
opp_registered = register_bluez_services(conn, profile_path, agent_path)
|
||||
if not opp_registered:
|
||||
rfcomm_listener = bind_rfcomm_fallback()
|
||||
apply_adapter_settings(conn)
|
||||
refresh_dev_props_cache(conn)
|
||||
else:
|
||||
for p in (AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
os.unlink(p)
|
||||
except OSError:
|
||||
pass
|
||||
elif member == "InterfacesAdded" and msg.body and len(msg.body) >= 2:
|
||||
opath, ifaces = msg.body[0], msg.body[1]
|
||||
if isinstance(opath, str) and isinstance(ifaces, dict) and "org.bluez.Device1" in ifaces:
|
||||
raw = ifaces["org.bluez.Device1"]
|
||||
if isinstance(raw, dict):
|
||||
dev_props_cache[opath] = {
|
||||
k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
|
||||
for k, v in raw.items()
|
||||
}
|
||||
if isinstance(opath, str) and isinstance(ifaces, dict):
|
||||
touched = False
|
||||
for iname in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1"):
|
||||
raw = ifaces.get(iname)
|
||||
if isinstance(raw, dict):
|
||||
unwrapped = unwrap_props_dict(raw)
|
||||
managed_objs.setdefault(opath, {})[iname] = unwrapped
|
||||
if iname == "org.bluez.Device1":
|
||||
dev_props_cache[opath] = dict(unwrapped)
|
||||
touched = True
|
||||
if touched:
|
||||
write_state_from_cache()
|
||||
elif member == "InterfacesRemoved" and msg.body and len(msg.body) >= 2:
|
||||
opath, ifaces = msg.body[0], msg.body[1]
|
||||
if isinstance(opath, str) and isinstance(ifaces, (list, tuple)):
|
||||
touched = False
|
||||
entry = managed_objs.get(opath)
|
||||
if isinstance(entry, dict):
|
||||
for iname in ifaces:
|
||||
if iname in entry:
|
||||
entry.pop(iname, None)
|
||||
touched = True
|
||||
if iname == "org.bluez.Device1" and opath in dev_props_cache:
|
||||
dev_props_cache.pop(opath, None)
|
||||
touched = True
|
||||
if not entry:
|
||||
managed_objs.pop(opath, None)
|
||||
if touched:
|
||||
write_state_from_cache()
|
||||
if "org.bluez.Device1" in ifaces or "org.bluez.Battery1" in ifaces:
|
||||
notify_networks_ui()
|
||||
elif member == "PropertiesChanged" and msg.body and len(msg.body) >= 2:
|
||||
obj_path = msg.header.fields.get(1)
|
||||
iface, changed = msg.body[0], msg.body[1]
|
||||
if iface == "org.bluez.Device1" and isinstance(changed, dict):
|
||||
if isinstance(obj_path, str):
|
||||
entry = dev_props_cache.setdefault(obj_path, {})
|
||||
invalidated = msg.body[2] if len(msg.body) >= 3 else ()
|
||||
if (isinstance(obj_path, str) and
|
||||
iface in ("org.bluez.Adapter1", "org.bluez.Device1", "org.bluez.Battery1") and
|
||||
isinstance(changed, dict)):
|
||||
mentry = managed_objs.setdefault(obj_path, {}).setdefault(iface, {})
|
||||
for k, v in changed.items():
|
||||
mentry[k] = unwrap_dbus_variant(v)
|
||||
if isinstance(invalidated, (list, tuple)):
|
||||
for ik in invalidated:
|
||||
mentry.pop(ik, None)
|
||||
if iface == "org.bluez.Device1":
|
||||
dentry = dev_props_cache.setdefault(obj_path, {})
|
||||
for k, v in changed.items():
|
||||
entry[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v
|
||||
if changed.get("Paired"):
|
||||
try:
|
||||
if os.path.exists(PAIR_PROMPT_FILE):
|
||||
with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf:
|
||||
pln = pf.readline()
|
||||
if "\tDISPLAY\t" in pln:
|
||||
clear_pair_prompt_files(notify_cancel=True)
|
||||
except OSError:
|
||||
pass
|
||||
if any(k in changed for k in ("Connected", "Paired", "Bonded")):
|
||||
notify_networks_ui()
|
||||
dentry[k] = unwrap_dbus_variant(v)
|
||||
if isinstance(invalidated, (list, tuple)):
|
||||
for ik in invalidated:
|
||||
dentry.pop(ik, None)
|
||||
if changed.get("Paired"):
|
||||
try:
|
||||
if os.path.exists(PAIR_PROMPT_FILE):
|
||||
with open(PAIR_PROMPT_FILE, "r", encoding="utf-8", errors="replace") as pf:
|
||||
pln = pf.readline()
|
||||
if "\tDISPLAY\t" in pln:
|
||||
clear_pair_prompt_files(notify_cancel=True)
|
||||
except OSError:
|
||||
pass
|
||||
if any(k not in EPHEMERAL_DEV_PROPS for k in changed) or bool(invalidated):
|
||||
write_state_from_cache()
|
||||
if any(k in changed for k in ("Connected", "Paired", "Bonded")):
|
||||
notify_networks_ui()
|
||||
else:
|
||||
write_state_from_cache()
|
||||
if iface == "org.bluez.Battery1" or (
|
||||
iface == "org.bluez.Adapter1" and
|
||||
any(k in changed for k in ("Powered", "Discoverable", "Alias"))
|
||||
):
|
||||
notify_networks_ui()
|
||||
|
||||
if rfcomm_listener is not None:
|
||||
while running:
|
||||
@@ -1742,7 +2029,7 @@ def run_daemon():
|
||||
except OSError:
|
||||
pass
|
||||
clear_pair_prompt_files(notify_cancel=True)
|
||||
for p in (PID_FILE, AGENT_READY_FILE):
|
||||
for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
os.unlink(p)
|
||||
@@ -1973,8 +2260,10 @@ def ensure_daemon_running():
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def prepare_bt_controller():
|
||||
def prepare_bt_controller(force=False):
|
||||
"""Power the adapter and enable LE before DBus Pair/Connect calls."""
|
||||
if not force and os.path.exists(CTRL_READY_FILE) and is_controller_powered_dbus():
|
||||
return
|
||||
try:
|
||||
subprocess.run(["timeout", "3", "bluetoothctl", "power", "on"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
@@ -1991,6 +2280,11 @@ def prepare_bt_controller():
|
||||
stderr=subprocess.DEVNULL, timeout=4)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
ensure_obex_ipc_dir()
|
||||
write_status(CTRL_READY_FILE, "1")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def clear_stale_linkkey(mac):
|
||||
@@ -2274,7 +2568,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
|
||||
if "key-missing" in err_str:
|
||||
dev_mac = dpath.split("dev_")[-1].replace("_", ":")
|
||||
if clear_stale_linkkey(dev_mac):
|
||||
prepare_bt_controller()
|
||||
prepare_bt_controller(force=True)
|
||||
if not use_cli_agent:
|
||||
w_end = time.monotonic() + 2.0
|
||||
while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE):
|
||||
@@ -2333,7 +2627,7 @@ def connect_or_pair_bt_device(mac, dev_name="", do_pair=False):
|
||||
w_end = time.monotonic() + 2.0
|
||||
while time.monotonic() < w_end and not os.path.exists(AGENT_READY_FILE):
|
||||
time.sleep(0.05)
|
||||
prepare_bt_controller()
|
||||
prepare_bt_controller(force=True)
|
||||
trust_device_path(conn_new, dpath)
|
||||
set_hog_preferred_bearer(conn_new, dpath, p)
|
||||
set_audio_preferred_bearer(conn_new, dpath, p)
|
||||
@@ -2479,7 +2773,7 @@ def stop_daemon():
|
||||
except OSError:
|
||||
pass
|
||||
clear_pair_prompt_files(notify_cancel=True)
|
||||
for p in (PID_FILE, AGENT_READY_FILE):
|
||||
for p in (PID_FILE, AGENT_READY_FILE, BT_STATE_FILE, CTRL_READY_FILE):
|
||||
try:
|
||||
if os.path.exists(p):
|
||||
os.unlink(p)
|
||||
@@ -2502,6 +2796,12 @@ def main():
|
||||
elif cmd == "stop":
|
||||
stop_daemon()
|
||||
return 0
|
||||
elif cmd == "dump-state":
|
||||
tsv = dump_bluez_state_tsv()
|
||||
if tsv:
|
||||
sys.stdout.write(tsv)
|
||||
return 0
|
||||
return 1
|
||||
elif cmd in ("connect", "pair"):
|
||||
if len(args) < 2:
|
||||
print(f"Usage: bananarchy-bt-obex {cmd} <MAC> [name]", file=sys.stderr)
|
||||
|
||||
@@ -38,7 +38,7 @@ fi
|
||||
printf '%s\n' \
|
||||
'menu scan' \
|
||||
'transport auto' \
|
||||
'duplicate-data on' \
|
||||
'duplicate-data off' \
|
||||
'back' \
|
||||
'power on'
|
||||
sleep 1
|
||||
|
||||
@@ -25,8 +25,6 @@ on() {
|
||||
if [ -s /etc/bananarchy/bt_mac ] && [ -x /usr/bin/bananarchy-engmenu-ctl ]; then
|
||||
/usr/bin/bananarchy-engmenu-ctl apply-boot >/dev/null 2>&1 || true
|
||||
fi
|
||||
/usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true
|
||||
timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true
|
||||
timeout 2 bluetoothctl power on >/dev/null 2>&1 || true
|
||||
/usr/bin/bananarchy-bt-le-enable.sh >/dev/null 2>&1 || true
|
||||
timeout 2 /usr/bin/btmgmt -i hci0 class 2 3 >/dev/null 2>&1 || true
|
||||
@@ -63,6 +61,8 @@ on() {
|
||||
|
||||
off() {
|
||||
/usr/bin/bananarchy-bt-obex stop >/dev/null 2>&1 || true
|
||||
timeout 2 bluetoothctl disconnect >/dev/null 2>&1 || true
|
||||
timeout 2 /usr/bin/btmgmt -i hci0 power off >/dev/null 2>&1 || true
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl stop bluetooth
|
||||
systemctl disable bluetooth
|
||||
@@ -70,7 +70,12 @@ off() {
|
||||
rc-service bluetooth stop
|
||||
rc-update del bluetooth
|
||||
fi
|
||||
btpid="$(pidof -s bluetoothd 2>/dev/null || true)"
|
||||
if [ -n "$btpid" ]; then
|
||||
kill -KILL $(pidof bluetoothd) 2>/dev/null || true
|
||||
fi
|
||||
rfkill block bluetooth
|
||||
rm -f /run/bananarchy/bt-obex/ctrl_ready /run/bananarchy/bt-obex/bt_state.tsv 2>/dev/null || true
|
||||
}
|
||||
|
||||
case "${1:-toggle}" in
|
||||
|
||||
Binary file not shown.
Reference in new issue
Block a user