Python dbus.Array() Examples

The following are 30 code examples of dbus.Array(). 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: BlinkerBLE.py    From blinker-py with MIT License 7 votes vote down vote up
def response(self, msg):
        if isDebugAll() is True:
            BLINKER_LOG('FFE1 Write: ' + str(msg))

        msg = json.dumps(msg)
        msg = msg + '\n'
        length = len(msg)
        a = []
        b = []
        for i in range(0, length):
            a.append(dbus.Byte(ord(msg[i])))
            b.append(msg[i])
        # if isDebugAll() is True:
        #     BLINKER_LOG(len(msg))
        #     BLINKER_LOG(a)
        #     BLINKER_LOG(b)

        msg = dbus.Array(a, signature=dbus.Signature('y'))
        bleProto.BLE_Response.PropertiesChanged(GATT_CHRC_IFACE, { 'Value': msg }, [])
        # if isDebugAll() is True:
        #     BLINKER_LOG('FFE1 Write: ' + str(msg)) 
Example #2
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 #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_sbc_caps_conversion(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')

        media = bt_manager.SBCAudioCodec(uuid='uuid', path='/endpoint/test')
        config = bt_manager.SBCCodecConfig(bt_manager.SBCChannelMode.ALL,
                                           bt_manager.SBCSamplingFrequency.ALL,
                                           bt_manager.SBCAllocationMethod.ALL,
                                           bt_manager.SBCSubbands.ALL,
                                           bt_manager.SBCBlocks.ALL,
                                           2,
                                           64)
        dbus_config = media._make_config(config)
        self.assertEqual(dbus_config, dbus.Array([dbus.Byte(0xFF),
                                                  dbus.Byte(0xFF),
                                                  dbus.Byte(2),
                                                  dbus.Byte(64)]))
        self.assertEqual(media._parse_config(dbus_config), config) 
Example #5
Source File: GATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def read_raw_value(self, flags=''):
        """
        Return this characteristic's value (if allowed).

        :param flags: "offset": Start offset
                      "device": Device path (Server only)
        :return:

        Possible Errors:    org.bluez.Error.Failed
                            org.bluez.Error.InProgress
                            org.bluez.Error.NotPermitted
                            org.bluez.Error.InvalidValueLength
                            org.bluez.Error.NotAuthorized
                            org.bluez.Error.NotSupported
        """
        return self.characteristic_methods.ReadValue(dbus.Array()) 
Example #6
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 #7
Source File: pulseaudio.py    From pulseaudio-dlna with GNU General Public License v3.0 6 votes vote down vote up
def _connect(self, signals):
        self.bus = self._get_bus()
        self.core = self.bus.get_object(object_path='/org/pulseaudio/core1')
        for sig_name, interface, sig_handler in signals:
            self.bus.add_signal_receiver(sig_handler, sig_name)
            self.core.ListenForSignal(
                interface.format(sig_name), dbus.Array(signature='o'))

        try:
            fallback_sink_path = self.core.Get(
                'org.PulseAudio.Core1', 'FallbackSink',
                dbus_interface='org.freedesktop.DBus.Properties')
            self.fallback_sink = PulseSinkFactory.new(
                self.bus, fallback_sink_path)
        except:
            logger.info(
                'Could not get default sink. Perhaps there is no one set?')

        system_sink_paths = self.core.Get(
            'org.PulseAudio.Core1', 'Sinks',
            dbus_interface='org.freedesktop.DBus.Properties')
        for sink_path in system_sink_paths:
            sink = PulseSinkFactory.new(self.bus, sink_path)
            if sink:
                self.system_sinks.append(sink) 
Example #8
Source File: localGATT.py    From python-bluezero with MIT License 6 votes vote down vote up
def Set(self, interface_name, property_name, value, *args, **kwargs):
        """Standard D-Bus API for setting a property value"""

        try:
            iface_props = self.props[interface_name]
        except KeyError:
            raise dbus.exceptions.DBusException(
                'no such interface ' + interface_name,
                name=self.interface + '.UnknownInterface')

        if property_name not in iface_props:
            raise dbus.exceptions.DBusException(
                'no such property ' + property_name,
                name=self.interface + '.UnknownProperty')

        iface_props[property_name] = value

        self.PropertiesChanged(interface_name,
                               dbus.Dictionary({property_name: value},
                                               signature='sv'),
                               dbus.Array([], signature='s')) 
Example #9
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 #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 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 #11
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 #12
Source File: dbus_tools.py    From python-bluezero with MIT License 5 votes vote down vote up
def str_to_dbusarray(word):
    return dbus.Array([dbus.Byte(ord(letter)) for letter in word], 'y') 
Example #13
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, {}) 
Example #14
Source File: dbus_tools.py    From python-bluezero with MIT License 5 votes vote down vote up
def bytes_to_dbusarray(bytesarray):
    return dbus.Array([dbus.Byte(elem) for elem in bytesarray], 'y') 
Example #15
Source File: advertisement.py    From python-bluezero with MIT License 5 votes vote down vote up
def service_data(self, data):
        for UUID in data:
            self.Set(constants.LE_ADVERTISEMENT_IFACE,
                     'ServiceData',
                     {UUID: dbus.Array(data[UUID], signature='y')}) 
