Python dbus.service() Examples

The following are 30 code examples of dbus.service(). 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 dbus , or try the search function .
Example #1
Source File: bluetooth_emulator_server.py    From Bluetooth_HID with GNU General Public License v3.0 6 votes vote down vote up
def read_sdp_service_record(self):

        print("Reading service record")

        try:
            fh = open(BluetoothDevice.SDP_RECORD_PATH, "r")
        except:
            sys.exit("Could not open the sdp record. Exiting...")

        return fh.read()



    # listen for incoming client connections

    # ideally this would be handled by the Bluez 5 profile
    # but that didn't seem to work 
Example #2
Source File: localGATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def GetAll(self, interface_name):
        """Return the service properties.

        This method is registered with the D-Bus at
        ``org.freedesktop.DBus.Properties``

        :param interface: interface to get the properties of.

        The interface must be ``org.bluez.GattCharacteristic1`` otherwise an
        exception is raised.
        """
        if interface_name != constants.GATT_CHRC_IFACE:
            raise InvalidArgsException()

        try:
            return self.props[interface_name]
        except KeyError:
            raise dbus.exceptions.DBusException(
                'no such interface ' + interface_name,
                name=interface_name + '.UnknownInterface') 
Example #3
Source File: btk_server.py    From BlogCode with MIT License 6 votes vote down vote up
def read_sdp_service_record(self):

        print("Reading service record")

        try:
            fh = open(BTKbDevice.SDP_RECORD_PATH, "r")
        except:
            sys.exit("Could not open the sdp record. Exiting...")

        return fh.read()   



    #listen for incoming client connections
    #ideally this would be handled by the Bluez 5 profile 
    #but that didn't seem to work 
Example #4
Source File: localGATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def GetAll(self, interface_name):
        """Return the service properties.

        This method is registered with the D-Bus at
        ``org.freedesktop.DBus.Properties``

        :param interface: interface to get the properties of.

        The interface must be ``org.bluez.GattService1`` otherwise an
        exception is raised.
        """
        if interface_name != constants.GATT_SERVICE_IFACE:
            raise InvalidArgsException()

        try:
            return self.props[interface_name]
        except KeyError:
            raise dbus.exceptions.DBusException(
                'no such interface ' + interface_name,
                name=interface_name + '.UnknownInterface') 
Example #5
Source File: localGATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, service_id, uuid, primary):
        """Default initialiser.

        1. Registers the service on the D-Bus.
        2. Sets up the service UUID and primary flags.

        :param service_id:
        :param uuid: service BLE UUID
        :param primary: whether or not the service is a primary service
        """
        # Setup D-Bus object paths and register service
        self.path = self.PATH_BASE + str('{0:04d}'.format(service_id))
        self.bus = dbus.SystemBus()
        self.interface = constants.GATT_SERVICE_IFACE
        dbus.service.Object.__init__(self, self.bus, self.path)
        self.props = {
            constants.GATT_SERVICE_IFACE: {
                'UUID': uuid,
                'Primary': primary}
        } 
Example #6
Source File: sound_menu.py    From lplayer with MIT License 6 votes vote down vote up
def __init__(self, desktop_name):
        """
        Creates a SoundMenuControls object.

        Requires a dbus loop to be created before the gtk mainloop,
        typically by calling DBusGMainLoop(set_as_default=True).

        arguments:
        desktop_name: The name of the desktop file for the application,
        such as, "simple-player" to refer to the file: simple-player.desktop.

        """

        self.desktop_name = desktop_name
        bus_str = """org.mpris.MediaPlayer2.%s""" % desktop_name
        bus_name = dbus.service.BusName(bus_str, bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, "/org/mpris/MediaPlayer2")
        self.__playback_status = "Stopped"

        self.song_changed() 
Example #7
Source File: service.py    From openrazer with GNU General Public License v2.0 6 votes vote down vote up
def get_service(bus_name, object_path):
        """
        Get an instance of the service history

        :param bus_name: DBus bus name
        :type bus_name: str

        :param object_path: DBus Object name
        :type object_path: str

        :return: New object
        :rtype: DBusService
        """
        new_service = type("DBUSService{0:04}".format(DBusServiceFactory.service_number), (DBusService,), {})
        DBusServiceFactory.service_number += 1

        return new_service(bus_name, object_path) 
