Python pydbus.SystemBus() Examples

The following are 14 code examples of pydbus.SystemBus(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pydbus , or try the search function .
Example #1
Source File: util.py    From btle-sniffer with MIT License 6 votes vote down vote up
def find_device_in_objects(objects, device_address, adapter_pattern=None):
    """
    Given a dictionary of objects, find the Device interface that
    corresponds to the given address and the related adapter pattern.
    """
    bus = pydbus.SystemBus()
    path_prefix = ""
    if adapter_pattern is not None:
        adapter = find_adapter_in_objects(objects, adapter_pattern)
        path_prefix = adapter._path

    for path, ifaces in objects.items():
        device = ifaces.get(DEVICE_INTERFACE)
        if device is not None:
            if device.Address == device_address and path.startswith(path_prefix):
                return bus.get(SERVICE_NAME, path)[DEVICE_INTERFACE]
    else:
        raise BlueZDBusException(
            "Bluetooth device '{}' not found.".format(device_address)
        ) 
Example #2
Source File: sniffer.py    From btle-sniffer with MIT License 6 votes vote down vote up
def _connect(self, device):
        def cb_connect():
            try:
                bus = pydbus.SystemBus()
                proxy = bus.get(SERVICE_NAME, device.path)
                proxy.Connect()
            except KeyError:
                self._log.debug("The device has likely disappeared.", exc_info=True)
            except GLib.Error:
                self._log.debug("Connect() failed:", exc_info=True)
            else:
                self._log.info("Connection successful.")

            self.queued_connections -= 1

        if self.queued_connections == 0:
            print_device(device, "Connecting")
            GLib.idle_add(cb_connect)
            device.connected = True
            self.queued_connections += 1 
Example #3
Source File: util.py    From btle-sniffer with MIT License 5 votes vote down vote up
def get_managed_objects():
    """
    Use the D-Bus ObjectManager interface to determine all managed objects
    of the BlueZ service.
    """
    bus = pydbus.SystemBus()
    manager = bus.get(SERVICE_NAME, "/")[OBJECT_MANAGER_INTERFACE]
    return manager.GetManagedObjects() 
Example #4
Source File: util.py    From btle-sniffer with MIT License 5 votes vote down vote up
def find_adapter_in_objects(objects, pattern=None):
    """
    Given a dictionary of objects, find either the first Adapter interface
    or the one defined by the specified string pattern.
    """
    bus = pydbus.SystemBus()
    for path, ifaces in objects.items():
        adapter = ifaces.get(ADAPTER_INTERFACE)
        if adapter is not None:
            if pattern is None or pattern == adapter.Address or path.endswith(pattern):
                return bus.get(SERVICE_NAME, path)[ADAPTER_INTERFACE]
    else:
        raise BlueZDBusException("Bluetooth adapter not found.") 
Example #5
Source File: util.py    From btle-sniffer with MIT License 5 votes vote down vote up
def get_known_devices():
    """
    Using the DBus ObjectManager, yield all known Devices.
    """
    bus = pydbus.SystemBus()
    manager = bus.get(SERVICE_NAME, "/")[OBJECT_MANAGER_INTERFACE]
    objs = manager.GetManagedObjects()
    for path, ifaces in objs.items():
        if DEVICE_INTERFACE in ifaces.keys():
            yield (path, ifaces[DEVICE_INTERFACE]) 
Example #6
Source File: util.py    From btle-sniffer with MIT License 5 votes vote down vote up
def get_known_services():
    """
    Using the DBus ObjectManager, yield all known GATT services.
    """
    bus = pydbus.SystemBus()
    manager = bus.get(SERVICE_NAME, "/")[OBJECT_MANAGER_INTERFACE]
    objs = manager.GetManagedObjects()
    for path, ifaces in objs.items():
        if GATT_SERVICE_INTERFACE in ifaces.keys():
            yield (path, ifaces[GATT_SERVICE_INTERFACE]) 
Example #7
Source File: signal.py    From pai with Eclipse Public License 2.0 5 votes vote down vote up
def _run(self):
        super(SignalTextInterface, self)._run()

        bus = SystemBus()

        self.signal = bus.get('org.asamk.Signal')
        self.signal.onMessageReceived = self.handle_message
        self.loop = GLib.MainLoop()

        logger.debug("Signal Interface Running")

        self.loop.run() 
Example #8
Source File: power.py    From uchroma with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self._logger = Log.get('uchroma.power')
        self._name_watchers = []
        self._running = False
        self._sleeping = False
        self._user_active = False

        self._session_bus = SessionBus()
        self._system_bus = SystemBus()
        self._dm = UChromaDeviceManager() #singleton 
Example #9
Source File: subprocess_manager.py    From vexbot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.session_bus_available = True
        try:
            self.bus = _SessionBus()
        # NOTE: GError from package `gi`
        except Exception:
            # No session bus if we're here. Depending on linux distro, that's
            # not surprising
            self.session_bus_available = False

        # TODO: It's possible that the user is on a system that is not using
        # systemd, which means that this next call will fail. Should probably
        # have a try/catch and then just default to not having a subprocess
        # manager if that happens.
        self.system_bus = _SystemBus()

        # TODO: Verify that we can start services as the system bus w/o root
        # permissions
        if self.session_bus_available:
            self.systemd = self.bus.get('.systemd1')
        else:
            self.systemd = self.system_bus.get('.systemd1')

        # atexit.register(self._close_subprocesses)
        # signal.signal(signal.SIGINT, self._handle_close_signal)
        # signal.signal(signal.SIGTERM, self._handle_close_signal) 
Example #10
Source File: btk.py    From btk with MIT License 5 votes vote down vote up
def loop():
    bus = SystemBus()
    bus.own_name('net.lvht.btk')
    obj_path = '/net/lvht/btk/HIDProfile'

    sock = bt.BluetoothSocket(bt.L2CAP)
    sock.setblocking(False)
    try:
        sock.bind(('', PSM_INTR))
    except:
        print("For bluez5 add --noplugin=input to the bluetoothd commandline")
        print("Else there is another application running that has it open.")
        sys.exit(errno.EACCES)
    sock.listen(1)

    profile = HIDProfile(bus.con, obj_path, sock)

    opts = {
        "PSM": GLib.Variant.new_uint16(PSM_CTRL),
        "ServiceRecord": GLib.Variant.new_string(open('sdp_record.xml', 'r').read()),
        "RequireAuthentication": GLib.Variant.new_boolean(True),
        "RequireAuthorization": GLib.Variant.new_boolean(False),
    }
    manager = bus.get('org.bluez')['.ProfileManager1']
    manager.RegisterProfile(obj_path, str(uuid.uuid4()), opts)

    profile.run() 
Example #11
Source File: daemon.py    From weresync with Apache License 2.0 5 votes vote down vote up
def run():
    """Function which starts the daemon and publishes the
    :class:`~weresync.daemon.copier.DriveCopier` over dbus."""
    utils.start_logging_handler(DEFAULT_DAEMON_LOG_LOCATION)
    utils.enable_localization()
    with SystemBus() as bus:
        with bus.publish("net.manilas.weresync.DriveCopier", DriveCopier()):
            GLib.idle_add(lambda: LOGGER.debug("Starting GLib loop"))
            loop = GLib.MainLoop()
            loop.run() 
Example #12
Source File: __init__.py    From signal-curses with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        log('message thread')

        if self.app.state.bus == 'system':
            self.bus = pydbus.SystemBus()
        else:
            self.bus = pydbus.SessionBus()

        log('waiting for ({}) dbus...'.format(self.app.state.bus))
        self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60)
        if not self.signal:
            log('dbus err')
            npyscreen.notify_wait('Unable to get signal {} bus. Messaging functionality will not function.'.format(
                self.app.state.bus), title='Error in SignalDaemonThread')
            exit(1)
        log('got dbus')
        # self.signal.onMessageReceived

        while True:
            item = self.queue.get()
            log('queue item', item)
            if 'exit' in item:
                break
            self.do_action(**item)
            self.queue.task_done()
        log('message thread exit') 