Example #16
Source File: advertisement.py    From python-bluezero with MIT License 5 votes vote down vote up
def GetAll(self, interface_name):
        """Return the advertisement 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.LEAdvertisement1`` otherwise an
        exception is raised.
        """
        if interface_name != constants.LE_ADVERTISEMENT_IFACE:
            raise InvalidArgsException()

        response = {}
        response['Type'] = self.props[interface_name]['Type']
        if self.props[interface_name]['ServiceUUIDs'] is not None:
            response['ServiceUUIDs'] = dbus.Array(
                self.props[interface_name]['ServiceUUIDs'],
                signature='s')
        if self.props[interface_name]['ServiceData'] is not None:
            response['ServiceData'] = dbus.Dictionary(
                self.props[interface_name]['ServiceData'],
                signature='sv')
        if self.props[interface_name]['ManufacturerData'] is not None:
            response['ManufacturerData'] = dbus.Dictionary(
                self.props[interface_name]['ManufacturerData'],
                signature='qv')
        if self.props[interface_name]['SolicitUUIDs'] is not None:
            response['SolicitUUIDs'] = dbus.Array(
                self.props[interface_name]['SolicitUUIDs'],
                signature='s')
        response['IncludeTxPower'] = dbus.Boolean(
            self.props[interface_name]['IncludeTxPower'])

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

        The dictionary has the following keys:

        - Type: the advertisement type.
        - ServiceUUIDS: UUIDs of services to advertise
        - SolicitUUIDS:
        - ManufacturerData: dictionary of manufacturer data
        - ServiceData: dictionary of service data
        - IncludeTxPower:

        """
        properties = dict()
        properties['Type'] = self.ad_type
        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='qay')
        if self.service_data is not None:
            properties['ServiceData'] = dbus.Dictionary(self.service_data,
                                                        signature='say')
        if self.include_tx_power is not None:
            properties['IncludeTxPower'] = dbus.Boolean(self.include_tx_power)
        return {constants.LE_ADVERTISEMENT_IFACE: properties} 
Example #18
Source File: localGATT.py    From python-bluezero with MIT License 5 votes vote down vote up
def Set(self, interface_name, property_name, value, *args, **kwargs):
        """Standard D-Bus API for setting a property value"""

        if property_name not in self.props[constants.GATT_CHRC_IFACE]:
            raise dbus.exceptions.DBusException(
                'no such property ' + property_name,
                name=constants.GATT_CHRC_IFACE + '.UnknownProperty')

        self.props[constants.GATT_CHRC_IFACE][property_name] = value

        return self.PropertiesChanged(interface_name,
                                      dbus.Dictionary({property_name: value},
                                                      signature='sv'),
                                      dbus.Array([], signature='s')) 
Example #19
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 #20
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 #21
Source File: GATT.py    From python-bluezero with MIT License 5 votes vote down vote up
def write_value(self, value, flags=''):
        """
        Issue a request to write the value of the descriptor.

        :param value: DBus byte array
        :param flags: "offset": Start offset
                      "device": Device path (Server only)

        :return:
        """
        self.descriptor_methods.WriteValue(value, dbus.Array(flags)) 
Example #22
Source File: GATT.py    From python-bluezero with MIT License 5 votes vote down vote up
def write_value(self, value, flags=''):
        """
        Write a new value to the characteristic.

        :param value:
        :param flags:
        :return:
        """
        self.characteristic_methods.WriteValue(value, dbus.Array(flags)) 
Example #23
Source File: cpu_temperature.py    From python-bluezero with MIT License 5 votes vote down vote up
def ReadValue(self, options):
        reading = [get_cpu_temperature()]
        self.props[constants.GATT_CHRC_IFACE]['Value'] = reading
        return dbus.Array(
            cpu_temp_sint16(self.props[constants.GATT_CHRC_IFACE]['Value'])
        ) 
Example #24
Source File: cpu_temperature.py    From python-bluezero with MIT License 5 votes vote down vote up
def temperature_cb(self):
        reading = [get_cpu_temperature()]
        print('Getting new temperature',
              reading,
              self.props[constants.GATT_CHRC_IFACE]['Notifying'])
        self.props[constants.GATT_CHRC_IFACE]['Value'] = reading

        self.PropertiesChanged(constants.GATT_CHRC_IFACE,
                               {'Value': dbus.Array(cpu_temp_sint16(reading))},
                               [])
        print('Array value: ', cpu_temp_sint16(reading))
        return self.props[constants.GATT_CHRC_IFACE]['Notifying'] 
Example #25
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 #26
Source File: service.py    From cputemp with MIT License 5 votes vote down vote up
def get_properties(self):
        return {
                GATT_CHRC_IFACE: {
                        'Service': self.service.get_path(),
                        'UUID': self.uuid,
                        'Flags': self.flags,
                        'Descriptors': dbus.Array(
                                self.get_descriptor_paths(),
                                signature='o')
                }
        } 
Example #27
Source File: service.py    From cputemp with MIT License 5 votes vote down vote up
def get_properties(self):
        return {
                GATT_SERVICE_IFACE: {
                        'UUID': self.uuid,
                        'Primary': self.primary,
                        'Characteristics': dbus.Array(
                                self.get_characteristic_paths(),
                                signature='o')
                }
        } 
Example #28
Source File: advertisement.py    From cputemp with MIT License 5 votes vote down vote up
def add_service_data(self, uuid, data):
        if not self.service_data:
            self.service_data = dbus.Dictionary({}, signature="sv")
        self.service_data[uuid] = dbus.Array(data, signature="y") 
Example #29
Source File: advertisement.py    From cputemp with MIT License 5 votes vote down vote up
def add_manufacturer_data(self, manuf_code, data):
        if not self.manufacturer_data:
            self.manufacturer_data = dbus.Dictionary({}, signature="qv")
        self.manufacturer_data[manuf_code] = dbus.Array(data, signature="y") 
Example #30
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}