我遇到了同样的问题,我找到了解决方法。
如果您的客户端启用了您的特征通知,则以下两行将设置特征当前值,BlueZ 将在堆栈中处理它并通知所有订阅者
gatt_characteristic1_set_value(interface,value);
g_dbus_interface_skeleton_flush(G_DBUS_INTERFACE_SKELETON(interface));
例如,您可以运行一个线程,每 X 秒调用一次此函数,并且您的客户端将每 X 秒收到通知。
编辑:
GattCharacteristic1 是由 gdbus-codegen 从 xml 文件创建的 C DBus 对象。
https://developer.gnome.org/gio/stable/gdbus-codegen.html
为了帮助你,这是我根据 BlueZ API doc 编写的 xml 文件。
<?xml version="1.0" encoding="UTF-8"?>
<node xmlns:doc="http://www.freedesktop.org/dbus/1.0/doc.dtd">
<interface name="org.bluez.GattCharacteristic1">
<property name="UUID" type="s" access="read" />
<property name="Service" type="o" access="read" />
<property name="Value" type="ay" access="read" />
<property name="Notifying" type="b" access="read" />
<property name="Flags" type="as" access="read" />
<method name="ReadValue">
<arg name="options" type="a{sv}" direction="in" />
<arg name="value" type="ay" direction="out" />
</method>
<method name="WriteValue">
<arg name="value" type="ay" direction="in" />
<arg name="options" type="a{sv}" direction="in" />
</method>
<method name="StartNotify"/>
<method name="StopNotify"/>
</interface>
</node>
一旦你有了描述 GATT BlueZ 对象的 xml 文件(名为 org.bluez.GattCharacteristic1.xml),使用 gbus-codegen 生成一个“C DBus 对象”
gdbus-codegen --generate-c-code org_bluez_gatt_characteristic_interface --interface-prefix org.bluez. org.bluez.GattCharacteristic1.xml
现在将 c 和 h 文件添加到您的源代码中
以下几行显示了我如何在 DBus 上创建一个 GATT BlueZ 特征
const char* char_flags[] = {"read", "write", "notify", "indicate", NULL};
GattCharacteristic1* interface = gatt_characteristic1_skeleton_new();
// dbus object properties
gatt_characteristic1_set_uuid(interface,UUID);
gatt_characteristic1_set_service(interface,service_name);
gatt_characteristic1_set_value(interface,value);
gatt_characteristic1_set_notifying(interface,notifying);
gatt_characteristic1_set_flags(interface,flags);
// get handler (for example), please read doc from gdbus-codegen provide above.
g_signal_connect(interface,
"handle_read_value",
G_CALLBACK(dbus_client_on_handle_gatt_characteristic_read_value),
NULL);
// register new interface on object
g_dbus_object_skeleton_add_interface(object,G_DBUS_INTERFACE_SKELETON(interface));
// exports object on manager
g_dbus_object_manager_server_export(server_manager,object);
请根据需要编辑标志。在接口对象上保留一个指针,并使用我在第一个答案中提供的行。 GBus 文档有很好的文档记录,所以我希望你能找到你需要的每一个。