Python dbus.UInt32() Examples

The following are 26 code examples of dbus.UInt32(). 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: py_spotify_listener.py    From polybar-spotify-controls with MIT License 7 votes vote down vote up
def unwrap(val):
    if isinstance(val, dbus.ByteArray):
        return "".join([str(x) for x in val])
    if isinstance(val, (dbus.Array, list, tuple)):
        return [unwrap(x) for x in val]
    if isinstance(val, (dbus.Dictionary, dict)):
        return dict([(unwrap(x), unwrap(y)) for x, y in val.items()])
    if isinstance(val, (dbus.Signature, dbus.String)):
        return str(val)
    if isinstance(val, dbus.Boolean):
        return bool(val)
    if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)):
        return int(val)
    if isinstance(val, dbus.Byte):
        return bytes([int(val)])
    return val 
Example #2
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 #3
Source File: test_bt_bus.py    From bt-manager with GNU General Public License v3.0 6 votes vote down vote up
def test_all(self):

        val = [1, 2, 3, 4, 5]
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.Array, val),  # noqa
                         dbus.Array(val))
        val = -1
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.Int32, val),  # noqa
                         dbus.Int32(val))
        val = 1
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.UInt32, val),  # noqa
                         dbus.UInt32(val))
        val = 'Test'
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.String, val),  # noqa
                         dbus.String(val))
        val = {'Hello': 1}
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.Dictionary,  # noqa
                                                           val),
                         dbus.Dictionary(val))
        val = 'True'
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.Boolean, val),  # noqa
                         dbus.Boolean(True))
        val = 'False'
        self.assertEqual(bt_manager.interface.translate_to_dbus_type(dbus.Boolean, val),  # noqa
                         dbus.Boolean(False)) 
Example #4
Source File: test_bt_bus.py    From bt-manager with GNU General Public License v3.0 6 votes vote down vote up
def test_agent_with_defaults(self, patched_system_bus):
        mock_system_bus = mock.MagicMock()
        patched_system_bus.return_value = mock_system_bus
        mock_system_bus.get_object.return_value = dbus.ObjectPath('/org/bluez')
        agent = bt_manager.BTAgent()

        obj = dbus.ObjectPath('/org/bluez/985/hci0/dev_00_11_67_D2_AB_EE')
        uuid = dbus.String(u'00001108-0000-1000-8000-00805f9b34fb')
        pin_code = dbus.String('0000')
        pass_key = dbus.UInt32(0)
        mode = 'Mode'

        self.assertEqual(agent.Release(), None)
        self.assertEqual(agent.Authorize(obj, uuid), None)
        self.assertEqual(agent.RequestPinCode(obj), pin_code)
        self.assertEqual(agent.RequestPasskey(obj), pass_key)
        self.assertEqual(agent.DisplayPasskey(obj, pass_key), None)
        self.assertEqual(agent.RequestConfirmation(obj, pass_key), None)
        self.assertEqual(agent.ConfirmModeChange(mode), None)
        self.assertEqual(agent.Cancel(), None) 
Example #5
Source File: agent.py    From bluetool with GNU General Public License v3.0 6 votes vote down vote up
def RequestPasskey(self, device):
        logger.info("RequestPasskey: {}\n".format(device))

        if not self._trust(device):
            logger.error("RequestPasskey: failed to trust\n")
            raise _Rejected

        dev_info = self._get_device_info(device)

        try:
            passkey = int(self._client.request_passkey(dev_info))
        except BaseException as error:
            logger.error("RequestPasskey: {}\n".format(error))
            raise _Rejected

        return dbus.UInt32(passkey) 
Example #6
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 #7
Source File: networkmanayer.py    From my-weather-indicator with MIT License 6 votes vote down vote up
def unwrap(self, val):
        if isinstance(val, dbus.ByteArray):
            return "".join([str(x) for x in val])
        if isinstance(val, (dbus.Array, list, tuple)):
            return [self.unwrap(x) for x in val]
        if isinstance(val, (dbus.Dictionary, dict)):
            return dict([(self.unwrap(x), self.unwrap(y)) for x, y in val.items()])
        if isinstance(val, dbus.ObjectPath):
            if val.startswith('/org/freedesktop/NetworkManager/'):
                classname = val.split('/')[4]
                classname = {
                    'Settings': 'Connection',
                    'Devices': 'Device',
                }.get(classname, classname)
                return globals()[classname](val)
        if isinstance(val, (dbus.Signature, dbus.String)):
            return unicode(val)
        if isinstance(val, dbus.Boolean):
            return bool(val)
        if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)):
            return int(val)
        if isinstance(val, dbus.Byte):
            return bytes([int(val)])
        return val 