Example #8
Source File: __init__.py    From FeelUOwn with GNU General Public License v3.0 6 votes vote down vote up
def run_mpris2_server(app):
    try:
        import dbus
        import dbus.service
        import dbus.mainloop.pyqt5
    except ImportError as e:
        logger.error("can't run mpris2 server: %s",  str(e))
    else:
        from .mpris2 import Mpris2Service, BusName

        # check if a mainloop was already set
        mainloop = dbus.get_default_main_loop()
        if mainloop is not None:
            logger.warn("mpris2 service already enabled? "
                        "maybe you should remove feeluown-mpris2-plugin")
            return

        # set the mainloop before any dbus operation
        dbus.mainloop.pyqt5.DBusQtMainLoop(set_as_default=True)
        session_bus = dbus.SessionBus()
        bus = dbus.service.BusName(BusName, session_bus)
        service = Mpris2Service(app, bus)
        service.enable() 
Example #9
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, service, advertising_type):
        """"Default initialiser.

        1. Registers the advertisement on the service path.
        2. Sets up initial values.

        :param service: service that the advertisement is associated with.
        :param advertising_type: type of advertisement
        """
        # print('**Service', service)
        self.index = id(self)
        self.path = self.PATH_BASE + str(self.index)
        dbus.service.Object.__init__(self, service.bus, self.path)

        self.ad_type = advertising_type
        # print('Service uuid', service.uuid)
        # print('Advert path', self.path)
        # print('Service bus', service.bus)
        self.service_uuids = None
        self.manufacturer_data = None
        self.solicit_uuids = None
        self.service_data = None
        self.include_tx_power = None 
Example #10
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def get_properties(self):
        """Return a dictionary of the characteristic properties.

        The dictionary has the following keys:

        - Service: the characteristic's service
        - UUID: the characteristic UUID
        - Flags: any characteristic flags
        - Descriptors: D-Bus array of the descriptor object paths
          associated with the characteristic.

        """
        return {
            constants.GATT_CHRC_IFACE: {
                'Service': self.service.get_path(),
                'UUID': self.uuid,
                'Flags': self.flags,
                'Descriptors': dbus.Array(
                    self.get_descriptor_paths(),
                    signature='o')
            }
        } 
Example #11
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def GetManagedObjects(self):
        """Get all objects that are managed by the service.

        Return type is a dictionary whose keys are each registered object and
        values the properties of the given object.
        """
        response = {}
        # print('GetManagedObjects')

        response[self.get_path()] = self.get_properties()
        chrcs = self.get_characteristics()
        for chrc in chrcs:
            response[chrc.get_path()] = chrc.get_properties()
            descs = chrc.get_descriptors()
            for desc in descs:
                response[desc.get_path()] = desc.get_properties()

        return response 
Example #12
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def get_properties(self):
        """Return a dictionary of the service properties.

        The dictionary has the following keys:

        - UUID: the service UUID
        - Primary: whether the service is the primary service
        - Characteristics: D-Bus array of the characteristic object paths
          associated with the service.

        """
        return {
            constants.GATT_SERVICE_IFACE: {
                'UUID': self.uuid,
                'Primary': self.primary,
                'Characteristics': dbus.Array(
                    self.get_characteristic_paths(),
                    signature='o')
            }
        } 
Example #13
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, uuid, primary, type='peripheral'):
        """Default initialiser.

        1. Registers the service on the D-Bus.
        2. Sets up the service UUID and primary flags.
        3. Initialises the list of characteristics associated with the service.

        :param uuid: service BLE UUID
        :param primary: whether or not the service is a primary service
        """
        # Setup D-Bus object paths and register service
        self.index = id(self)
        self.path = self.PATH_BASE + str(self.index)
        self.bus = dbus.SystemBus()
        dbus.service.Object.__init__(self, self.bus, self.path)

        # Setup UUID, primary flag
        self.uuid = uuid
        self.primary = primary
        self.type = type
        self.service_data = None

        # Initialise characteristics within the service
        self.characteristics = [] 
Example #14
Source File: gtkapp.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def __verifyNotRunning(self):
        if os.path.exists(common.LOCK_FILE):
            pid = Application._read_pid_from_lock_file()

            # Check that the found PID is running and is autokey
            with subprocess.Popen(["ps", "-p", pid, "-o", "command"], stdout=subprocess.PIPE) as p:
                output = p.communicate()[0]

            if "autokey" in output.decode():
                logging.debug("AutoKey is already running as pid %s", pid)
                bus = dbus.SessionBus()

                try:
                    dbusService = bus.get_object("org.autokey.Service", "/AppService")
                    dbusService.show_configure(dbus_interface="org.autokey.Service")
                    sys.exit(0)
                except dbus.DBusException as e:
                    logging.exception("Error communicating with Dbus service")
                    self.show_error_dialog(_("AutoKey is already running as pid %s but is not responding") % pid, str(e))
                    sys.exit(1)

        return True 
