Python dbus.SystemBus() Examples

The following are 30 code examples of dbus.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 dbus , or try the search function .
Example #1
Source File: gatt_linux.py    From gatt-python with MIT License 7 votes vote down vote up
def __init__(self, adapter_name):
        self.listener = None
        self.adapter_name = adapter_name

        self._bus = dbus.SystemBus()
        try:
            adapter_object = self._bus.get_object('org.bluez', '/org/bluez/' + adapter_name)
        except dbus.exceptions.DBusException as e:
            raise _error_from_dbus_error(e)
        object_manager_object = self._bus.get_object("org.bluez", "/")
        self._adapter = dbus.Interface(adapter_object, 'org.bluez.Adapter1')
        self._adapter_properties = dbus.Interface(self._adapter, 'org.freedesktop.DBus.Properties')
        self._object_manager = dbus.Interface(object_manager_object, "org.freedesktop.DBus.ObjectManager")
        self._device_path_regex = re.compile('^/org/bluez/' + adapter_name + '/dev((_[A-Z0-9]{2}){6})$')
        self._devices = {}
        self._discovered_devices = {}
        self._interface_added_signal = None
        self._properties_changed_signal = None
        self._main_loop = None

        self.update_devices() 
Example #2
Source File: __init__.py    From launcher with GNU General Public License v3.0 6 votes vote down vote up
def find_device_in_objects(objects, device_address, adapter_pattern=None):
	bus = dbus.SystemBus()
	path_prefix = ""
	if adapter_pattern:
		adapter = find_adapter_in_objects(objects, adapter_pattern)
		path_prefix = adapter.object_path
	for path, ifaces in objects.iteritems():
		device = ifaces.get(DEVICE_INTERFACE)
		if device is None:
			continue
		if (device["Address"] == device_address and
						path.startswith(path_prefix)):
			obj = bus.get_object(SERVICE_NAME, path)
			return dbus.Interface(obj, DEVICE_INTERFACE)

	raise Exception("Bluetooth device not found") 
Example #3
Source File: systemd.py    From ideascube with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, path):
        proxy = dbus.SystemBus().get_object('org.freedesktop.systemd1', path)
        self._unit = dbus.Interface(
            proxy, dbus_interface='org.freedesktop.systemd1.Unit')

        props = self._unit.GetAll(
            'org.freedesktop.systemd1.Unit',
            dbus_interface=dbus.PROPERTIES_IFACE)

        for prop in props:
            prop = str(prop)

            if not hasattr(self.__class__, prop):
                setattr(self.__class__, prop, self._make_property(prop))

        if self.LoadState == 'not-found':
            raise NoSuchUnit(self.Id) 
Example #4
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #5
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #6
Source File: localGATT.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 D-Bus path and register it
        self.bus = dbus.SystemBus()
        self.path = '/ukBaz/bluezero'
        self.bus_name = dbus.service.BusName('ukBaz.bluezero', self.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.path)

        # Objects to be associated with this service
        self.managed_objs = []
        self.eventloop = async_tools.EventLoop() 
Example #7
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #8
Source File: openshift_facts.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def is_service_running(service):
    """ Queries systemd through dbus to see if the service is running """
    service_running = False
    bus = SystemBus()
    systemd = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
    manager = Interface(systemd, dbus_interface='org.freedesktop.systemd1.Manager')
    try:
        service_unit = service if service.endswith('.service') else manager.GetUnit('{0}.service'.format(service))
        service_proxy = bus.get_object('org.freedesktop.systemd1', str(service_unit))
        service_properties = Interface(service_proxy, dbus_interface='org.freedesktop.DBus.Properties')
        service_load_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'LoadState')
        service_active_state = service_properties.Get('org.freedesktop.systemd1.Unit', 'ActiveState')
        if service_load_state == 'loaded' and service_active_state == 'active':
            service_running = True
    except DBusException:
        pass

    return service_running 
