/* Serializes the supplied publish data into the supplied buffer, ready for sending  */
int MQTTSerialize_publish(unsigned char *buf, int buflen, unsigned char dup, int qos, unsigned char retained, unsigned short packetid, MQTTString topicName, unsigned char *payload, int payloadlen)
/* Serializes the supplied publish data into the supplied buffer, ready for sending  */
int MQTTSerialize_publish(unsigned char *buf, int buflen, unsigned char dup, int qos, unsigned char retained, unsigned short packetid, MQTTString topicName, unsigned char *payload, int payloadlen)
{
    unsigned char* ptr = buf;
    MQTTHeader header = {0};
    int rem_len = 0;
    int rc = 0;
    FUNC_ENTRY;
    if (MQTTPacket_len(rem_len = MQTTSerialize_publishLength(
                           qos, topicName, payloadlen)) > buflen) {
        rc = MQTTPACKET_BUFFER_TOO_SHORT;
        goto exit;
    }
    header.bits.type = PUBLISH;
    header.bits.dup = dup;
    header.bits.qos = qos;
    header.bits.retain = retained;
    writeChar(&ptr, header.byte);
    ptr += MQTTPacket_encode(ptr, rem_len);
    ;
    writeMQTTString(&ptr, topicName);
    if (qos > 0)
        writeInt(&ptr, packetid);
    memcpy(ptr, payload, payloadlen);
    ptr += payloadlen;
    rc = ptr - buf;
exit:
    FUNC_EXIT_RC(rc);
    return rc;
}