Example #8
Source File: other_nm.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def mask_to_dbus(mask):
        return dbus.UInt32(mask) 
Example #9
Source File: other_nm.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def addr_to_dbus(addr, family):
        if family == socket.AF_INET:
            return dbus.UInt32(struct.unpack('I', socket.inet_pton(family, addr))[0])
        else:
            return dbus.ByteArray(socket.inet_pton(family, addr)) 
Example #10
Source File: other_nm.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def base_to_python(val):
        if isinstance(val, dbus.ByteArray):
            return "".join([str(x) for x in val])
        if isinstance(val, (dbus.Array, list, tuple)):
            return [fixups.base_to_python(x) for x in val]
        if isinstance(val, (dbus.Dictionary, dict)):
            return dict([(fixups.base_to_python(x), fixups.base_to_python(y)) for x, y in val.items()])
        if isinstance(val, dbus.ObjectPath):
            for obj in (NetworkManager, Settings, AgentManager):
                if val == obj.object_path:
                    return obj
            if val.startswith('/org/freedesktop/NetworkManager/'):
                classname = val.split('/')[4]
                classname = {
                    'Settings': 'Connection',
                    'Devices': 'Device',
                }.get(classname, classname)
                try:
                    return globals()[classname](val)
                except ObjectVanished:
                    return None
            if val == '/':
                return None
        if isinstance(val, (dbus.Signature, dbus.String)):
            return six.text_type(val)
        if isinstance(val, dbus.Boolean):
            return bool(val)
        if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)):
            return int(val)
        if isinstance(val, dbus.Byte):
            return six.int2byte(int(val))
        return val 
Example #11
Source File: agent.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        _bluetooth.make_discoverable(True, self.timeout)
        _bluetooth.set_adapter_property("Pairable", dbus.Boolean(1))
        _bluetooth.set_adapter_property("PairableTimeout", dbus.UInt32(0))
        self.agent = Agent(self.client_class, self.timeout, self.path)

        if not self._register():
            self.shutdown()
            return

        self._mainloop.run() 
Example #12
Source File: bluetool.py    From bluetool with GNU General Public License v3.0 5 votes vote down vote up
def make_discoverable(self, value=True, timeout=180):
        try:
            adapter = bluezutils.find_adapter()
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            logger.error(str(error) + "\n")
            return False

        try:
            props = dbus.Interface(
                self._bus.get_object("org.bluez", adapter.object_path),
                "org.freedesktop.DBus.Properties")

            timeout = int(timeout)
            value = int(value)

            if int(props.Get(
                    "org.bluez.Adapter1", "DiscoverableTimeout")) != timeout:
                props.Set(
                    "org.bluez.Adapter1", "DiscoverableTimeout",
                    dbus.UInt32(timeout))

            if int(props.Get("org.bluez.Adapter1", "Discoverable")) != value:
                props.Set(
                    "org.bluez.Adapter1", "Discoverable", dbus.Boolean(value))
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return False

        logger.info("Discoverable: {}".format(value))
        return True 