Example #9
Source File: bt-audio.py    From bt-audio with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):

        self.bus = dbus.SystemBus()
        self.adapters = {}


        self.bus.add_signal_receiver(self._interfaceAdded, dbus_interface='org.freedesktop.DBus.ObjectManager', signal_name = "InterfacesAdded")
        self.bus.add_signal_receiver(self._interfaceRemoved, dbus_interface='org.freedesktop.DBus.ObjectManager', signal_name = "InterfacesRemoved")
        self.bus.add_signal_receiver(self._propertiesChanged, dbus_interface='org.freedesktop.DBus.Properties', signal_name = "PropertiesChanged", path_keyword = "path")

        # Find the adapters and create the objects
        obj_mgr = dbus.Interface(self.bus.get_object("org.bluez", "/"), 'org.freedesktop.DBus.ObjectManager')
        objs = obj_mgr.GetManagedObjects()
        for obj_path in objs:
            obj = objs[obj_path]
            if 'org.bluez.Adapter1' in obj:
                adapt_name = obj_path.split('/')[3]
                self.adapters[adapt_name] = Adapter(self.bus, obj_path)
                self.adapters[adapt_name].agentRegister() 
Example #10
Source File: daemon.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        setproctitle.setproctitle('pulseaudio-daemon')
        self.mainloop = GObject.MainLoop()
        self.processes = []
        self.check_id = None
        self.is_checking = False

        self._check_processes()

        signals = (
            ('NameOwnerChanged', 'org.freedesktop.DBus.{}',
                self.on_name_owner_changed),
        )
        self.bus = dbus.SystemBus()
        self.core = self.bus.get_object('org.freedesktop.DBus', '/')
        for sig_name, interface, sig_handler in signals:
            self.bus.add_signal_receiver(sig_handler, sig_name) 
Example #11
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 #12
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 #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: advertisement.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, adapter_addr=None):

        self.bus = dbus.SystemBus()

        if adapter_addr is None:
            adapters = adapter.list_adapters()
            if len(adapters) > 0:
                adapter_addr = adapters[0]

        self.advert_mngr_path = dbus_tools.get_dbus_path(adapter=adapter_addr)
        self.advert_mngr_obj = self.bus.get_object(
            constants.BLUEZ_SERVICE_NAME,
            self.advert_mngr_path)
        self.advert_mngr_methods = dbus.Interface(
            self.advert_mngr_obj,
            constants.LE_ADVERTISING_MANAGER_IFACE)
        self.advert_mngr_props = dbus.Interface(self.advert_mngr_obj,
                                                dbus.PROPERTIES_IFACE) 
Example #15
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 #16
Source File: GATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, adapter_addr):
        """
        GATT Manager Initialisation.

        :param manager_path: dbus path to the GATT Manager.
        """
        self.manager_path = dbus_tools.get_dbus_path(adapter_addr)
        self.bus = dbus.SystemBus()
        self.manager_obj = self.bus.get_object(
            constants.BLUEZ_SERVICE_NAME,
            self.manager_path)
        self.manager_methods = dbus.Interface(
            self.manager_obj,
            constants.GATT_MANAGER_IFACE)
        self.manager_props = dbus.Interface(self.manager_obj,
                                            dbus.PROPERTIES_IFACE) 
Example #17
Source File: ipc.py    From QMusic with GNU Lesser General Public License v2.1 6 votes vote down vote up
def auth_with_policykit(action,
                        bus_name,
                        object_path,
                        interface_name,
                        interactive=1, ):
    system_bus = dbus.SystemBus()
    obj = system_bus.get_object(bus_name, object_path, interface_name)

    policykit = dbus.Interface(obj, interface_name)
    pid = os.getpid()

    subject = ('unix-process', {'pid': dbus.UInt32(pid,
                                                   variant_level=1),
                                'start-time': dbus.UInt64(0), })
    details = {'': ''}
    flags = dbus.UInt32(interactive)
    cancel_id = ''
    (ok, notused, details) = policykit.CheckAuthorization(
        subject, action, details, flags, cancel_id)

    return ok 
