#!/usr/bin/env python3 """One-shot BlueZ calls with structured errors; no pairing agent or discovery lease.""" import json import re import sys ADAPTER = re.compile(r'/org/bluez/hci[0-9]+') DEVICE = re.compile(r'/org/bluez/hci[0-9]+/dev_(?:[0-9A-Fa-f]{2}_){5}[0-9A-Fa-f]{2}') class Bluez: def __init__(self): from gi.repository import Gio, GLib self.Gio, self.GLib = Gio, GLib self.bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) def call(self, path, interface, method, signature=None, args=(), timeout=45000): params = self.GLib.Variant(signature, args) if signature else None return self.bus.call_sync('org.bluez', path, interface, method, params, None, self.Gio.DBusCallFlags.NO_AUTO_START, timeout, None).unpack() def status(self): objects = self.call('/', 'org.freedesktop.DBus.ObjectManager', 'GetManagedObjects', timeout=5000)[0] return {'adapterCount': sum('org.bluez.Adapter1' in interfaces for interfaces in objects.values())} def power(self, path, enabled): self.call(path, 'org.freedesktop.DBus.Properties', 'Set', '(ssv)', ('org.bluez.Adapter1', 'Powered', self.GLib.Variant('b', enabled))) def discover(self, path): import signal loop = self.GLib.MainLoop() # GLib delivers these signals without polling while the lease is held. self.GLib.unix_signal_add(self.GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (loop.quit(), False)[1]) self.GLib.timeout_add_seconds(60, lambda: (loop.quit(), False)[1]) started = False try: self.call(path, 'org.bluez.Adapter1', 'StartDiscovery', timeout=5000) started = True print(json.dumps({'ok': True, 'event': 'started'}), flush=True) loop.run() finally: if started: self.call(path, 'org.bluez.Adapter1', 'StopDiscovery', timeout=5000) def connect(self, path): self.call(path, 'org.bluez.Device1', 'Connect') def disconnect(self, path): self.call(path, 'org.bluez.Device1', 'Disconnect') def forget(self, path): self.call(path.rsplit('/', 1)[0], 'org.bluez.Adapter1', 'RemoveDevice', '(o)', (path,)) def execute(action, path='', factory=Bluez): if action == 'status': if path: raise ValueError('status does not accept a device path') return factory().status() if action == 'discover': if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path') factory().discover(path) elif action in {'power-on', 'power-off'}: if not ADAPTER.fullmatch(path): raise ValueError('Invalid BlueZ adapter path') factory().power(path, action == 'power-on') elif action in {'connect', 'disconnect', 'forget'}: if not DEVICE.fullmatch(path): raise ValueError('Invalid BlueZ device path') getattr(factory(), action)(path) else: raise ValueError('Unsupported Bluetooth action') return {} def main(): try: if len(sys.argv) not in {2, 3}: raise ValueError('Expected action and optional BlueZ path') result = execute(sys.argv[1], sys.argv[2] if len(sys.argv) == 3 else '') print(json.dumps({'ok': True, **result})) return 0 except Exception as error: print(json.dumps({'ok': False, 'error': str(error)})) return 1 if __name__ == '__main__': sys.exit(main())