Python Dbus:如何导出接口属性

6 投票
2 回答
6609 浏览
提问于 2025-04-16 04:18

在所有关于Python dbus的文档中,都会有关于如何导出对象、接口和信号的信息,但没有关于如何导出接口属性的内容。

有没有人知道该怎么做呢?

2 个回答

2

这个例子之所以不工作,我觉得是因为:

'''
可以通过调用 org.freedesktop.DBus.Introspectable.Introspect 来确定可用的属性以及它们是否可以被写入,具体可以参考“org.freedesktop.DBus.Introspectable”这一部分。
'''

而在检查数据中,属性是缺失的:

我使用的是 dbus-python-1.1.1 版本。

13

在Python中实现D-Bus属性是完全可行的!D-Bus属性其实就是某个特定接口上的方法,具体来说就是org.freedesktop.DBus.Properties。这个接口的定义可以在D-Bus规范中找到;你可以像实现其他D-Bus接口一样在你的类中实现它:

# Untested, just off the top of my head

import dbus

MY_INTERFACE = 'com.example.Foo'

class Foo(dbus.service.object):
    # …

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='ss', out_signature='v')
    def Get(self, interface_name, property_name):
        return self.GetAll(interface_name)[property_name]

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='s', out_signature='a{sv}')
    def GetAll(self, interface_name):
        if interface_name == MY_INTERFACE:
            return { 'Blah': self.blah,
                     # …
                   }
        else:
            raise dbus.exceptions.DBusException(
                'com.example.UnknownInterface',
                'The Foo object does not implement the %s interface'
                    % interface_name)

    @dbus.service.method(interface=dbus.PROPERTIES_IFACE,
                         in_signature='ssv'):
    def Set(self, interface_name, property_name, new_value):
        # validate the property name and value, update internal state…
        self.PropertiesChanged(interface_name,
            { property_name: new_value }, [])

    @dbus.service.signal(interface=dbus.PROPERTIES_IFACE,
                         signature='sa{sv}as')
    def PropertiesChanged(self, interface_name, changed_properties,
                          invalidated_properties):
        pass

虽然dbus-python应该能让实现属性变得更简单,但目前这个库的维护情况并不是很好。

如果有人愿意参与进来,帮助修复这些问题,那就太好了。即使只是把这个常见问题的扩展版本添加到文档中,也是一个不错的开始。如果你感兴趣,可以把补丁发送到D-Bus邮件列表,或者附加到在FreeDesktop的bug追踪器上针对dbus-python提交的bug.

撰写回答