概述
使用EMQX搭建MQTT服务,可参考另一个博客https://editor.csdn.net/md/?articleId=121849144
一、建立连接
MQTTPacket_connectData condata = MQTTPacket_connectData_initializer;
client.isconnected = 0;
client.uri = flash_db_syscfg_ptr()->mqtt_uri;
static char cid[20] = { 0 };
/* generate the random client ID */
rt_snprintf(cid, sizeof(cid), "FRYER_%s", sys_info_ptr()->dev_str);
/* config connect param */
memcpy(&client.condata, &condata, sizeof(condata));
client.condata.clientID.cstring = cid;
client.condata.keepAliveInterval = 30;
client.condata.cleansession = 1;
client.condata.username.cstring = MQTT_USERNAME;
client.condata.password.cstring = MQTT_PASSWORD;
/* config MQTT will param. */
static char will_pubtopic[MQTT_TOPIC_LEN]={0};
rt_snprintf(will_pubtopic,MQTT_TOPIC_LEN,MQTT_PUBTOPIC,sys_info_ptr()->dev_str,"will");
client.condata.willFlag = 1;
client.condata.will.qos = 1;
client.condata.will.retained = 0;
client.condata.will.topicName.cstring = will_pubtopic;
client.condata.will.message.cstring = MQTT_WILLMSG;
/* malloc buffer. */
client.buf_size = client.readbuf_size = 1024;
client.buf = rt_calloc(1, client.buf_size);
client.readbuf = rt_calloc(1, client.readbuf_size);
if (!(client.buf && client.readbuf))
{
LOG_E("no memory for MQTT client buffer!");
}
/* set event callback function */
client.connect_callback = mqtt_connect_callback;
client.online_callback = mqtt_online_callback;
client.offline_callback = mqtt_offline_callback;
/* set subscribe table and event callback */
static char subtopic[MQTT_TOPIC_LEN]={0};
rt_snprintf(subtopic,MQTT_TOPIC_LEN,MQTT_SUBTOPIC,sys_info_ptr()->dev_str,"ctrl");
client.messageHandlers[0].topicFilter = subtopic;
client.messageHandlers[0].callback = mqtt_sub_callback;
client.messageHandlers[0].qos = QOS1;
/* set default subscribe event callback */
client.defaultMessageHandler = mqtt_sub_default_callback;
//断开连接后重连时间
client.reconnect_interval = 60000;
//连接超时时间
client.connect_timeout = 10000;
/* run mqtt client */
paho_mqtt_start(&client);
client.connect_callback = mqtt_connect_callback;
client.online_callback = mqtt_online_callback;
client.offline_callback = mqtt_offline_callback;
连接、在线、离线回调函数配置
client.messageHandlers[0].callback = mqtt_sub_callback;
订阅消息回调函数配置
二、消息处理函数
client_cmd_t client_cmd[]={
"run", cmd_run,
"pid", cmd_pid,
"para", cmd_para,
"menu", cmd_menu,
};
static void mqtt_sub_callback(MQTTClient *c, MessageData *msg_data)
{
*((char *)msg_data->message->payload + msg_data->message->payloadlen) = '