Example #13
Source File: dbus_client.py    From gateway with Apache License 2.0 5 votes vote down vote up
def __init__(self, logger=None, c_extension=True, ignored_ep_filter=None):

        # logger
        self.logger = logger or logging.getLogger(__name__)

        # Main loop for events
        self.loop = GLib.MainLoop()

        # Connect to session bus
        self.bus = SystemBus()

        # Manage sink list
        self.sink_manager = SinkManager(
            bus=self.bus,
            on_new_sink_cb=self.on_sink_connected,
            on_sink_removal_cb=self.on_sink_disconnected,
            on_stack_started=self.on_stack_started,
            logger=self.logger,
        )

        self.ignore_ep_filter = ignored_ep_filter

        # Register for packet on Dbus
        if c_extension:
            self.logger.info("Starting dbus client with c extension")
            self.c_extension_thread = DbusEventHandler(
                self._on_data_received_c, self.logger
            )
        else:
            self.logger.info("Starting dbus client without c extension")
            # Subscribe to all massages received from any sink (no need for
            # connected sink for that)
            self.bus.subscribe(
                signal="MessageReceived",
                object="/com/wirepas/sink",
                signal_fired=self._on_data_received,
            )

            self.c_extension_thread = None 
Example #14
Source File: media.py    From canute-ui with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self):
        self.bus = pydbus.SystemBus()
        ud = self.bus.get('.UDisks2')

        ud_api = ud['org.freedesktop.DBus.ObjectManager']

        # Entries are by-path symlinks.
        self.mounted = []

        # Map UDisks2 object paths to by-path symlinks affected by them
        # coming and going.  More than one UDisks2 object may map to the
        # same symlink because we map both the partition and the
        # whole-block-device object to the symlink.
        self.obj2sym = {}

        # When True (i.e. just during synthesize_insertions()) we don't
        # trigger actions for insertions, just subscribe to updates and
        # populate mappings.
        self.synthetic = True
        self.synthesize_insertions(ud_api)
        self.synthetic = False

        # Drivers vary in their handling of removal of a medium.  Our
        # (2640) SD card reader whole-medium block device will persist
        # when the card is removed but will shrink to zero size.
        # There's no implicit unmounting of rudely removed media, so we
        # do that manually.  USB sticks' block devices disappear when
        # they're removed.  There's no implicit unmounting of rudely
        # removed media, so we do that.  So multiple subscriptions are
        # used to handle these cases.  Adding to the fun is that pydbus
        # doesn't always give all the information needed to work out
        # what to do, so there's some caching thrown in.
        ud_api.InterfacesAdded.connect(self.handle_medium_insertion)
        ud_api.InterfacesRemoved.connect(self.handle_medium_removal)

        # Simulate these either with udisksadm monitor or with:
        #   dbus-monitor --system \
        #       sender='org.freedesktop.UDisks2',\
        #       arg0='org.freedesktop.UDisks2.Filesystem',\
        #       member=PropertiesChanged,\
        #       interface=org.freedesktop.DBus.Properties
        self.bus.subscribe(sender='org.freedesktop.UDisks2',
                           iface='org.freedesktop.DBus.Properties',
                           signal='PropertiesChanged',
                           arg0='org.freedesktop.UDisks2.Filesystem',
                           signal_fired=self.handle_mounts)

        self.bus.subscribe(sender='org.freedesktop.UDisks2',
                           iface='org.freedesktop.DBus.Properties',
                           signal='PropertiesChanged',
                           arg0='org.freedesktop.UDisks2.Block',
                           signal_fired=self.handle_device_shrinks)