return -ENODATA;
}
/* Compute message size
- * Packet ID is 2 bytes long. There is no "message size" field in the publish packet, as the
- * message size can be computed by substracting the topic string size and packet id size from
- * the packet "remaining length" field. */
- remaining_length = 2 + pkt->message_size;
+ * There is no "message size" field in the publish packet, as the message size can be computed by
+ * substracting the topic string size and packet id size from the packet "remaining length" field.
+ */
+ remaining_length = pkt->message_size;
+ /* Packet ID is 2 bytes long. If QoS is 0, then the packet must not include a packet ID */
+ if (pkt->topic.QoS != 0) {
+ remaining_length += 2;
+ }
/* Topic is mandatory */
if (pkt->topic.name == NULL) {
return -EINVAL;
/* Topic is mandatory */
len += mqtt_pack_str((buf + len), pkt->topic.name, topic_len);
/* Packet ID */
- tmp_packet_id = htons(pkt->packet_id);
- memcpy((buf + len), &tmp_packet_id, 2);
- len += 2;
+ if (pkt->topic.QoS != 0) {
+ tmp_packet_id = htons(pkt->packet_id);
+ memcpy((buf + len), &tmp_packet_id, 2);
+ len += 2;
+ }
/* Add optionnal application message */
if (pkt->message_size != 0) {
memcpy((buf + len), pkt->application_message, pkt->message_size);
topic_len = ntohs(tmp);
pkt->topic.name = (char*)(buf + idx + 2);
idx += topic_len + 2;
- if ((idx + 2) > size) {
+ /* Does it fit in the remaining length ? */
+ tmp = idx;
+ if (pkt->topic.QoS != 0) {
+ tmp += 2;
+ }
+ if (tmp > size) {
return -EPROTO;
}
/* Decode packet ID */
- idx += 2;
+ if (pkt->topic.QoS != 0) {
memcpy(&tmp, (buf + idx), 2);
pkt->packet_id = ntohs(tmp);
+ idx += 2;
+ }
/* Get application message */
pkt->message_size = size - idx;
if (pkt->message_size != 0) {