Example #13
Source File: ipaddress.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def convert(dbus_obj):
    """Converts dbus_obj from dbus type to python type.
    :param dbus_obj: dbus object.
    :returns: dbus_obj in python type.
    """
    _isinstance = partial(isinstance, dbus_obj)
    ConvertType = namedtuple('ConvertType', 'pytype dbustypes')

    pyint = ConvertType(int, (dbus.Byte, dbus.Int16, dbus.Int32, dbus.Int64,
                              dbus.UInt16, dbus.UInt32, dbus.UInt64))
    pybool = ConvertType(bool, (dbus.Boolean, ))
    pyfloat = ConvertType(float, (dbus.Double, ))
    pylist = ConvertType(lambda _obj: list(map(convert, dbus_obj)),
                         (dbus.Array, ))
    pytuple = ConvertType(lambda _obj: tuple(map(convert, dbus_obj)),
                          (dbus.Struct, ))
    types_str = (dbus.ObjectPath, dbus.Signature, dbus.String)
    pystr = ConvertType(str, types_str)

    pydict = ConvertType(
        lambda _obj: dict(list(zip(list(map(convert, dbus_obj.keys())),
                                   list(map(convert, dbus_obj.values()))
                                   ))
                          ),
        (dbus.Dictionary, )
    )

    for conv in (pyint, pybool, pyfloat, pylist, pytuple, pystr, pydict):
        if any(map(_isinstance, conv.dbustypes)):
            return conv.pytype(dbus_obj)
    else:
        return dbus_obj 
Example #14
Source File: networkmanayer.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def mask_to_dbus(mask):
        return dbus.UInt32(mask) 
Example #15
Source File: networkmanayer.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def addr_to_dbus(addr, family):
        if (family == socket.AF_INET):
            return dbus.UInt32(struct.unpack('I', socket.inet_pton(family, addr))[0])
        else:
            return dbus.ByteArray(socket.inet_pton(family, addr)) 
Example #16
Source File: tools.py    From backintime with GNU General Public License v2.0 5 votes vote down vote up
def inhibitSuspend(app_id = sys.argv[0],
                    toplevel_xid = None,
                    reason = 'take snapshot',
                    flags = INHIBIT_SUSPENDING | INHIBIT_IDLE):
    """
    Prevent machine to go to suspend or hibernate.
    Returns the inhibit cookie which is used to end the inhibitor.
    """
    if ON_TRAVIS or dbus is None:
        # no suspend on travis (no dbus either)
        return
    if not app_id:
        app_id = 'backintime'
    try:
        if not toplevel_xid:
            toplevel_xid = 0
    except IndexError:
        toplevel_xid = 0

    for dbus_props in INHIBIT_DBUS:
        try:
            #connect directly to the socket instead of dbus.SessionBus because
            #the dbus.SessionBus was initiated before we loaded the environ
            #variables and might not work
            if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
                bus = dbus.bus.BusConnection(os.environ['DBUS_SESSION_BUS_ADDRESS'])
            else:
                bus = dbus.SessionBus()
            interface = bus.get_object(dbus_props['service'], dbus_props['objectPath'])
            proxy = interface.get_dbus_method(dbus_props['methodSet'], dbus_props['interface'])
            cookie = proxy(*[(app_id, dbus.UInt32(toplevel_xid), reason, dbus.UInt32(flags))[i] for i in dbus_props['arguments']])
            logger.debug('Inhibit Suspend started. Reason: {}'.format(reason))
            return (cookie, bus, dbus_props)
        except dbus.exceptions.DBusException:
            pass
    if isRoot():
        logger.debug("Inhibit Suspend failed because BIT was started as root.")
        return
    logger.warning('Inhibit Suspend failed.') 
Example #17
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 #18
Source File: upower.py    From cpu-g with GNU General Public License v3.0 5 votes vote down vote up
def convert(dbus_obj):
    """Converts dbus_obj from dbus type to python type.
    :param dbus_obj: dbus object.
    :returns: dbus_obj in python type.
    """
    _isinstance = partial(isinstance, dbus_obj)
    ConvertType = namedtuple('ConvertType', 'pytype dbustypes')

    pyint = ConvertType(int, (dbus.Byte, dbus.Int16, dbus.Int32, dbus.Int64,
                              dbus.UInt16, dbus.UInt32, dbus.UInt64))
    pybool = ConvertType(bool, (dbus.Boolean, ))
    pyfloat = ConvertType(float, (dbus.Double, ))
    pylist = ConvertType(lambda _obj: list(map(convert, dbus_obj)),
                         (dbus.Array, ))
    pytuple = ConvertType(lambda _obj: tuple(map(convert, dbus_obj)),
                          (dbus.Struct, ))
    types_str = (dbus.ObjectPath, dbus.Signature, dbus.String)
    pystr = ConvertType(str, types_str)

    pydict = ConvertType(
        lambda _obj: dict(zip(map(convert, dbus_obj.keys()),
                              map(convert, dbus_obj.values())
                              )
                          ),
        (dbus.Dictionary, )
    )

    for conv in (pyint, pybool, pyfloat, pylist, pytuple, pystr, pydict):
        if any(map(_isinstance, conv.dbustypes)):
            return conv.pytype(dbus_obj)
        return dbus_obj 
