初次使用mqtt,然后就去找了一个库libmosquitto.so.1,然后就看了下头文件mosquitto.h,找了一下例子。然后就跑起来了
/* libmosquitto lib init */
mosquitto_lib_init();
/* create a mosquitto client */
mosq = mosquitto_new(device_id, false, mqqtcdev);
if(!mosq)
{
printf("create client failed..\n");
mosquitto_lib_cleanup();
return -1;
}
/* set the username and password */
mosquitto_username_pw_set(mosq, username, password);
/* set log call callback */
// mosquitto_log_callback_set(mosq, my_log_callback);
/* set connect callback */
mosquitto_connect_callback_set(mosq, my_connect_callback);
/* set message callback */
mosquitto_message_callback_set(mosq, my_message_callback);
/* set subscribe callback */
mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
/* connect to the broker */
if(mosquitto_connect(mosq, MQTT_SERVER_ADDR, MQTT_SERVER_PORT, MQQT_KEEPALIVE))
{
fprintf(stderr, "Unable to connect.\n");
return -1;
}
/* 循环处理网络消息 */
mosquitto_loop_forever(mosq, -1, 1);
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
static void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
ret = mosquitto_subscribe(mosq, NULL, "12345/67800/sub", 2);
}
static void my_subscribe_callback(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
{
printf("Subscribed (mid: %d): %d\n", mid, granted_qos[0]);
printf("Subscribed qos_count: %d\n", qos_count);
}
static void my_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
int ret = 0;
printf("mqtt have a message, msglen=%d\n", message->payloadlen);
}
这个吊样mqtt就使用起来了,开始还能正常工作,但是用着用着就订阅不了了,不知道什么原因。后来给订阅的函数加了个mid就好了,也不知道怎么回四,也没时间看,记录一下。看有没有有志青年去探究一下。
int mid = 0;
ret = mosquitto_subscribe(mosq, &mid, "12345/67800/sub", 2);