Mosquitto Broker is receving data partially

296 views Asked by At

I am trying to send a connect packet to the mosquitto MQTT broker. I can establish the connection with broker, but the broker is not completely receiving connect data i.e. wireshark doesnt show MQIspd data in the broker but receiving client ID.

MQTT protocl version is v3.0.

Sending packet via SIM900 GSM/GPRS modem.

What is wrong with the code?

Below is connect packet C code:

#define MQTTCONNECT 1<<4
#define MQTTPUBLISH 3<<4
#define KEEPALIVE 15000

int main()
{
    uint8_t buf[255];
    char *id="MQTT"
    uint8_t var_header[] = {0x00,0x06,0x4d,0x51,0x49,0x73,0x64,0x70,0x03,0x02,0x00,KEEPALIVE/500,0x00,strlen(id);
    uint8_t fixed_header[] = {MQTTCONNECT,12+strlen(id)+2};
    char packet[sizeof(fixed_header)+sizeof(var_header)+strlen(id)];

    memset(packet,0,sizeof(packet));
    memcpy(packet,fixed_header,sizeof(fixed_header));
    //memcpy(packet+sizeof(fixed_header),var_header,sizeof(var_header));
    //memcpy(packet+sizeof(fixed_header)+sizeof(var_header),id,strlen(id));
    //sprintf(buf,"%s\x1A",memcpy(packet+sizeof(fixed_header)+sizeof(var_header),id,strlen(id));
    sprintf(buf,"%s\x1A",memcpy(packet+sizeof(fixed_header)+sizeof(var_header),id,strlen(id)));
    port_write(buf); //write data into the serial port.
    return 0;
}

Thanks.

2

There are 2 answers

0
ppatierno On

As @ralight said, with the memcpy inside sprintf, you are copying into buf only the payload of the message (you aren't copying fixed header and variable header) and in this case the payload contains only the client ID. However I agree with @ralight ... two "buffers" aren't useful.

6
ralight On

Your port_write(buf) will write data from the packet variable starting at packet[sizeof(fixed_header)+sizeof(var_header)]. This is what the sprintf() call is copying to buf and is certainly not what you want. I don't think there is a need to have both a packet and a buf variable, just use one of them and I think it will simplify matters.

Try this instead:

int main()
{
    char *id="MQTT"
    uint8_t var_header[] = {0x00, 0x06, 0x4d, 0x51, 0x49, 0x73, 0x64, 0x70, 0x03, 0x02, 0x00, KEEPALIVE/500, 0x00, strlen(id);
    uint8_t fixed_header[] = {MQTTCONNECT, 12+strlen(id)+2};
    char packet[sizeof(fixed_header)+sizeof(var_header)+strlen(id) + 2];

    memset(packet, 0, sizeof(packet));
    memcpy(packet, fixed_header, sizeof(fixed_header));
    memcpy(packet+sizeof(fixed_header), var_header, sizeof(var_header));
    sprintf(packet+sizeof(fixed_header)+sizeof(var_header), "%s\x1A", id);

    port_write((uint8_t *)packet); //write data into the serial port.

    return 0;
}