Example #19
Source File: dirtyagent.py    From HomePWN with GNU General Public License v3.0 5 votes vote down vote up
def RequestPasskey(self, device):
        print("RequestPasskey (%s)" % (device))
        set_trusted(device)
        passkey = ask("Enter passkey: ")
        return dbus.UInt32(passkey) 
Example #20
Source File: agent.py    From launcher with GNU General Public License v3.0 5 votes vote down vote up
def RequestPasskey(self, device):
        print("RequestPasskey (%s)" % (device))
        set_trusted(device)
        passkey = "000000"
        return dbus.UInt32(passkey) 
Example #21
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def mask_to_dbus(mask):
				return dbus.UInt32(mask) 
Example #22
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def addr_to_dbus(addr,family):
				if (family == socket.AF_INET):
						return dbus.UInt32(struct.unpack('I', socket.inet_pton(family,addr))[0])
				else:
						return dbus.ByteArray(socket.inet_pton(family,addr)) 
Example #23
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def base_to_python(val):
				if isinstance(val, dbus.ByteArray):
						return "".join([str(x) for x in val])
				if isinstance(val, (dbus.Array, list, tuple)):
						return [fixups.base_to_python(x) for x in val]
				if isinstance(val, (dbus.Dictionary, dict)):
						return dict([(fixups.base_to_python(x), fixups.base_to_python(y)) for x,y in val.items()])
				if isinstance(val, dbus.ObjectPath):
						for obj in (NetworkManager, Settings, AgentManager):
								if val == obj.object_path:
										return obj
						if val.startswith('/org/freedesktop/NetworkManager/'):
								classname = val.split('/')[4]
								classname = {
									 'Settings': 'Connection',
									 'Devices': 'Device',
								}.get(classname, classname)
								return globals()[classname](val)
						if val == '/':
								return None
				if isinstance(val, (dbus.Signature, dbus.String)):
						return six.text_type(val)
				if isinstance(val, dbus.Boolean):
						return bool(val)
				if isinstance(val, (dbus.Int16, dbus.UInt16, dbus.Int32, dbus.UInt32, dbus.Int64, dbus.UInt64)):
						return int(val)
				if isinstance(val, dbus.Byte):
						return six.int2byte(int(val))
				return val 
Example #24
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_ap_scan(self, value):
        return self.__set_property("ApScan", dbus.UInt32(value)) 
Example #25
Source File: avahi-aliases.py    From ansible-roles with MIT License 5 votes vote down vote up
def publish(self, cname):
        """ Push the cname into the avahi stack
            copied from https://gist.github.com/gdamjan/3168336
        """
        bus = dbus.SystemBus()
        server = dbus.Interface(
            bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER),
            avahi.DBUS_INTERFACE_SERVER
        )
        group = dbus.Interface(
            bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()),
            avahi.DBUS_INTERFACE_ENTRY_GROUP
        )

        cname = self.encode(cname)
        rdata = self.encode_rdata(server.GetHostNameFqdn())
        rdata = avahi.string_to_byte_array(rdata)

        group.AddRecord(
            avahi.IF_UNSPEC,
            avahi.PROTO_UNSPEC,
            dbus.UInt32(0),
            cname,
            Settings.CLASS_IN,
            Settings.TYPE_CNAME,
            Settings.TTL,
            rdata
        )
        group.Commit() 
Example #26
Source File: demo.py    From bt-manager with GNU General Public License v3.0 5 votes vote down vote up
def agent_event_request_pass_key(event, device):
    print '\n========================================================='
    print 'Agent event:', event
    print 'Device:', device
    print 'Using pass code 1234765'
    return dbus.UInt32('1234765')