Add Bluetooth audio/HID/discoverability/alias support, fix SD card hotplug & caller ID matching, and expand ReMEdy J2ME JSRs + 64MB GC

This commit is contained in:
Luxferre committed 2026-11-01 16:18:04 +02:00
1 parent 456d3fbc42
commit 471916424e
51 files changed
+2961 -305

No files matched your search

+278 -6
View File
@@ -5,6 +5,8 @@
import os
import sys
import time
import fcntl
import select
import struct
import socket
import signal
@@ -60,15 +62,24 @@ def notify_networks_ui():
def notify_user(title, body):
try:
bus_addr = "unix:path=/run/user/10000/bus"
if os.path.exists("/run/user/10000/dbus.bus"):
try:
with open("/run/user/10000/dbus.bus", "r", encoding="utf-8") as bf:
line = bf.readline().strip()
if line:
bus_addr = line
except OSError:
pass
if os.geteuid() == 0:
subprocess.Popen([
"su", "-", "user", "-c",
f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/10000/bus notify-send { subprocess.list2cmdline([title, body]) }"
f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS={subprocess.list2cmdline([bus_addr])} notify-send {subprocess.list2cmdline([title, body])}"
], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
env = os.environ.copy()
env.setdefault("DISPLAY", ":0")
env.setdefault("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/10000/bus")
env.setdefault("DBUS_SESSION_BUS_ADDRESS", bus_addr)
subprocess.Popen(["notify-send", title, body],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception:
@@ -278,6 +289,239 @@ def handle_obex_rx_session(sock):
pass
def run_gamepad_uinput_bridge(is_running):
ev_fmt = "llHHi"
ev_size = struct.calcsize(ev_fmt)
ui_set_evbit = 0x40045564
ui_set_keybit = 0x40045565
ui_dev_create = 0x5501
ui_dev_destroy = 0x5502
eviocgbit_key = (2 << 30) | (96 << 16) | (0x45 << 8) | (0x20 + 0x01)
# Map Linux gamepad button codes to Bananarchy keypad/navigation keys:
# South(A)=Enter(OK), East(B)=8(GB B), West(X)=5(Fire/Turbo B), North(Y)=6(Turbo A)
# Start=2(GB Start), Select=3(GB Select), L1=F1(LSK), R1=F2(RSK), L2=*, R2=0, Mode=Esc
btn_map = {
0x130: 28, # BTN_SOUTH (A) -> KEY_ENTER
0x131: 9, # BTN_EAST (B) -> KEY_8
0x132: 8, # BTN_C -> KEY_7
0x133: 6, # BTN_WEST (X) -> KEY_5
0x134: 7, # BTN_NORTH (Y) -> KEY_6
0x135: 10, # BTN_Z -> KEY_9
0x136: 59, # BTN_TL (L1) -> KEY_F1 (Left Softkey)
0x137: 60, # BTN_TR (R1) -> KEY_F2 (Right Softkey)
0x138: 55, # BTN_TL2 (L2) -> KEY_KPASTERISK (*)
0x139: 11, # BTN_TR2 (R2) -> KEY_0
0x13a: 4, # BTN_SELECT -> KEY_3
0x13b: 3, # BTN_START -> KEY_2
0x13c: 1, # BTN_MODE -> KEY_ESC
0x120: 28, # BTN_TRIGGER -> KEY_ENTER
0x121: 9, # BTN_THUMB -> KEY_8
0x220: 103, # BTN_DPAD_UP -> KEY_UP
0x221: 108, # BTN_DPAD_DOWN -> KEY_DOWN
0x222: 105, # BTN_DPAD_LEFT -> KEY_LEFT
0x223: 106, # BTN_DPAD_RIGHT -> KEY_RIGHT
}
all_keys = sorted(set(btn_map.values()) | {103, 108, 105, 106})
uinput_fd = None
gamepads = {} # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}}
last_scan = 0.0
def ensure_uinput():
nonlocal uinput_fd
if uinput_fd is not None:
return True
try:
subprocess.run(["modprobe", "-q", "uinput"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)
fcntl.ioctl(fd, ui_set_evbit, 0x00) # EV_SYN
fcntl.ioctl(fd, ui_set_evbit, 0x01) # EV_KEY
for k in all_keys:
fcntl.ioctl(fd, ui_set_keybit, k)
name = b"Bananarchy BT Gamepad Bridge"
udev = struct.pack("80sHHHHi", name, 0x06, 0x1209, 0x8110, 1, 0) + (b"\x00" * (64 * 4 * 4))
os.write(fd, udev)
fcntl.ioctl(fd, ui_dev_create)
uinput_fd = fd
return True
except Exception:
return False
def emit_key(code, val):
if uinput_fd is None and not ensure_uinput():
return
try:
os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x01, code, val))
os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x00, 0, 0))
except OSError:
pass
def get_axis_dir(fd, axis, val, cache):
if axis not in cache:
try:
ioc = (2 << 30) | (24 << 16) | (0x45 << 8) | (0x40 + axis)
buf = fcntl.ioctl(fd, ioc, b"\x00" * 24)
_v, min_v, max_v, _fz, _fl, _rs = struct.unpack("6i", buf)
if max_v > min_v:
cache[axis] = (min_v, max_v)
else:
cache[axis] = (-32768, 32767)
except Exception:
cache[axis] = (-32768, 32767)
min_v, max_v = cache[axis]
mid = (min_v + max_v) / 2.0
span = (max_v - min_v) / 2.0
if span <= 0:
return 0
norm = (val - mid) / span
if norm < -0.40:
return -1
if norm > 0.40:
return 1
return 0
while is_running():
now = time.monotonic()
if now - last_scan >= 2.0:
last_scan = now
try:
for entry in os.listdir("/dev/input"):
if not entry.startswith("event"):
continue
dev_path = f"/dev/input/{entry}"
if dev_path in gamepads:
continue
sys_name_path = f"/sys/class/input/{entry}/device/name"
try:
with open(sys_name_path, "r", encoding="utf-8") as nf:
dname = nf.read().strip()
if "Bananarchy BT Gamepad Bridge" in dname:
continue
except OSError:
pass
try:
fd = os.open(dev_path, os.O_RDONLY | os.O_NONBLOCK)
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:
ensure_uinput()
gamepads[dev_path] = {
"fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}
}
else:
os.close(fd)
except Exception:
pass
except OSError:
pass
if not gamepads:
time.sleep(1.5)
continue
fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())}
try:
rlist, _, _ = select.select(list(fd_map.keys()), [], [], 1.0)
except Exception:
time.sleep(0.5)
continue
for rfd in rlist:
path, info = fd_map.get(rfd, (None, None))
if not path:
continue
try:
data = os.read(rfd, ev_size * 16)
if not data:
raise OSError("EOF")
except OSError:
try:
os.close(rfd)
except OSError:
pass
gamepads.pop(path, 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_code in btn_map:
if ev_val in (0, 1, 2):
emit_key(btn_map[ev_code], ev_val)
elif ev_type == 0x03:
if ev_code == 0x10: # ABS_HAT0X
new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
old_dir = info["hat_x"]
if new_dir != old_dir:
if old_dir == -1:
emit_key(105, 0)
elif old_dir == 1:
emit_key(106, 0)
if new_dir == -1:
emit_key(105, 1)
elif new_dir == 1:
emit_key(106, 1)
info["hat_x"] = new_dir
elif ev_code == 0x11: # ABS_HAT0Y
new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0)
old_dir = info["hat_y"]
if new_dir != old_dir:
if old_dir == -1:
emit_key(103, 0)
elif old_dir == 1:
emit_key(108, 0)
if new_dir == -1:
emit_key(103, 1)
elif new_dir == 1:
emit_key(108, 1)
info["hat_y"] = new_dir
elif ev_code == 0x00: # ABS_X (Left Stick X)
new_dir = get_axis_dir(rfd, 0x00, ev_val, info["ax"])
old_dir = info["lx"]
if new_dir != old_dir:
if old_dir == -1:
emit_key(105, 0)
elif old_dir == 1:
emit_key(106, 0)
if new_dir == -1:
emit_key(105, 1)
elif new_dir == 1:
emit_key(106, 1)
info["lx"] = new_dir
elif ev_code == 0x01: # ABS_Y (Left Stick Y)
new_dir = get_axis_dir(rfd, 0x01, ev_val, info["ax"])
old_dir = info["ly"]
if new_dir != old_dir:
if old_dir == -1:
emit_key(103, 0)
elif old_dir == 1:
emit_key(108, 0)
if new_dir == -1:
emit_key(103, 1)
elif new_dir == 1:
emit_key(108, 1)
info["ly"] = new_dir
for info in gamepads.values():
try:
os.close(info["fd"])
except OSError:
pass
if uinput_fd is not None:
try:
fcntl.ioctl(uinput_fd, ui_dev_destroy)
except Exception:
pass
try:
os.close(uinput_fd)
except OSError:
pass
def run_daemon():
from jeepney import DBusAddress, new_method_call, new_method_return, MessageType
from jeepney.io.blocking import open_dbus_connection
@@ -297,14 +541,42 @@ def run_daemon():
signal.signal(signal.SIGTERM, stop_handler)
signal.signal(signal.SIGINT, stop_handler)
# Make adapter discoverable and pairable when Bluetooth is ON so senders can see the phone
subprocess.run(["bluetoothctl", "discoverable-timeout", "0"],
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 = "1"
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"
except OSError:
pass
disc_on = bt_disc.lower() not in ("0", "off", "no", "false")
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "0"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["bluetoothctl", "discoverable", "on"],
subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
subprocess.run(["bluetoothctl", "pairable", "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,), daemon=True)
gp_thread.start()
profile_path = "/org/bananarchy/obex_opp"
conn = None
try: