如何在 CycloneDDS 中为发布者创建监听器?

How to create listener for publisher in CycloneDDS?

我正在尝试为 cyclonedds 中的发布者使用监听器。但 CycloneDDS 上没有任何示例。 有人可以解释如何在 code 中使用它们吗?

从上面link,the publisher sending data part

对于这个例子,我们希望订阅者能够实际阅读 我们的信息。这并不总是必要的。还有就是这样 这里所做的只是为了说明最简单的方法。它不是 但是,真的建议在轮询循环中等待。

请查看 Listeners 和 WaitSets 以获得更好的效果 解决方案,尽管有些更复杂。

    std::cout << "=== [Publisher] Waiting for subscriber." << std::endl;
    while (writer.publication_matched_status().current_count() == 0) { // how to use a listener here? 
        std::this_thread::sleep_for(std::chrono::milliseconds(20));
    }

    HelloWorldData::Msg msg(1, "Hello World");
    writer.write(msg);

等待订阅者停止以确保它收到了通常不需要的消息,不建议在轮询循环中这样做。

    std::cout << "=== [Publisher] Waiting for sample to be accepted." << std::endl;
    while (writer.publication_matched_status().current_count() > 0) {// how to use a listener here? 
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }

侦听器安装者:

dds_listener_t *l = dds_create_listener (...);
dds_lset_...
dds_set_listener (entity, l);

其中“dds_lset_...”代表设置您要安装的侦听器回调,例如,“dds_lset_publication_matched”。它不会帮助您 等待 直到事件发生,您只会得到一个回调。您当然可以等待条件变量上的触发器(或将字节写入管道或...)并使用回调生成该触发器。

使用等待集,您可以使用 DDS API 来等待事件。例如,您可以将发布者中的轮询循环替换为:

dds_entity_t ws = dds_create_waitset (participant);
// The third argument of attach() is how the entity is
// identified in the output from wait().  Here, we know
// so any value will do.
dds_waitset_attach (ws, writer, 0);
// Wait() only returns once something triggered, and
// here there is only a single entity attached to it,
// with the status mask set to the only event we want
// to wait for, so an infinite timeout and ignoring
// the return value or list of triggered suffices for
// the example.
(void) dds_waitset_wait (ws, NULL, 0, DDS_INFINITY);

如果我“真正”这样做,我会添加错误检查并检查等待调用的结果。只有在非常有限的情况下,就像这个例子,你可以不用检查任何东西。