Example #18
Source File: GATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def __init__(self, adapter_addr, device_addr, profile_uuid):
        """
        Remote GATT Profile Initialisation.

        :param profile_path: dbus path to the profile.
        """
        self.profile_path = dbus_tools.get_profile_path(adapter_addr,
                                                        device_addr,
                                                        profile_uuid)
        self.bus = dbus.SystemBus()
        self.profile_object = self.bus.get_object(
            constants.BLUEZ_SERVICE_NAME,
            self.profile_path)
        self.profile_methods = dbus.Interface(
            self.profile_object,
            constants.GATT_PROFILE_IFACE)
        self.profile_props = dbus.Interface(self.profile_object,
                                            dbus.PROPERTIES_IFACE) 
Example #19
Source File: bluezutils.py    From DirtyTooth-RaspberryPi with GNU Affero General Public License v3.0 6 votes vote down vote up
def find_device_in_objects(objects, device_address, adapter_pattern=None):
	bus = dbus.SystemBus()
	path_prefix = ""
	if adapter_pattern:
		adapter = find_adapter_in_objects(objects, adapter_pattern)
		path_prefix = adapter.object_path
	for path, ifaces in objects.iteritems():
		device = ifaces.get(DEVICE_INTERFACE)
		if device is None:
			continue
		if (device["Address"] == device_address and
						path.startswith(path_prefix)):
			obj = bus.get_object(SERVICE_NAME, path)
			return dbus.Interface(obj, DEVICE_INTERFACE)

	raise Exception("Bluetooth device not found") 
Example #20
Source File: bluetooth_emulator_server.py    From Bluetooth_HID with GNU General Public License v3.0 6 votes vote down vote up
def init_bluez_profile(self):

        print("Configuring Bluez Profile")

        # setup profile options
        service_record = self.read_sdp_service_record()

        opts = {
            "ServiceRecord": service_record,
            "Role": "server",
            "RequireAuthentication": False,
            "RequireAuthorization": False
        }

        # retrieve a proxy for the bluez profile interface
        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez", "/org/bluez"), "org.bluez.ProfileManager1")

        profile = BluetoothBluezProfile(bus, BluetoothDevice.PROFILE_DBUS_PATH)

        manager.RegisterProfile(BluetoothDevice.PROFILE_DBUS_PATH, BluetoothDevice.UUID, opts)

        print("Profile registered ")

    # read and return an sdp record from a file 
Example #21
Source File: user_interface.py    From Bluetooth_HID with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, master, background="white"):
        Frame.__init__(self, master, bg=background)

        self.container = Frame(self, bg=background)
        self.container.pack(side="top")

        self.buttons = []

        for i in xrange(3):
            for j in xrange(3):
                self.buttons.append(Button(self.container, text=str(i * 3 + j + 1)))
                self.buttons[i * 3 + j].bind("<ButtonPress-1>", self.on_press(i, j))
                self.buttons[i * 3 + j].bind("<ButtonRelease-1>", self.on_release)
                self.buttons[i * 3 + j].grid(row=i, column=j, padx=20, pady=20)

        self.bus = dbus.SystemBus()
        self.bluetoothservice = self.bus.get_object('org.upwork.HidBluetoothService', "/org/upwork/HidBluetoothService")
        self.iface = dbus.Interface(self.bluetoothservice, 'org.upwork.HidBluetoothService') 
Example #22
Source File: btk_server.py    From keyboard_mouse_emulate_on_raspberry with MIT License 6 votes vote down vote up
def init_bluez_profile(self):
		print("Configuring Bluez Profile")

		# setup profile options
		service_record = self.read_sdp_service_record()
		opts = {
			"ServiceRecord": service_record,
			"Role": "server",
			"RequireAuthentication": False,
			"RequireAuthorization": False,
			"AutoConnect": True
		}

		# retrieve a proxy for the bluez profile interface
		bus = dbus.SystemBus()
		manager = dbus.Interface(bus.get_object(
		    "org.bluez", "/org/bluez"), "org.bluez.ProfileManager1")
		profile = BTKbBluezProfile(bus, BTKbDevice.PROFILE_DBUS_PATH)
		manager.RegisterProfile("/org/bluez/hci0", BTKbDevice.UUID, opts)
		print("Profile registered ")

	# read and return an sdp record from a file 