Example #15
Source File: peripheral.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, device_id=None):
        """Default initialiser.

        1. Initialises the program loop using ``GObject``.
        2. Registers the Application on the D-Bus.
        3. Initialises the list of services offered by the application.

        """
        # Initialise the loop that the application runs in
        GObject.threads_init()
        dbus.mainloop.glib.threads_init()
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        self.mainloop = GObject.MainLoop()

        # Initialise the D-Bus path and register it
        self.bus = dbus.SystemBus()
        self.path = '/ukBaz/bluezero/application{}'.format(id(self))
        self.bus_name = dbus.service.BusName('ukBaz.bluezero', self.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.path)

        # Initialise services within the application
        self.services = []

        self.dongle = adapter.Adapter(device_id) 
Example #16
Source File: advertisement.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, advert_id, ad_type):
        """Default initialiser.

        Creates the interface to the specified advertising data.
        The DBus path must be specified.

        :param advert_id: Unique ID of advertisement.
        :param ad_type: Possible values: "broadcast" or "peripheral"
        """
        # Setup D-Bus object paths and register service
        self.path = '/ukBaz/bluezero/advertisement{0:04d}'.format(advert_id)
        self.bus = dbus.SystemBus()
        self.eventloop = async_tools.EventLoop()
        self.interface = constants.LE_ADVERTISEMENT_IFACE
        dbus.service.Object.__init__(self, self.bus, self.path)
        self.props = {
            constants.LE_ADVERTISEMENT_IFACE: {
                'Type': ad_type,
                'ServiceUUIDs': None,
                'ManufacturerData': None,
                'SolicitUUIDs': None,
                'ServiceData': None,
                'IncludeTxPower': False
            }
        } 
Example #17
Source File: gtkapp.py    From autokey with GNU General Public License v3.0 6 votes vote down vote up
def show_script_error(self, parent):
        """
        Show the last script error (if any)
        """
        if self.service.scriptRunner.error != '':
            dlg = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK,
                                     message_format=self.service.scriptRunner.error)
            self.service.scriptRunner.error = ''
            # revert the tray icon
            self.notifier.set_icon(cm.ConfigManager.SETTINGS[cm.NOTIFICATION_ICON])
            self.notifier.errorItem.hide()
            self.notifier.update_visible_status()

        else:
            dlg = Gtk.MessageDialog(type=Gtk.MessageType.INFO, buttons=Gtk.ButtonsType.OK,
                                     message_format=_("No error information available"))

        dlg.set_title(_("View script error"))
        dlg.set_transient_for(parent)
        dlg.run()
        dlg.destroy() 
Example #18
Source File: bluetooth_emulator_server.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def close(self):
        self.queue.put("Disconnected")
        self.scontrol.close()
        self.sinterrupt.close()


# define a dbus service that emulates a bluetooth keyboard and mouse
# this will enable different clients to connect to and use
# the service 
Example #19
Source File: bluetooth_emulator_server.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):

        print("Setting up service")

        # set up as a dbus service
        bus_name = dbus.service.BusName("org.upwork.HidBluetoothService", bus=dbus.SystemBus())
        dbus.service.Object.__init__(self, bus_name, "/org/upwork/HidBluetoothService")

        queue = sys.argv[1]

        # create and setup our device
        self.device = BluetoothDevice(queue)

        # start listening for connections
        self.device.listen() 
Example #20
Source File: bluetooth_emulator_server.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def init_bt_device(self):

        print("Configuring for name " + BluetoothDevice.MY_DEV_NAME)

        # set the device class to a keybord/mouse combo and set the name
        #os.system("sudo hciconfig hcio class 0x25C0") # Keyboard/Mouse Combo in Limited Discoverable Mode
        os.system("sudo hciconfig hcio class 0x05C0")  # Keyboard/Mouse Combo in General Discoverable Mode
        os.system("sudo hciconfig hcio name " + BluetoothDevice.MY_DEV_NAME)

        # make the device discoverable
        os.system("sudo hciconfig hcio piscan")

    # set up a bluez profile to advertise device capabilities from a loaded service record 
Example #21
Source File: user_interface.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):

        print("Setting up service")

        # set up as a dbus service
        bus_name = dbus.service.BusName("org.upwork.HidBluetoothService", bus=dbus.SystemBus())
        dbus.service.Object.__init__(self, bus_name, "/org/upwork/HidBluetoothService")

        # create and setup our device
        self.device = BluetoothDevice()

        # start listening for connections
        self.device.listen() 
