AWS IoT Device SDK C: MQTT
MQTT 3.1.1 client library
Return to main page ↑
IotMqtt_SerializePublish

Generate a PUBLISH packet from the given parameters.

size_t remainingLength,
uint16_t * pPacketIdentifier,
uint8_t ** pPacketIdentifierHigh,
uint8_t * pBuffer,
size_t bufferSize );
Parameters
[in]pPublishInfoUser-provided PUBLISH information.
[in]remainingLengthremaining length of the packet to be serialized.
[out]pPacketIdentifierThe packet identifier generated for this PUBLISH.
[out]pPacketIdentifierHighWhere the high byte of the packet identifier is written.
[in,out]pBufferUser provide buffer where the PUBLISH packet is written.
[in]bufferSizeSize of the buffer pointed to by pBuffer.
Returns
IOT_MQTT_SUCCESS or IOT_MQTT_BAD_PARAMETER.
Note
pBuffer must be allocated by caller.
This call is part of serializer API used for implementing light-weight MQTT client.

Example

// Example code below shows how IotMqtt_SerializePublish() should be used to serialize
// MQTT Publish packet and send it to broker.
// Example uses static memory, but dynamically allocated memory can be used as well.
#define mqttexampleSHARED_BUFFER_SIZE 100
static ucSharedBuffer[mqttexampleSHARED_BUFFER_SIZE];
void sendUnsubscribePacket( int xMQTTSocket )
{
IotMqttError_t xResult;
IotMqttPublishInfo_t xMQTTPublishInfo;
size_t xRemainingLength = 0;
size_t xPacketSize = 0;
size_t xSentBytes = 0;
uint16_t usPacketIdentifier;
uint8_t * pusPacketIdentifierHigh;
// Initialize Publish parameters. Details are out of scope for this example.
// It will involve setting QOS, topic filter, topic filter length, payload
// payload length.
_initializePublish( &xMQTTPublishInfo );
// Find out length of Publish packet size.
xResult = IotMqtt_GetPublishPacketSize( &xMQTTPublishInfo, &xRemainingLength, &xPacketSize );
// Make sure the packet size is less than static buffer size
IotMqtt_Assert( xPacketSize < mqttexampleSHARED_BUFFER_SIZE );
xResult = IotMqtt_SerializePublish( &xMQTTPublishInfo,
xRemainingLength,
&usPacketIdentifier,
&pusPacketIdentifierHigh,
ucSharedBuffer,
xPacketSize );
// xMQTTSocket here is posix socket created and connected to MQTT broker outside of this function.
xSentBytes = send( xMQTTSocket, ( void * ) ucSharedBuffer, xPacketSize, 0 );
IotMqtt_Assert( xSentBytes == xPacketSize );
}