【问题标题】:Async mosquitto client trying to re-connect with mosquitto broker异步 mosquitto 客户端尝试与 mosquitto 代理重新连接
【发布时间】:2021-09-07 08:32:04
【问题描述】:

尝试实现一个基于 mosquitto MQTT 代理的异步客户端,在后台永久运行。我的目的是创建一个能够连接/重新连接到代理的客户端,以防代理在某个时间脱机。我希望所有连接/重新连接逻辑都由 mosquitto 回调(事件驱动)管理。但是,如果您在代理最初停止(离线)时尝试运行客户端,则此代码不会尝试连接到代理:

struct mosquitto *broker;
char ip[INET_ADDRSTRLEN]; // broker ip address
int port; // 1883
int keepalive; // 60
bool running = true;


int main(void)
{
    mosquitto_lib_init();
    broker = mosquitto_new(NULL, true, NULL);

    mosquitto_connect_callback_set(broker, on_connect_callback);
    mosquitto_disconnect_callback_set(broker, on_disconnect_callback);
    mosquitto_message_callback_set(broker, on_message_callback);

    mosquitto_connect_async(broker, ip, port, keepalive);
    mosquitto_loop_start(broker);


    while(running) {
        pause();
    }
}

经过一番测试,更换

mosquitto_connect_async(broker, ip, port, keepalive);

通过 while 循环轮询 mosquitto_connect_async 函数返回的第一个成功:

bool connected_to_broker = false;
while (!connected_to_broker) {
    rc = mosquitto_connect_async(broker, ip, port, keepalive);
    if (rc == MOSQ_ERR_SUCCESS) {
        connected_to_broker = true;
    } else {
        sleep(retry_timeout);
    }
}

在while循环之后,似乎所有的源代码都可以基于mosquitto回调了。

这是处理这种情况的预期方法吗?还是应该以不同的方式进行管理?谢谢!

【问题讨论】:

  • 请分享所有相关代码,尤其是变量和回调的定义。首先你有一个变量broker(实际上是一个客户端实例),然后你传递了一些其他实例cli_ctx.broker
  • 对不起,我编辑了相关的源代码。回调的内容不相关,只是一个日志看看是否被调用。
  • 如果回调只输出日志消息,那么重连逻辑在哪里?

标签: asynchronous background client mqtt mosquitto


【解决方案1】:

您不必进行多次连接尝试。您的问题是第一次尝试因同样的原因而失败,但尚未触发任何回调,因为通信线程尚未启动。

如果您检查mosquitto_connect_async 的返回值,您将看到它是MOSQ_ERR_ERRNO,其中errno 被设置为ECONNREFUSED (111)。

如果在您第一次尝试连接之前调用了 mosquitto_loop_start,则应触发断开回调 - 也可以使用 rc == MOSQ_ERR_ERRNOerrno == ECONNREFUSED

【讨论】:

  • 天啊。谢谢!我在谷歌上搜索示例,在所有示例中,mosquitto_connect_async 都被称为 before mosquitto_loop_start。只需按照建议交换顺序,而不使用任何 while 循环,就可以使事情按预期发生。非常感谢您的回答,这非常有帮助! :-)
  • 在 mosquitto_connect_async() 之前调用 mosquitto_loop_start() 对我来说是有问题的 - 如果您再次尝试连接,它将无法正常工作 - 在我发现此错误并升级到 v2.0.13 之前(据报道该错误已修复在 v2.0.12 中):link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多