Python dbus.Byte() Examples

The following are 28 code examples of dbus.Byte(). 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: gatt_linux.py    From gatt-python with MIT License 6 votes vote down vote up
def write_value(self, value, offset=0):
        """
        Attempts to write a value to the characteristic.

        Success or failure will be notified by calls to `write_value_succeeded` or `write_value_failed` respectively.

        :param value: array of bytes to be written
        :param offset: offset from where to start writing the bytes (defaults to 0)
        """
        bytes = [dbus.Byte(b) for b in value]

        try:
            self._object.WriteValue(
                bytes,
                {'offset': dbus.UInt16(offset, variant_level=1)},
                reply_handler=self._write_value_succeeded,
                error_handler=self._write_value_failed,
                dbus_interface='org.bluez.GattCharacteristic1')
        except dbus.exceptions.DBusException as e:
            self._write_value_failed(self, error=e) 
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: 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 #6
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 #7
Source File: other_nm.py    From python-eduvpn-client with GNU General Public License v3.0 5 votes vote down vote up
def cert_to_dbus(cert):
        if not isinstance(cert, bytes):
            if not cert.startswith('file://'):
                cert = 'file://' + cert
            cert = cert.encode('utf-8') + b'\0'
        return [dbus.Byte(x) for x in cert]


# Turn NetworkManager and Settings into singleton objects 
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 mac_to_dbus(mac):
        return [dbus.Byte(int(x, 16)) for x in mac.split(':')] 
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 ssid_to_dbus(ssid):
        if isinstance(ssid, six.text_type):
            ssid = ssid.encode('utf-8')
        return [dbus.Byte(x) for x in ssid] 
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: 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 #12
Source File: networkmanayer.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def mac_to_dbus(mac):
        return [dbus.Byte(int(x, 16)) for x in mac.split(':')] 
Example #13
Source File: networkmanayer.py    From my-weather-indicator with MIT License 5 votes vote down vote up
def ssid_to_dbus(ssid):
        if isinstance(ssid, unicode):
            ssid = ssid.encode('utf-8')
        return [dbus.Byte(x) for x in ssid] 
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: 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 #16
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 #17
Source File: cpu_temperature.py    From python-bluezero with MIT License 5 votes vote down vote up
def cpu_temp_sint16(value):
    answer = []
    value_int16 = sint16(value[0])
    for bytes in value_int16:
        answer.append(dbus.Byte(bytes))

    return answer 
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: cputemp.py    From cputemp with MIT License 5 votes vote down vote up
def ReadValue(self, options):
        value = []
        desc = self.UNIT_DESCRIPTOR_VALUE

        for c in desc:
            value.append(dbus.Byte(c.encode()))

        return value 
Example #20
Source File: cputemp.py    From cputemp with MIT License 5 votes vote down vote up
def ReadValue(self, options):
        value = []

        if self.service.is_farenheit(): val = "F"
        else: val = "C"
        value.append(dbus.Byte(val.encode()))

        return value 
Example #21
Source File: cputemp.py    From cputemp with MIT License 5 votes vote down vote up
def ReadValue(self, options):
        value = []
        desc = self.TEMP_DESCRIPTOR_VALUE

        for c in desc:
            value.append(dbus.Byte(c.encode()))

        return value 
Example #22
Source File: cputemp.py    From cputemp with MIT License 5 votes vote down vote up
def get_temperature(self):
        value = []
        unit = "C"

        cpu = CPUTemperature()
        temp = cpu.temperature
        if self.service.is_farenheit():
            temp = (temp * 1.8) + 32
            unit = "F"

        strtemp = str(round(temp, 1)) + " " + unit
        for c in strtemp:
            value.append(dbus.Byte(c.encode()))

        return value 
Example #23
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def cert_to_dbus(cert):
				if not isinstance(cert, bytes):
						if not cert.startswith('file://'):
								cert = 'file://' + cert
						cert = cert.encode('utf-8') + b'\0'
				return [dbus.Byte(x) for x in cert]

# Turn NetworkManager and Settings into singleton objects 
Example #24
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def mac_to_dbus(mac):
				return [dbus.Byte(int(x, 16)) for x in mac.split(':')] 
Example #25
Source File: NetworkManager.py    From AstroBox with GNU Affero General Public License v3.0 5 votes vote down vote up
def ssid_to_dbus(ssid):
				if isinstance(ssid, six.text_type):
						ssid = ssid.encode('utf-8')
				return [dbus.Byte(x) for x in ssid] 
Example #26
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 #27
Source File: test_gatt.py    From pylgbst with MIT License 5 votes vote down vote up
def test_one(self):
        log.debug("")
        manager = DeviceManagerMock("hci0")
        obj = CustomDevice("AA", manager)

        def callback(handle, value):
            log.debug("%s: %s", type(value), str2hex(value))
            if sys.version_info[0] == 2:
                self.assertEquals("0f0004020126000000001000000010", str2hex(value))

        obj.set_notific_handler(callback)
        arr = "dbus.Array([dbus.Byte(15), dbus.Byte(0), dbus.Byte(4), dbus.Byte(2), dbus.Byte(1), dbus.Byte(38), " \
              "dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(16), dbus.Byte(0), dbus.Byte(0), " \
              "dbus.Byte(0), dbus.Byte(16)], signature=dbus.Signature('y'), variant_level=1)"
        obj.characteristic_value_updated(None, arr if sys.version_info[0] == 2 else bytes(arr, 'ascii')) 
Example #28
Source File: notify2.py    From scudcloud with MIT License 5 votes vote down vote up
def set_hint_byte(self, key, value):
        """Set a hint with a dbus byte value. The input value can be an
        integer or a bytes string of length 1.
        """
        self.hints[key] = dbus.Byte(value)