C语言MQTT库MQTTPacket.c使用,尤其接收

参考: https://blog.csdn.net/ai5945fei/article/details/89332928

开启订阅

bool MQTT_Subscribe(char *subscribe)
{
    int len;
    int req_qos = 0;
    u8 buf[512];
    MQTTString topicString = MQTTString_initializer;
    topicString.cstring = subscribe;
    len = MQTTSerialize_subscribe(buf, sizeof(buf), 0, MQTT_packid++, 1, &topicString, &req_qos);
    _socket.Write((char*)buf, len);
    len = _socket.Read((char*)buf, 512);
    if (len >= 5 && (memcmp("\x90\x03", buf, 2) == 0))
    {
        if ((buf[4] & 0x80) != 0x80)
        {
            return true;
        }
    }
    return false;
}

主动发出推送

bool MQTT_Publish(char *topic, char *str)
{
 
    u8 fifo[512];
    int outLen = 0;
    MQTTString topicString = MQTTString_initializer;
    topicString.cstring = topic;
    int len = MQTTSerialize_publish(fifo, 512, 0, 0, 0, MQTT_packid++, topicString, (u8*)str, strlen(str));
 
    _socket.Write((char*)fifo, len);
 
    return false;
}

 

接收到订阅数据

    int len = _socket.Read(rxfifo, 512);
    if (len >= 2)
    {
        if ((rxfifo[0] & 0xF0) == 0x30)//收到发布的消息
        {
            u8 dup;
            int qos;
            u8 retanined;
            u16 msgid;
            MQTTString receiveTopic;
            u8 *payload;
            int payloadLen;
            int ret = MQTTDeserialize_publish(&dup, &qos, &retanined, &msgid, &receiveTopic, &payload, &payloadLen, (u8*)rxfifo, len);
            if (ret)
            {
                char topic[100];
                char data[512];
                memcpy(topic, receiveTopic.lenstring.data, receiveTopic.lenstring.len);
                topic[receiveTopic.lenstring.len] = 0;
 
                memcpy(data, payload, payloadLen);
                data[payloadLen] = 0;
                printf_s("发序列化成功 topic[%s] payload[%s]\r\n", topic, data);
            }
        }
    }

注意:反序列化函数输出值  主题名(receiveTopic.lenstring.data)和主题的数据部分(payload)地址指向原始数据空间(rxfifo数组)中的某一个位置,结算后拷贝出来,不要对上述两个值执行写操作,以免数据破坏。

 

posted on 2020-03-09 19:38  覃隆强  阅读(5361)  评论(0编辑  收藏  举报