Example #22
Source File: serviceHelper.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def _checkPolkitPrivilege(self, sender, conn, privilege):
        # from jockey
        """
        Verify that sender has a given PolicyKit privilege.

        sender is the sender's (private) D-BUS name, such as ":1:42"
        (sender_keyword in @dbus.service.methods). conn is
        the dbus.Connection object (connection_keyword in
        @dbus.service.methods). privilege is the PolicyKit privilege string.

        This method returns if the caller is privileged, and otherwise throws a
        PermissionDeniedByPolicy exception.
        """
        if sender is None and conn is None:
            # called locally, not through D-BUS
            return
        if not self.enforce_polkit:
            # that happens for testing purposes when running on the session
            # bus, and it does not make sense to restrict operations here
            return

        # query PolicyKit
        self._initPolkit()
        try:
            # we don't need is_challenge return here, since we call with AllowUserInteraction
            (is_auth, _, details) = self.polkit.CheckAuthorization(
                    ('system-bus-name', {'name': dbus.String(sender, variant_level=1)}),
                    privilege, {'': ''}, dbus.UInt32(1), '', timeout=3000)
        except dbus.DBusException as e:
            if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown':
                # polkitd timed out, connect again
                self.polkit = None
                return self._checkPolkitPrivilege(sender, conn, privilege)
            else:
                raise

        if not is_auth:
            raise PermissionDeniedByPolicy(privilege) 
Example #23
Source File: user_interface.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def close(self):
        global connection_status_queue
        connection_status_queue.put("Disconnected")
        self.scontrol.close()
        self.sinterrupt.close()


# define a dbus service that emulates a bluetooth keyboard and mouse
# this will enable different clients to connect to and use
# the service 
Example #24
Source File: user_interface.py    From Bluetooth_HID with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus, path):
        dbus.service.Object.__init__(self, bus, path)


#
# create a bluetooth device to emulate a HID keyboard/mouse,
# advertize a SDP record using our bluez profile class
# 
Example #25
Source File: py_spotify_listener.py    From polybar-spotify-controls with MIT License 5 votes vote down vote up
def __init__(self, bus_name, object_path, loop):
        """Initialize the DBUS service object."""
        dbus.service.Object.__init__(self, bus_name, object_path)
        self.loop = loop 
Example #26
Source File: advertisement.py    From python-bluezero with MIT License 5 votes vote down vote up
def Release(self):
        """
        This method gets called when the service daemon
        removes the Advertisement. A client can use it to do
        cleanup tasks. There is no need to call
        UnregisterAdvertisement because when this method gets
        called it has already been unregistered.
        :return:
        """
        pass 
Example #27
Source File: serviceHelper.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def addRule(self, cmd, uuid, sender=None, conn=None):
        """
        Receive command and uuid and create an Udev rule out of this.
        This is done on the service side to prevent malicious code to
        run as root.
        """
        #prevent breaking out of su command
        chars = re.findall(r'[^a-zA-Z0-9-/\.>& ]', cmd)
        if chars:
            raise InvalidChar("Parameter 'cmd' contains invalid character(s) %s"
                              % '|'.join(set(chars)))
        #only allow relevant chars in uuid
        chars = re.findall(r'[^a-zA-Z0-9-]', uuid)
        if chars:
            raise InvalidChar("Parameter 'uuid' contains invalid character(s) %s"
                              % '|'.join(set(chars)))

        self._validateCmd(cmd)

        info = SenderInfo(sender, conn)
        user = info.connectionUnixUser()
        owner = info.nameOwner()

        self._checkLimits(owner, cmd)

        #create su command
        sucmd = "%s - '%s' -c '%s'" %(self.su, user, cmd)
        #create Udev rule
        rule = 'ACTION=="add|change", ENV{ID_FS_UUID}=="%s", RUN+="%s"\n' %(uuid, sucmd)

        #store rule
        if not owner in self.tmpDict:
            self.tmpDict[owner] = []
        self.tmpDict[owner].append(rule) 
Example #28
Source File: gnome-pass-search-provider.py    From gnome-pass-search-provider with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.session_bus = dbus.SessionBus()
        bus_name = dbus.service.BusName(self.bus_name, bus=self.session_bus)
        dbus.service.Object.__init__(self, bus_name, self._object_path)
        self.password_store = getenv("PASSWORD_STORE_DIR") or expanduser(
            "~/.password-store"
        ) 
Example #29
Source File: peripheral.py    From python-bluezero with MIT License 5 votes vote down vote up
def UUID(self):
        """Return Service UUID"""
        return self.service.Get(constants.GATT_SERVICE_IFACE, 'UUID') 
Example #30
Source File: peripheral.py    From python-bluezero with MIT License 5 votes vote down vote up
def add_service(self, service):
        """Add a service to the list of services offered by the Application.

        :param service: the service to be added (type: peripheral.Service)
        """
        self.services.append(service)