Python dbus.String() Examples

The following are 30 code examples of dbus.String(). 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: spotrec.py    From SpotRec with MIT License 6 votes vote down vote up
def on_playing_uri_changed(self, Player, three, four):
        #log.debug("uri changed event")

        # Update Metadata
        self.update_metadata()

        # Update track & trackid

        self.trackid2 = self.metadata.get(dbus.String(u'mpris:trackid'))
        if self.trackid != self.trackid2:
            # Update trackid
            self.trackid = self.trackid2
            # Update track name
            self.track = self.get_track(self.metadata)
            # Trigger event method
            self.playing_song_changed()

        # Update playback status

        self.playbackstatus2 = self.iface.Get(Player, "PlaybackStatus")

        if self.playbackstatus != self.playbackstatus2:
            self.playbackstatus = self.playbackstatus2

            self.playbackstatus_changed() 
Example #3
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 #4
Source File: interface.py    From bt-manager with GNU General Public License v3.0 6 votes vote down vote up
def translate_to_dbus_type(typeof, value):
    """
    Helper function to map values from their native Python types
    to Dbus types.

    :param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
    :param value: Value to assign using type 'typeof'
    :return: 'value' converted to type 'typeof'
    :rtype: typeof
    """
    if ((isinstance(value, types.UnicodeType) or
         isinstance(value, str)) and typeof is not dbus.String):
        # FIXME: This is potentially dangerous since it evaluates
        # a string in-situ
        return typeof(eval(value))
    else:
        return typeof(value) 
Example #5
Source File: nmcli.py    From baremetal-deploy with Apache License 2.0 6 votes vote down vote up
def dict_to_string(self, d):
        # Try to trivially translate a dictionary's elements into nice string
        # formatting.
        dstr = ""
        for key in d:
            val = d[key]
            str_val = ""
            add_string = True
            if isinstance(val, dbus.Array):
                for elt in val:
                    if isinstance(elt, dbus.Byte):
                        str_val += "%s " % int(elt)
                    elif isinstance(elt, dbus.String):
                        str_val += "%s" % elt
            elif isinstance(val, dbus.Dictionary):
                dstr += self.dict_to_string(val)
                add_string = False
            else:
                str_val = val
            if add_string:
                dstr += "%s: %s\n" % (key, str_val)
        return dstr 
Example #6
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 #7
Source File: i3-appmenu-service.py    From i3-hud-menu with MIT License 5 votes vote down vote up
def GetMenuForWindow(self, windowId):
    if windowId in self.window_dict:
      sender, menuObjectPath = self.window_dict[windowId]
      return [dbus.String(sender), dbus.ObjectPath(menuObjectPath)] 
Example #8
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_WFDIEs(self, parameter):
        self.__set_property(dbus.String("WFDIEs"), dbus.Array(parameter, "y")) 
Example #9
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 #10
Source File: advertisement.py    From cputemp with MIT License 5 votes vote down vote up
def get_properties(self):
        properties = dict()
        properties["Type"] = self.ad_type

        if self.local_name is not None:
            properties["LocalName"] = dbus.String(self.local_name)

        if self.service_uuids is not None:
            properties["ServiceUUIDs"] = dbus.Array(self.service_uuids,
                                                    signature='s')
        if self.solicit_uuids is not None:
            properties["SolicitUUIDs"] = dbus.Array(self.solicit_uuids,
                                                    signature='s')
        if self.manufacturer_data is not None:
            properties["ManufacturerData"] = dbus.Dictionary(
                self.manufacturer_data, signature='qv')

        if self.service_data is not None:
            properties["ServiceData"] = dbus.Dictionary(self.service_data,
                                                        signature='sv')
        if self.include_tx_power is not None:
            properties["IncludeTxPower"] = dbus.Boolean(self.include_tx_power)

        if self.local_name is not None:
            properties["LocalName"] = dbus.String(self.local_name)

        return {LE_ADVERTISEMENT_IFACE: properties} 
Example #11
Source File: advertisement.py    From cputemp with MIT License 5 votes vote down vote up
def add_local_name(self, name):
        if not self.local_name:
            self.local_name = ""
        self.local_name = dbus.String(name) 
Example #12
Source File: __init__.py    From launcher with GNU General Public License v3.0 5 votes vote down vote up
def print_normal(self,address, properties):
        print("[ " + address + " ]")

        for key in properties.keys():
            value = properties[key]
            if type(value) is dbus.String:
                value = unicode(value).encode('ascii', 'replace')
            if (key == "Class"):
                print("    %s = 0x%06x" % (key, value))
            else:
                print("    %s = %s" % (key, value))

        print()

	properties["Logged"] = True 
Example #13
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 #14
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_capabilities(self):
        return self.__get_property(dbus.String("Capabilities")) 
Example #15
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 #16
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 #17
Source File: spotrec.py    From SpotRec with MIT License 5 votes vote down vote up
def __init__(self):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        try:
            bus = dbus.SessionBus()
            player = bus.get_object(self.dbus_dest, self.dbus_path)
            self.iface = dbus.Interface(player, "org.freedesktop.DBus.Properties")
            self.update_metadata()
        except DBusException:
            log.error("Failed to connect to Spotify. (Maybe it's not running yet?)")
            sys.exit(1)
            pass

        self.track = self.get_track(self.metadata)
        self.trackid = self.metadata.get(dbus.String(u'mpris:trackid'))
        self.playbackstatus = self.iface.Get(self.mpris_player_string, "PlaybackStatus")

        self.iface.connect_to_signal("PropertiesChanged", self.on_playing_uri_changed)

        class DBusListenerThread(Thread):
            def run(self2):
                # Run the GLib event loop to process DBus signals as they arrive
                self.glibloop = GLib.MainLoop()
                self.glibloop.run()

                # run() blocks this thread. This gets printed after it's dead.
                log.info(f"[{app_name}] GLib Loop thread killed")

        dbuslistener = DBusListenerThread()
        dbuslistener.start()

        log.info(f"[{app_name}] Spotify DBus listener started")

        log.info(f"[{app_name}] Current song: " + self.track)
        log.info(f"[{app_name}] Current state: " + self.playbackstatus)

    # TODO: this is a dirty solution (uses cmdline instead of python for now) 