Example #23
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 6 votes vote down vote up
def __new__(klass, object_path=None):
				# If we didn't introspect this one at definition time, let's do it now.
				if object_path and not klass.introspection_data:
						proxy = dbus.SystemBus().get_object(klass.dbus_service, object_path)
						klass.introspection_data = proxy.Introspect(dbus_interface='org.freedesktop.DBus.Introspectable')
						root = etree.fromstring(klass.introspection_data)
						for element in root:
								if element.tag == 'interface' and element.attrib['name'] in klass.interface_names:
										for item in element:
												if item.tag == 'property':
														setattr(klass, item.attrib['name'], type(klass).make_property(klass.__name__, element.attrib['name'], item.attrib))
														klass.properties.append(item.attrib['name'])
												elif item.tag == 'method':
														aname = item.attrib['name']
														if hasattr(klass, aname):
																aname = '_' + aname
														setattr(klass, aname, type(klass).make_method(klass.__name__, element.attrib['name'], item.attrib, list(item)))
												elif item.tag == 'signal':
														SignalDispatcher.args[(element.attrib['name'], item.attrib['name'])] = [(arg.attrib.get('name',None), arg.attrib['type']) for arg in item]
														setattr(klass, 'On' + item.attrib['name'], type(klass).make_signal(klass.__name__, element.attrib['name'], item.attrib))
														klass.signals.append(item.attrib['name'])

				SignalDispatcher.listen_for_restarts()
				return super(NMDbusInterface, klass).__new__(klass) 
Example #24
Source File: dirtyagent.py    From HomePWN with GNU General Public License v3.0 6 votes vote down vote up
def run_agent():
    if GObject:
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
        capability = "NoInputNoOutput"

        path = "/test/agent"
        agent = Agent(bus, path)

        mainloop = GObject.MainLoop()

        obj = bus.get_object(BUS_NAME, "/org/bluez")
        manager = dbus.Interface(obj, "org.bluez.AgentManager1")
        manager.RegisterAgent(path, capability)

        print("\n\n[+] Agent registered in background ")

        manager.RequestDefaultAgent(path)
        try:
            mainloop.run()
        except:
            print("\n[-] The agent has finished ")
    else:
        print("No agent running...") 
Example #25
Source File: __init__.py    From ubuntu-cleaner with GNU General Public License v3.0 6 votes vote down vote up
def _check_permission(self, sender, action):
        '''
        Verifies if the specified action is permitted, and raises
        an AccessDeniedException if not.

        The caller should use ObtainAuthorization() to get permission.
        '''

        try:
            if sender:
                kit = dbus.SystemBus().get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
                kit = dbus.Interface(kit, 'org.freedesktop.PolicyKit1.Authority')

                (granted, _, details) = kit.CheckAuthorization(
                                ('system-bus-name', {'name': sender}),
                                action, {}, dbus.UInt32(1), '', timeout=600)

                if not granted:
                    raise AccessDeniedException('Session not authorized by PolicyKit')

        except AccessDeniedException:
            raise

        except dbus.DBusException as ex:
            raise AccessDeniedException(ex.message) 
Example #26
Source File: mouse_client.py    From keyboard_mouse_emulate_on_raspberry with MIT License 5 votes vote down vote up
def __init__(self):
        self.bus = dbus.SystemBus()
        self.btkservice = self.bus.get_object(
            'org.yaptb.btkbservice', '/org/yaptb/btkbservice')
        self.iface = self.bus.Interface(btkservice, 'org.yaptb.btkbservice')
        self.mouse_delay = 20 / 1000
        self.mouse_speed = 1 
