mongoose7 mqtt例程
时间: 2023-12-06 07:03:46 浏览: 93
以下是使用mongoose7库实现MQTT协议的例程:
```c
#include "mgos.h"
#include "mgos_mqtt.h"
static void mqtt_ev_handler(struct mg_connection *nc, int ev, void *ev_data, void *user_data) {
struct mg_mqtt_message *msg = (struct mg_mqtt_message *) ev_data;
switch (ev) {
case MG_EV_MQTT_CONNACK:
mgos_mqtt_pub("/my/topic", "hello", 5, 0, false);
break;
case MG_EV_MQTT_SUBACK:
LOG(LL_INFO, ("Subscription %d acknowledged", msg->message_id));
break;
case MG_EV_MQTT_PUBLISH:
LOG(LL_INFO, ("Got publish [%.*s]", (int) msg->payload.len, msg->payload.p));
break;
default:
break;
}
}
enum mgos_app_init_result mgos_app_init(void) {
struct mg_connection *nc = mgos_mqtt_connect("mqtt://test.mosquitto.org", mqtt_ev_handler, NULL);
if (nc == NULL) {
return MGOS_APP_INIT_ERROR;
}
mgos_mqtt_sub("/my/topic", NULL);
return MGOS_APP_INIT_SUCCESS;
}
```
这个例程连接到了test.mosquitto.org的MQTT服务器,并订阅了/my/topic主题。当连接成功后,它会发布一条消息到/my/topic主题。当收到订阅的消息时,它会打印出消息内容。
阅读全文