Example #18
Source File: spotrec.py    From SpotRec with MIT License 5 votes vote down vote up
def update_metadata(self):
        self.metadata = self.iface.Get(self.mpris_player_string, "Metadata")

        self.metadata_artist = ", ".join(self.metadata.get(dbus.String(u'xesam:artist')))
        self.metadata_album = self.metadata.get(dbus.String(u'xesam:album'))
        self.metadata_trackNumber = str(self.metadata.get(dbus.String(u'xesam:trackNumber'))).zfill(2)
        self.metadata_title = self.metadata.get(dbus.String(u'xesam:title')) 
Example #19
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 #20
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_debug_level(self):
        return self.__get_property(dbus.String("DebugLevel")) 
Example #21
Source File: CameraStream.py    From rpisurv with GNU General Public License v2.0 5 votes vote down vote up
def set_videopos(self,new_coordinates):
        logger.debug('CameraStream: ' + self.name + ' Set new position for ' + self.name + ' with new coordinates: + ' + str(new_coordinates) + ' on dbus interface')
        if platform.system() == "Linux":
            if self.dbusconnection is not None:
                self.dbusconnection.VideoPosWrapper((ObjectPath('/not/used'), String(" ".join(map(str,new_coordinates)))))
            else:
                logger.error('CameraStream: ' + self.name + ' has no dbus connection, probably because omxplayer crashed because it can not connect to this stream. As a result we could not change its videopos dynamically for this stream at this time.') 
Example #22
Source File: player.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _from_dbus_type(fn):
    def from_dbus_type(dbusVal):
        def from_dbus_dict(dbusDict):
            d = dict()
            for dbusKey, dbusVal in dbusDict.items():
                d[from_dbus_type(dbusKey)] = from_dbus_type(dbusVal)
            return d

        typeUnwrapper = {
            dbus.types.Dictionary: from_dbus_dict,
            dbus.types.Array: lambda x: list(map(from_dbus_type, x)),
            dbus.types.Double: float,
            dbus.types.Boolean: bool,
            dbus.types.Byte: int,
            dbus.types.Int16: int,
            dbus.types.Int32: int,
            dbus.types.Int64: int,
            dbus.types.UInt32: int,
            dbus.types.UInt64: int,
            dbus.types.ByteArray: str,
            dbus.types.ObjectPath: str,
            dbus.types.Signature: str,
            dbus.types.String: str
        }
        try:
            return typeUnwrapper[type(dbusVal)](dbusVal)
        except KeyError:
            return dbusVal

    def wrapped(fn, self, *args, **kwargs):
            return from_dbus_type(fn(self, *args, **kwargs))

    return decorator(wrapped, fn)


# CLASSES 
Example #23
Source File: player.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_aspect_mode(self, mode):
        """
        Set the aspect mode of the video

        Args:
            mode (str): One of ("letterbox" | "fill" | "stretch")
        """
        self._player_interface.SetAspectMode(ObjectPath('/not/used'), String(mode)) 
Example #24
Source File: player.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_video_pos(self, x1, y1, x2, y2):
        """
        Set the video position on the screen

        Args:
            x1 (int): Top left x coordinate (px)
            y1 (int): Top left y coordinate (px)
            x2 (int): Bottom right x coordinate (px)
            y2 (int): Bottom right y coordinate (px)
        """
        position = "%s %s %s %s" % (str(x1),str(y1),str(x2),str(y2))
        self._player_interface.VideoPos(ObjectPath('/not/used'), String(position)) 
Example #25
Source File: player.py    From python-omxplayer-wrapper with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_video_crop(self, x1, y1, x2, y2):
        """
        Args:
            x1 (int): Top left x coordinate (px)
            y1 (int): Top left y coordinate (px)
            x2 (int): Bottom right x coordinate (px)
            y2 (int): Bottom right y coordinate (px)
        """
        crop = "%s %s %s %s" % (str(x1),str(y1),str(x2),str(y2))
        self._player_interface.SetVideoCropPos(ObjectPath('/not/used'), String(crop)) 
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_pin_code(event, device):
    print '\n========================================================='
    print 'Agent event:', event
    print 'Device:', device
    print 'Enter PIN 1234 on device'
    return dbus.String('1234') 
Example #27
Source File: test_bt_bus.py    From bt-manager with GNU General Public License v3.0 5 votes vote down vote up
def StartDiscovery(self):
        self._props[dbus.String(u'Discovering')] = \
            dbus.Boolean(True, variant_level=1) 
Example #28
Source File: test_bt_bus.py    From bt-manager with GNU General Public License v3.0 5 votes vote down vote up
def StopDiscovery(self):
        self._props[dbus.String(u'Discovering')] = \
            dbus.Boolean(False, variant_level=1) 
Example #29
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_WFDIEs(self):
        return self.__get_property(dbus.String("WFDIEs")) 
Example #30
Source File: dbuswpasupplicant.py    From pywificontrol with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_debug_level(self, parameter):
        self.__set_property(dbus.String("DebugLevel"), dbus.String(parameter))