Example #27
Source File: btspeaker.py    From intel-iot-refkit with MIT License 5 votes vote down vote up
def remove_paired_bt_device():
    bus = dbus.SystemBus()
    om = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
    obj = om.GetManagedObjects()
    bt_adapter_path = "/org/bluez/hci0"
    bt_device = None
    bt_adapter = None

    for path, interf in obj.iteritems():
        if "org.bluez.Device1" in interf:
            properties = interf["org.bluez.Device1"]
            if properties["Adapter"] == bt_adapter_path:
                bt_device_inter = interf.get("org.bluez.Device1")
                if bt_device_inter["Address"] == properties["Address"]:
                    obj2 = bus.get_object("org.bluez", path)
                    bt_device = dbus.Interface(obj2, "org.bluez.Device1")
                    bt_adapter = dbus.Interface(obj2, "org.bluez.Adapter1")
                    print("found device object")
                    break;

    for path, interf in obj.iteritems():
        adapter_inter = interf.get("org.bluez.Adapter1")
        if adapter_inter is not None:
            obj2 = bus.get_object("org.bluez", path)
            bt_adapter = dbus.Interface(obj2, "org.bluez.Adapter1")

    if bt_device is not None:
        for attr in dir(bt_device):
          print "bt_device.%s = %s" % (attr, getattr(bt_device, attr))
        bt_device.Disconnect()
        path = bt_device.object_path
        if bt_adapter is not None:
          bt_adapter.RemoveDevice(path)

# This is the main pairing functions called from main thread 
Example #28
Source File: __init__.py    From launcher with GNU General Public License v3.0 5 votes vote down vote up
def get_managed_objects():
	bus = dbus.SystemBus()
	manager = dbus.Interface(bus.get_object("org.bluez", "/"),
				"org.freedesktop.DBus.ObjectManager")
	return manager.GetManagedObjects() 
Example #29
Source File: __init__.py    From launcher with GNU General Public License v3.0 5 votes vote down vote up
def find_adapter_in_objects(objects, pattern=None):
	bus = dbus.SystemBus()
	for path, ifaces in objects.iteritems():
		adapter = ifaces.get(ADAPTER_INTERFACE)
		if adapter is None:
			continue
		if not pattern or pattern == adapter["Address"] or \
							path.endswith(pattern):
			obj = bus.get_object(SERVICE_NAME, path)
			return dbus.Interface(obj, ADAPTER_INTERFACE)
	raise Exception("Bluetooth adapter not found") 
Example #30
Source File: cpu_temperature.py    From python-bluezero with MIT License 5 votes vote down vote up
def __init__(self):
        self.bus = dbus.SystemBus()
        self.app = localGATT.Application()
        self.srv = localGATT.Service(1, CPU_TMP_SRVC, True)

        self.charc = TemperatureChrc(self.srv)

        self.charc.service = self.srv.path

        cpu_format_value = dbus.Array([dbus.Byte(0x0E),
                                       dbus.Byte(0xFE),
                                       dbus.Byte(0x2F),
                                       dbus.Byte(0x27),
                                       dbus.Byte(0x01),
                                       dbus.Byte(0x00),
                                       dbus.Byte(0x00)])
        self.cpu_format = localGATT.Descriptor(4,
                                               CPU_FMT_DSCP,
                                               self.charc,
                                               cpu_format_value,
                                               ['read'])

        self.app.add_managed_object(self.srv)
        self.app.add_managed_object(self.charc)
        self.app.add_managed_object(self.cpu_format)

        self.srv_mng = GATT.GattManager(adapter.list_adapters()[0])
        self.srv_mng.register_application(self.app, {})

        self.dongle = adapter.Adapter(adapter.list_adapters()[0])
        advert = advertisement.Advertisement(1, 'peripheral')

        advert.service_UUIDs = [CPU_TMP_SRVC]
        # eddystone_data = tools.url_to_advert(WEB_BLINKT, 0x10, TX_POWER)
        # advert.service_data = {EDDYSTONE: eddystone_data}
        if not self.dongle.powered:
            self.dongle.powered = True
        ad_manager = advertisement.AdvertisingManager(self.dongle.address)
        ad_manager.register_advertisement(advert, {})