bluetooth: fix BLE/HID keyboard & mouse pairing, auto-bypass T9 on external keyboard, and show mouse cursor

This commit is contained in:
Luxferre committed 2026-11-03 20:24:54 +02:00
1 parent b9e7c6847b
commit 02ce3ab1f4
67 files changed
+1227 -293

No files matched your search

Binary file not shown.
+470 -42
View File
@@ -327,6 +327,7 @@ def run_gamepad_uinput_bridge(is_running):
uinput_fd = None
gamepads = {} # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}}
last_scan = 0.0
last_input_mtime = 0
def ensure_uinput():
nonlocal uinput_fd
@@ -386,6 +387,16 @@ def run_gamepad_uinput_bridge(is_running):
now = time.monotonic()
if now - last_scan >= 2.0:
last_scan = now
try:
st_in = os.stat("/dev/input")
if last_input_mtime != 0 and st_in.st_mtime_ns != last_input_mtime:
subprocess.Popen(
["sh", "-c", "DISPLAY=:0 xsetroot -name \"$(cat /tmp/sxmo_status_bar 2>/dev/null || printf 'Bananarchy')\" >/dev/null 2>&1 || sxmo_hook_statusbar.sh >/dev/null 2>&1"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
last_input_mtime = st_in.st_mtime_ns
except OSError:
pass
try:
for entry in os.listdir("/dev/input"):
if not entry.startswith("event"):
@@ -406,7 +417,8 @@ def run_gamepad_uinput_bridge(is_running):
buf = bytearray(96)
fcntl.ioctl(fd, eviocgbit_key, buf, True)
has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1)
if has_gamepad:
has_qwerty = bool((buf[16 // 8] >> (16 % 8)) & 1) and bool((buf[30 // 8] >> (30 % 8)) & 1)
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": {}
@@ -522,6 +534,137 @@ def run_gamepad_uinput_bridge(is_running):
pass
def trust_device_path(conn, dev_path):
if not isinstance(dev_path, str) or not dev_path.startswith("/org/bluez/"):
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", "Trusted", ("b", True))))
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:
return False
path = msg.header.fields.get(1)
member = msg.header.fields.get(3)
if path != agent_path:
return False
dev_path = msg.body[0] if (msg.body and len(msg.body) > 0) else None
if member in ("RequestConfirmation", "RequestAuthorization", "AuthorizeService"):
conn.send(new_method_return(msg))
trust_device_path(conn, dev_path)
notify_networks_ui()
return True
if member == "RequestPinCode":
conn.send(new_method_return(msg, "s", ("0000",)))
trust_device_path(conn, dev_path)
notify_networks_ui()
return True
if member == "RequestPasskey":
conn.send(new_method_return(msg, "u", (0,)))
trust_device_path(conn, dev_path)
notify_networks_ui()
return True
if member in ("DisplayPinCode", "DisplayPasskey"):
conn.send(new_method_return(msg))
trust_device_path(conn, dev_path)
notify_networks_ui()
return True
if member in ("Cancel", "Release"):
conn.send(new_method_return(msg))
return True
conn.send(new_method_return(msg))
return True
def dbus_call_with_agent(conn, call_msg, agent_path, timeout=5.0):
from jeepney import HeaderFields, MessageType
serial = next(conn.outgoing_serial)
conn.send(call_msg, serial=serial)
deadline = time.time() + timeout
while time.time() < deadline:
rem = max(0.05, deadline - time.time())
try:
msg = conn.receive(timeout=rem)
except TimeoutError:
return None
if msg is None:
continue
if handle_agent_method_call(conn, msg, agent_path):
continue
if msg.header.message_type in (MessageType.method_return, MessageType.error):
if msg.header.fields.get(HeaderFields.reply_serial, -1) == serial:
return msg
return None
def register_bluez_services(conn, profile_path, agent_path):
from jeepney import DBusAddress, 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))),
agent_path,
timeout=2.0
)
dbus_call_with_agent(
conn,
new_method_call(aprop, "Set", "ssv",
("org.bluez.Adapter1", "Pairable", ("b", True))),
agent_path,
timeout=2.0
)
except Exception:
pass
try:
am = DBusAddress("/org/bluez", bus_name="org.bluez",
interface="org.bluez.AgentManager1")
dbus_call_with_agent(
conn,
new_method_call(am, "RegisterAgent", "os",
(agent_path, "NoInputNoOutput")),
agent_path,
timeout=3.0
)
dbus_call_with_agent(
conn,
new_method_call(am, "RequestDefaultAgent", "o", (agent_path,)),
agent_path,
timeout=3.0
)
except Exception:
pass
try:
pm = DBusAddress("/org/bluez", bus_name="org.bluez",
interface="org.bluez.ProfileManager1")
opts = {
"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
)
except Exception:
pass
def run_daemon():
from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
from jeepney.io.blocking import open_dbus_connection
@@ -578,22 +721,22 @@ def run_daemon():
gp_thread.start()
profile_path = "/org/bananarchy/obex_opp"
agent_path = "/org/bananarchy/bt_agent"
conn = None
try:
conn = open_dbus_connection(bus="SYSTEM", enable_fds=True)
pm = DBusAddress("/org/bluez", bus_name="org.bluez",
interface="org.bluez.ProfileManager1")
opts = {
"Name": ("s", "OBEX Object Push"),
"Role": ("s", "server"),
"Channel": ("q", 9),
"RequireAuthentication": ("b", False),
"RequireAuthorization": ("b", False),
"AutoConnect": ("b", True),
}
reg_msg = new_method_call(pm, "RegisterProfile", "osa{sv}",
(profile_path, OPP_UUID, opts))
conn.send_and_get_reply(reg_msg, timeout=5.0)
dbus_bus = DBusAddress("/org/freedesktop/DBus",
bus_name="org.freedesktop.DBus",
interface="org.freedesktop.DBus")
conn.send(new_method_call(
dbus_bus, "AddMatch", "s",
("type='signal',sender='org.freedesktop.DBus',member='NameOwnerChanged',arg0='org.bluez'",)
))
conn.send(new_method_call(
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)
except Exception:
pass
@@ -617,23 +760,37 @@ def run_daemon():
msg = conn.receive(timeout=1.0)
except TimeoutError:
msg = None
if msg is not None and msg.header.message_type == MessageType.method_call:
member = msg.header.fields.get(3) # Member name
path = msg.header.fields.get(1) # Object path
if path == profile_path and member == "NewConnection":
# Args: (o device, h fd, a{sv} fd_properties)
dev_path, fd_obj, _props = msg.body
reply = new_method_return(msg)
conn.send(reply)
raw_fd = os.dup(fd_obj.fileno())
fd_obj.close()
client_sock = socket.socket(fileno=raw_fd)
t = threading.Thread(target=handle_obex_rx_session,
args=(client_sock,), daemon=True)
t.start()
elif path == profile_path and member in ("RequestDisconnection", "Release"):
reply = new_method_return(msg)
conn.send(reply)
if msg is not None:
if handle_agent_method_call(conn, msg, agent_path):
pass
elif msg.header.message_type == MessageType.method_call:
member = msg.header.fields.get(3) # Member name
path = msg.header.fields.get(1) # Object path
if path == profile_path and member == "NewConnection":
# Args: (o device, h fd, a{sv} fd_properties)
dev_path, fd_obj, _props = msg.body
reply = new_method_return(msg)
conn.send(reply)
raw_fd = os.dup(fd_obj.fileno())
fd_obj.close()
client_sock = socket.socket(fileno=raw_fd)
t = threading.Thread(target=handle_obex_rx_session,
args=(client_sock,), daemon=True)
t.start()
elif path == profile_path and member in ("RequestDisconnection", "Release"):
reply = new_method_return(msg)
conn.send(reply)
elif msg.header.message_type == MessageType.signal:
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:
register_bluez_services(conn, profile_path, agent_path)
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):
if any(k in changed for k in ("Connected", "Paired", "Bonded")):
notify_networks_ui()
else:
time.sleep(1.0)
@@ -831,6 +988,275 @@ def send_file_obex(mac, filepath):
pass
def ensure_daemon_running():
if os.path.exists(PID_FILE):
try:
with open(PID_FILE, "r", encoding="utf-8") as f:
pid = int(f.read().strip())
os.kill(pid, 0)
return
except Exception:
pass
try:
subprocess.Popen([sys.executable, __file__, "daemon"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
time.sleep(0.25)
except Exception:
pass
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
ensure_daemon_running()
mac = mac.strip().upper()
if not mac:
return 1
dev_path = "/org/bluez/hci0/dev_" + mac.replace(":", "_")
orig_path = dev_path
cli_agent_path = f"/org/bananarchy/bt_cli_agent_{os.getpid()}"
adapter_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
interface="org.bluez.Adapter1")
am_addr = DBusAddress("/org/bluez", bus_name="org.bluez",
interface="org.bluez.AgentManager1")
om_addr = DBusAddress("/", bus_name="org.bluez",
interface="org.freedesktop.DBus.ObjectManager")
conn = None
try:
conn = open_dbus_connection(bus="SYSTEM")
aprop_addr = DBusAddress("/org/bluez/hci0", bus_name="org.bluez",
interface="org.freedesktop.DBus.Properties")
dbus_call_with_agent(
conn,
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_method_call(am_addr, "RegisterAgent", "os",
(cli_agent_path, "NoInputNoOutput")),
cli_agent_path,
timeout=2.5
)
dbus_call_with_agent(
conn,
new_method_call(am_addr, "RequestDefaultAgent", "o", (cli_agent_path,)),
cli_agent_path,
timeout=2.5
)
def pump_agent(duration):
end_t = time.time() + duration
while time.time() < end_t:
rem = max(0.05, min(0.25, end_t - time.time()))
try:
m = conn.receive(timeout=rem)
if m is not None:
handle_agent_method_call(conn, m, cli_agent_path)
except TimeoutError:
pass
def get_dev_props(dpath):
prop_addr = DBusAddress(dpath, 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",)),
cli_agent_path,
timeout=2.5
)
if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
return None
raw = rep.body[0]
if not isinstance(raw, dict):
return None
out = {}
for k, v in raw.items():
out[k] = v[1] if (isinstance(v, (tuple, list)) and len(v) == 2) else v
return out
def find_matching_device(target_name, prefer_path=None):
if not target_name:
return None
t_low = target_name.strip().lower()
rep = dbus_call_with_agent(
conn,
new_method_call(om_addr, "GetManagedObjects"),
cli_agent_path,
timeout=3.0
)
if rep is None or rep.header.message_type != MessageType.method_return or not rep.body:
return None
objs = rep.body[0]
if not isinstance(objs, dict):
return None
candidates = []
for opath, ifaces in objs.items():
if not isinstance(opath, str) or not opath.startswith("/org/bluez/hci0/dev_"):
continue
dprops_raw = ifaces.get("org.bluez.Device1") if isinstance(ifaces, dict) else None
if not isinstance(dprops_raw, dict):
continue
dprops = {
k: (v[1] if isinstance(v, (tuple, list)) and len(v) == 2 else v)
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
if dprops.get("Connected"):
score += 100
if "RSSI" in dprops and dprops.get("RSSI") is not None:
score += 50
if opath == prefer_path:
score += 10
candidates.append((score, opath))
if not candidates:
return None
candidates.sort(key=lambda x: x[0], reverse=True)
return candidates[0][1]
def wait_for_bond_if_connected(dpath, max_wait=3.5):
deadline = time.time() + max_wait
while time.time() < deadline:
pump_agent(0.25)
p = get_dev_props(dpath)
if not p or not p.get("Connected"):
break
if p.get("Paired") or p.get("Bonded"):
return p
return get_dev_props(dpath)
def cancel_pending_connect(dpath):
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
)
def attempt_connect_path(dpath, want_pair):
trust_device_path(conn, dpath)
p = get_dev_props(dpath)
if p is None:
return False
if p.get("Connected"):
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
dev_addr = DBusAddress(dpath, bus_name="org.bluez",
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
)
if rep is None:
cancel_pending_connect(dpath)
p = get_dev_props(dpath) or {}
if not p.get("Connected"):
rep = dbus_call_with_agent(
conn, new_method_call(dev_addr, "Connect"), cli_agent_path, timeout=8.0
)
if rep is None:
cancel_pending_connect(dpath)
p = get_dev_props(dpath) or {}
if p.get("Connected") and not (p.get("Paired") or p.get("Bonded")):
p = wait_for_bond_if_connected(dpath, 4.0) or p
if p.get("Connected"):
return True
if want_pair and (p.get("Paired") or p.get("Bonded")):
return True
return 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
)
scan_start = time.time()
scan_deadline = scan_start + max_scan
discovered_path = prefer_path
while time.time() < scan_deadline:
pump_agent(0.35)
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)):
discovered_path = prefer_path
break
if dev_name:
alt = find_matching_device(dev_name, prefer_path=prefer_path)
if alt:
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)
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
)
pump_agent(0.15)
return discovered_path
props = get_dev_props(dev_path)
orig_unbonded = (props is None) or (not props.get("Paired") and not props.get("Bonded"))
if props and not dev_name:
dev_name = str(props.get("Name") or props.get("Alias") or "").strip()
if props is None and dev_name:
alt = find_matching_device(dev_name)
if alt:
dev_path = alt
props = get_dev_props(dev_path)
trust_device_path(conn, 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)
ok = attempt_connect_path(dev_path, do_pair)
if not ok:
discovered_path = scan_for_device(dev_path, max_scan=15.0)
ok = attempt_connect_path(discovered_path, do_pair)
if ok and discovered_path != orig_path and orig_unbonded:
dbus_call_with_agent(
conn,
new_method_call(adapter_addr, "RemoveDevice", "o", (orig_path,)),
cli_agent_path,
timeout=2.0
)
notify_networks_ui()
return 0 if ok else 1
except Exception:
return 1
finally:
if conn is not None:
try:
dbus_call_with_agent(
conn,
new_method_call(am_addr, "UnregisterAgent", "o", (cli_agent_path,)),
cli_agent_path,
timeout=1.5
)
except Exception:
pass
try:
conn.close()
except Exception:
pass
def stop_daemon():
if os.path.exists(PID_FILE):
try:
@@ -852,21 +1278,23 @@ def main():
if cmd == "daemon":
run_daemon()
elif cmd == "start":
if os.path.exists(PID_FILE):
try:
with open(PID_FILE, "r", encoding="utf-8") as f:
pid = int(f.read().strip())
os.kill(pid, 0)
return 0
except Exception:
pass
subprocess.Popen([sys.executable, __file__, "daemon"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
start_new_session=True)
ensure_daemon_running()
return 0
elif cmd == "stop":
stop_daemon()
return 0
elif cmd == "connect":
if len(sys.argv) < 3:
print("Usage: bananarchy-bt-obex connect <MAC> [name]", file=sys.stderr)
return 1
nm = sys.argv[3] if len(sys.argv) >= 4 else ""
return connect_or_pair_bt_device(sys.argv[2], nm, do_pair=False)
elif cmd == "pair":
if len(sys.argv) < 3:
print("Usage: bananarchy-bt-obex pair <MAC> [name]", file=sys.stderr)
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 == "send":
if len(sys.argv) < 4:
print("Usage: bananarchy-bt-obex send <MAC> <filepath>", file=sys.stderr)
Binary file not shown.
Binary file not shown.
@@ -10,7 +10,9 @@ fi
on() {
rfkill unblock bluetooth
modprobe -q uhid hidp uinput rfcomm bnep xpad 2>/dev/null || true
modprobe -q uhid hidp uinput rfcomm bnep xpad af_alg algif_hash algif_skcipher algif_rng algif_aead 2>/dev/null || true
chgrp input /dev/uinput 2>/dev/null || true
chmod 0660 /dev/uinput 2>/dev/null || true
if [ -d /run/systemd/system ]; then
systemctl start bluetooth
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.