我对paho mqtt库有一点问题。 我注册了一个回调函数MQTTClient_messageArrived和MQTTClient_connectionLost。
然后在此回调函数中调用MQTTClient_subscribe()或MQTTClient_unsubscribe()。运行此回调函数后。我从MQTTClient_connectionLost收到错误代码(-3)。此外,我打印原因为NULL。
我的问题可能有问题吗?谢谢
这是我的初始化函数和回调函数:
void mqtt_initialize(void){
int rc;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
if(MQTTClient_create(&g_MQTT_client, BROKER_ADDR, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) < 0){
g_mqtt_exist = MQTT_INSTANCE_NOT_EXIST;
} else {
g_mqtt_exist = MQTT_INSTANCE_EXIST;
}
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(g_MQTT_client, NULL, mqtt_connlost_cb, mqtt_arrived_cb, mqtt_delivered_cb);
if ((rc = MQTTClient_connect(g_MQTT_client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
MAIN_PRINT_DEBUG(0, "Failed to connect MQTT broker, return code %d\n", rc);
mqtt_free();
}
/* set subscribe control topic */
MQTTClient_subscribe(g_MQTT_client, "topic_1", MQTT_QOS);
}
int mqtt_arrived_cb(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
int ret = 0;
printf("topic: %s\n", topicName);
if(!strcmp(topicName, "topic_1")){
printf("topic_1\n");
ret = MQTTClient_subscribe(g_MQTT_client, "topic_2", 0);
if (ret < 0){
printf("mqtt operation fail\n");
}
}
return 1;
}
void mqtt_connlost_cb(void *context, char *cause)
{
MAIN_PRINT_DEBUG(0, "\n MQTT Connection lost\n");
MAIN_PRINT_DEBUG(0," cause: %s\n", cause);
}
答案 0 :(得分:0)
您是否尝试将其他任何客户端连接到具有相同客户端ID的相同代理?如果您失去连接,则可能是这种情况。另外,如果您的回调引发异常,则将导致连接丢失,但是在这种情况下,paho将重新连接。