async def init(self, use_system_bus=False): """Asyncio initialization Initialize connection to the bus Args: use_system_bus (bool) True to connect to system bus """ bus_type = BusType.SYSTEM if use_system_bus else BusType.SESSION self.bus = MessageBus(bus_type=bus_type) await self.bus.connect() return self
async def component_init(self) -> None: try: self.bus = MessageBus(bus_type=BusType.SYSTEM) await self.bus.connect() except Exception: logging.info("Unable to Connect to D-Bus") return # Make sure that all required actions are register try: self.polkit = await self.get_interface( "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority") except self.DbusError: self.server.add_warning("Unable to find DBus PolicyKit Interface")
class DbusSystemd(): """Base class containing common definitions and methods""" # The typical path of systemd service on system DBUS DBUS_SERVICE_SYSTEMD = 'org.freedesktop.systemd1' def __init__(self): self.bus = None async def init(self, use_system_bus=False): """Asyncio initialization Initialize connection to the bus Args: use_system_bus (bool) True to connect to system bus """ bus_type = BusType.SYSTEM if use_system_bus else BusType.SESSION self.bus = MessageBus(bus_type=bus_type) await self.bus.connect() return self async def get_object(self, obj_path): """Get an object from systemd dbus service""" introspection = await self.bus.introspect(self.DBUS_SERVICE_SYSTEMD, obj_path) # Select systemd service object return self.bus.get_proxy_object(self.DBUS_SERVICE_SYSTEMD, obj_path, introspection)
async def main(): async with MessageBus(bus_type=bus_type).connect() as bus: message = Message(destination=destination, member=member, interface=interface, path=object_path, signature=signature, body=body) result = await bus.call(message) ret = 0 if result.message_type is MessageType.ERROR: print(f'Error: {result.error_name}', file=sys.stderr) ret = 1 def default(o): if type(o) is Variant: return [o.signature, o.value] else: raise json.JSONDecodeError() print(json.dumps(result.body, indent=2, default=default)) sys.exit(ret)
async def main(): async with MessageBus().connect() as bus: # the introspection xml would normally be included in your project, but # this is convenient for development introspection = await bus.introspect('org.mpris.MediaPlayer2.vlc', '/org/mpris/MediaPlayer2') obj = bus.get_proxy_object('org.mpris.MediaPlayer2.vlc', '/org/mpris/MediaPlayer2', introspection) player = obj.get_interface('org.mpris.MediaPlayer2.Player') properties = obj.get_interface('org.freedesktop.DBus.Properties') # call methods on the interface (this causes the media player to play) await player.call_play() volume = await player.get_volume() print(f'current volume: {volume}, setting to 0.5') await player.set_volume(0.5) # listen to signals def on_properties_changed(interface_name, changed_properties, invalidated_properties): for changed, variant in changed_properties.items(): print(f'property changed: {changed} - {variant.value}') properties.on_properties_changed(on_properties_changed) await bus.wait_for_disconnect()
async def test_connection_via_tcp(): server = await asyncio.start_server(None, '127.0.0.1', 55556) bus = MessageBus(bus_address="tcp:host=127.0.0.1,port=55556") assert bus._sock.getpeername()[0] == '127.0.0.1' assert bus._sock.getsockname()[0] == '127.0.0.1' assert bus._sock.gettimeout() == 0 assert bus._stream.closed is False server.close()
async def main(): async with MessageBus( bus_address="tcp:host=127.0.0.1,port=55556").connect() as bus: introspection = await bus.introspect('org.freedesktop.Notifications', '/org/freedesktop/Notifications') obj = bus.get_proxy_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications', introspection) notification = obj.get_interface('org.freedesktop.Notifications') await notification.call_notify("test.py", 0, "", "DBus Test", "Test notification", [""], dict(), 5000)
async def main(): bus = MessageBus() #bus_type=BusType.SYSTEM) await bus.connect() workers = [ # empty future to make sure we will wait forever asyncio.get_event_loop().create_future(), ] bus.export('/org/gnome/Shell/Screenshot', ScreenshotInterface()) idle = IdleTime() await idle.start() if idle.worker: workers.append(idle.worker) bus.export('/org/gnome/Mutter/IdleMonitor/Core', idle) # Now we are ready to handle messages! await bus.request_name('org.gnome.Shell.Screenshot') if idle.worker: await bus.request_name('org.gnome.Mutter.IdleMonitor') print('Started!') # run forever (FIXME is it a good way?) #await asyncio.get_event_loop().create_future() await asyncio.gather(*workers)
async def main(): async with MessageBus().connect() as bus: reply = await bus.call( Message(destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus', member='ListNames')) if reply.message_type == MessageType.ERROR: raise Exception(reply.body[0]) print(json.dumps(reply.body[0], indent=2))
async def test_bus_disconnect_before_reply(event_loop): '''In this test, the bus disconnects before the reply comes in. Make sure the caller receives a reply with the error instead of hanging.''' bus = MessageBus() assert not bus.connected await bus.connect() assert bus.connected ping = bus.call( Message(destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus', member='Ping')) event_loop.call_soon(bus.disconnect) with pytest.raises((EOFError, BrokenPipeError)): await ping assert bus._disconnected assert not bus.connected assert (await bus.wait_for_disconnect()) is None
async def test_unexpected_disconnect(event_loop): bus = MessageBus() assert not bus.connected await bus.connect() assert bus.connected ping = bus.call( Message(destination='org.freedesktop.DBus', path='/org/freedesktop/DBus', interface='org.freedesktop.DBus', member='Ping')) event_loop.call_soon(functools.partial(os.close, bus._fd)) with pytest.raises(OSError): await ping assert bus._disconnected assert not bus.connected with pytest.raises(OSError): await bus.wait_for_disconnect()
class DbusManager: Variant = dbus_next.Variant DbusError = dbus_next.errors.DBusError def __init__(self, config: ConfigHelper) -> None: self.server = config.get_server() self.bus: Optional[MessageBus] = None self.polkit: Optional[ProxyInterface] = None self.warned: bool = False proc_data = pathlib.Path(f"/proc/self/stat").read_text() start_clk_ticks = int(proc_data.split()[21]) self.polkit_subject = [ "unix-process", { "pid": dbus_next.Variant("u", os.getpid()), "start-time": dbus_next.Variant("t", start_clk_ticks) } ] def is_connected(self) -> bool: return self.bus is not None and self.bus.connected async def component_init(self) -> None: try: self.bus = MessageBus(bus_type=BusType.SYSTEM) await self.bus.connect() except Exception: logging.info("Unable to Connect to D-Bus") return # Make sure that all required actions are register try: self.polkit = await self.get_interface( "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority") except self.DbusError: self.server.add_warning("Unable to find DBus PolicyKit Interface") async def check_permission(self, action: str, err_msg: str = "") -> bool: if self.polkit is None: return False try: ret = await self.polkit.call_check_authorization( # type: ignore self.polkit_subject, action, {}, 0, "") except Exception as e: self.server.add_warning( f"Error checking authorization for action [{action}]: {e}" ", This may indicate that PolicyKit is not installed, " f"{err_msg}") return False if not ret[0]: if not self.warned: self.server.add_warning( "Missing PolicyKit permisions detected. See the " "PolicyKit Permissions section of the install " "documentation at https://moonraker.readthedocs.io/ " "for details.") self.warned = True self.server.add_warning( "Moonraker not authorized for PolicyKit action: " f"[{action}], {err_msg}") return ret[0] async def get_interface(self, bus_name: str, bus_path: str, interface_name: str) -> ProxyInterface: ret = await self.get_interfaces(bus_name, bus_path, [interface_name]) return ret[0] async def get_interfaces( self, bus_name: str, bus_path: str, interface_names: List[str]) -> List[ProxyInterface]: if self.bus is None: raise self.server.error("Bus not avaialable") interfaces: List[ProxyInterface] = [] introspection = await self.bus.introspect(bus_name, bus_path) proxy_obj = self.bus.get_proxy_object(bus_name, bus_path, introspection) for ifname in interface_names: intf = proxy_obj.get_interface(ifname) interfaces.append(intf) return interfaces async def close(self): if self.bus is not None and self.bus.connected: self.bus.disconnect() await self.bus.wait_for_disconnect()
def wait(): time.sleep(0.5) def create_client_window(name): client_win = conn.generate_id() print("Window : ", hex(client_win)) conn.core.CreateWindowChecked(depth, client_win, root, 0, 0, 100, 100, 0, xproto.WindowClass.InputOutput, visual, 0, []).check() set_window_name(conn, client_win, "Test window "+name) set_window_class(conn, client_win, "Test windows") set_window_state(conn, client_win, 1) conn.core.MapWindowChecked(client_win).check() return client_win loop = asyncio.get_event_loop() bus = loop.run_until_complete(MessageBus().connect()) cmid = conn.generate_id() colormap = conn.core.CreateColormapChecked(xproto.ColormapAlloc._None, cmid, root, visual32).check() # Create window client_wins = [] for i in range(0,2): client_wins.append(create_client_window(str(i))) # Create frame window frame_win = conn.generate_id() print("Window : ", hex(frame_win)) conn.core.CreateWindowChecked(depth, frame_win, root, 0, 0, 200, 200, 0, xproto.WindowClass.InputOutput, visual, 0, []).check() set_window_name(conn, frame_win, "Frame")