### Initialize MQTT Context Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_init_function.html Demonstrates the setup of transport, buffer, and callback functions required to initialize the MQTT context. ```c // Function for obtaining a timestamp. uint32_t getTimeStampMs(); // Callback function for receiving packets. bool eventCallback( MQTTContext_t * pContext, MQTTPacketInfo_t * pPacketInfo, MQTTDeserializedInfo_t * pDeserializedInfo, MQTTSuccessFailReasonCode_t * pReasonCode, MQTTPropBuilder_t * pSendPropsBuffer, MQTTPropBuilder_t * pGetPropsBuffer ); // Network send. int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes ); // Network receive. int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes ); MQTTContext_t mqttContext; TransportInterface_t transport; MQTTFixedBuffer_t fixedBuffer; // Create a globally accessible buffer which remains in scope for the entire duration // of the MQTT context. uint8_t buffer[ 1024 ]; // Clear context. memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) ); // Set transport interface members. transport.pNetworkContext = &someTransportContext; transport.send = networkSend; transport.recv = networkRecv; transport.writev = NULL; // Set buffer members. fixedBuffer.pBuffer = buffer; fixedBuffer.size = 1024; status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer ); if( status == MQTTSuccess ) { // Do something with mqttContext. The transport and fixedBuffer structs were // copied into the context, so the original structs do not need to stay in scope. // However, the memory pointed to by the fixedBuffer.pBuffer must remain in scope. } ``` -------------------------------- ### Topic Matching Example Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h.html Demonstrates how to use MQTT_MatchTopic to verify if a topic name matches a specific filter. ```c // Variables used in this example. const char * pTopic = "topic/match/1"; const char * pFilter = "topic/#"; MQTTStatus_t status = MQTTSuccess; bool match = false; status = MQTT_MatchTopic( pTopic, strlen( pTopic ), pFilter, strlen( pFilter ), &match ); // Our parameters were valid, so this will return success. assert( status == MQTTSuccess ); // For this specific example, we already know this value is true. This // check is placed here as an example for use with variable topic names. if( match ) { // Application can decide what to do with the matching topic name. } ``` -------------------------------- ### Calculate Publish Packet Size Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_getpublishpacketsize_function.html Example demonstrating the initialization of publish information and the subsequent call to MQTT_GetPublishPacketSize to determine packet size requirements. ```c // Variables used in this example. MQTTStatus_t status; MQTTPublishInfo_t publishInfo = { 0 }; MQTTPropBuilder_t publishProperties = { 0 }; uint16_t topicAliasMax; uint8_t retainAvailable; uint8_t maxQos; size_t remainingLength = 0, packetSize = 0; // Initialize the publish info. publishInfo.qos = MQTTQoS0; publishInfo.pTopicName = "/some/topic/name"; publishInfo.topicNameLength = strlen( publishInfo.pTopicName ); publishInfo.pPayload = "Hello World!"; publishInfo.payloadLength = strlen( "Hello World!" ); // Initialize publish properties (if needed) initializePublishProperties( &publishProperties ); // Validate publish parameters status = MQTT_ValidatePublishParams(&publishInfo, topicAliasMax, retainAvailable, maxQos); // Get the size requirement for the publish packet. status = MQTT_GetPublishPacketSize( &publishInfo, &publishProperties, &remainingLength, &packetSize, maxPacketSize ); if( status == MQTTSuccess ) { // The publish packet can now be sent to the broker. } ``` -------------------------------- ### Serializing an MQTT Unsubscribe Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_serializeunsubscribe_function.html Example demonstrating the initialization of buffers and subscription lists, followed by calculating the packet size and serializing the unsubscribe packet. ```c // Variables used in this example. MQTTStatus_t status; MQTTSubscribeInfo_t subscriptionList[2]; MQTTPropBuilder_t unsubscribeProperties; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[100]; size_t remainingLength = 0, packetSize = 0; uint16_t packetId = 1; // Initialize the fixed buffer. fixedBuffer.pBuffer = buffer; fixedBuffer.size = sizeof( buffer ); // Initialize subscription list. subscriptionList[0].pTopicFilter = "topic/1"; subscriptionList[0].topicFilterLength = strlen("topic/1"); subscriptionList[1].pTopicFilter = "topic/2"; subscriptionList[1].topicFilterLength = strlen("topic/2"); // Initialize properties (optional) // Get size requirement for the unsubscribe packet. status = MQTT_GetUnsubscribePacketSize( subscriptionList, 2, &unsubscribeProperties, &remainingLength, &packetSize ); if( status == MQTTSuccess ) { // Serialize unsubscribe packet. status = MQTT_SerializeUnsubscribe( subscriptionList, 2, &unsubscribeProperties, packetId, remainingLength, &fixedBuffer ); } if( status == MQTTSuccess ) { // The unsubscribe packet has been serialized successfully. // The serialized packet is now ready to be sent to the broker. } ``` -------------------------------- ### Calculating Subscribe Packet Size Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_getsubscribepacketsize_function.html This example demonstrates how to initialize subscription information and properties before calling MQTT_GetSubscribePacketSize to determine the required buffer size. ```c // Variables used in this example. MQTTStatus_t status; MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 }; MQTTPropBuilder_t subscribeProperties = { 0 }; size_t remainingLength = 0, packetSize = 0; // This is assumed to be a list of filters we want to subscribe to. const char * filters[ NUMBER_OF_SUBSCRIPTIONS ]; // Set each subscription. for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ ) { subscriptionList[ i ].qos = MQTTQoS0; // Each subscription needs a topic filter. subscriptionList[ i ].pTopicFilter = filters[ i ]; subscriptionList[ i ].topicFilterLength = strlen( filters[ i ] ); subscriptionList[ i ].noLocalOption = false; subscriptionList[ i ].retainAsPublishedOption = false; subscriptionList[ i ].retainHandlingOption = retainSendOnSub; } // Initialize subscribe properties (if needed) initializeSubscribeProperties( &subscribeProperties ); // Get the size requirement for the subscribe packet. status = MQTT_GetSubscribePacketSize( &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &subscribeProperties, &remainingLength, &packetSize, maxPacketSize ); if( status == MQTTSuccess ) { // The application should allocate or use a static #MQTTFixedBuffer_t // of size >= packetSize to serialize the subscribe request. } ``` -------------------------------- ### Calculate ACK Packet Size Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8c.html Example demonstrating how to initialize variables and call MQTT_GetAckPacketSize to determine the required buffer size for an ACK packet. ```c // Variables used in this example. MQTTStatus_t status; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ BUFFER_SIZE ]; MQTTAckInfo_t ackInfo; uint16_t sessionExpiry; fixedBuffer.pBuffer = buffer; fixedBuffer.size = BUFFER_SIZE; // Variables used in this example. MQTTStatus_t status; size_t remainingLength =0; size_t packetSize = 0; size_t ackPropertyLength = 0; uint32_t maxPacketSize; //set the parameters. // Get the size requirement for the ack packet. status = MQTT_GetAckPacketSize(&remainingLength,&packetSize,maxPacketSize, ackPropertyLength); } ``` -------------------------------- ### Validating Publish Parameters Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_validatepublishparams_function.html This example demonstrates how to initialize the necessary variables and call MQTT_ValidatePublishParams to ensure the publish information is valid before proceeding with packet size calculation and serialization. ```c // Variables used in this example. MQTTStatus_t status; MQTTPublishInfo_t publishInfo = {0}; uint16_t topicAlias; uint8_t retainAvailable; uint8_t maxQos; // Set in the CONNACK packet. uint32_t maxPacketSize ; //Set the publish info parameters. //Validate the publish packet status = MQTT_ValidatePublishParams(&publishInfo, retainAvailable, maxQos, topicAlias, maxPacketSize); if( status == MQTTSuccess ) { // Get the packet size and serialize the publish packet. } ``` -------------------------------- ### Get Status String Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Returns a string representation of an MQTT status code. ```c const char * MQTT_Status_strerror( MQTTStatus_t status ); ``` -------------------------------- ### Sending an MQTT DISCONNECT packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_disconnect_function.html This example demonstrates initializing a property builder, adding a reason string, and calling MQTT_Disconnect to close the connection. ```c // Variables used in this example. MQTTStatus_t status; // This context is assumed to be initialized and connected. MQTTContext_t * pContext; // Optional properties to be sent in the DISCONNECT packet. MQTTPropBuilder_t propertyBuilder; uint8_t propertyBuffer[ 100 ]; size_t propertyBufferLength = sizeof( propertyBuffer ); status = MQTTPropertyBuilder_Init( &propertyBuilder, propertyBuffer, propertyBufferLength ); // Set a property in the propertyBuilder status = MQTTPropAdd_ReasonString( &propertyBuilder, "Disconnecting", 13, &(uint8_t){ MQTT_PACKET_TYPE_DISCONNECT }); MQTTSuccessFailReasonCode_t reason = MQTT_REASON_DISCONNECT_NORMAL_DISCONNECTION; status = MQTT_Disconnect( pContext, &propertyBuilder, &reason ); if( status == MQTTSuccess ) { // The DISCONNECT packet was sent successfully. The connection is now closed. } ``` -------------------------------- ### Calculate MQTT UNSUBSCRIBE packet size Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_getunsubscribepacketsize_function.html This example demonstrates how to calculate the required packet size and remaining length for an UNSUBSCRIBE operation using the coreMQTT library. ```c // Variables used in this example. MQTTStatus_t status; MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 }; size_t remainingLength = 0, packetSize = 0; MQTTPropBuilder_t unsubscribeProperties = { 0 }; size_t maxPacketSize = 0; // Initialize maxPacketSize. The details are out of scope for this example. initializeMaxPacketSize( &maxPacketSize ); // Initialize the subscribe info. The details are out of scope for this example. initializeSubscribeInfo( &subscriptionList[ 0 ] ); //Initialize the property buffer. The details are out of scope for this example. initializePropertyBuffer( &unsubscribeProperties ); // Get the size requirement for the unsubscribe packet. status = MQTT_GetUnsubscribePacketSize( &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &unsubscribeProperties, &remainingLength, &packetSize, maxPacketSize); if( status == MQTTSuccess ) { // The unsubscribe packet can now be sent to the broker. } ``` -------------------------------- ### Validate MQTT Properties Source: https://freertos.github.io/coreMQTT/v5.0.2/group__mqtt__constants.html Examples of using packet type constants to validate properties during addition to the MQTT property builder. ```c MQTTPropAdd_SessionExpiry( &props, 3600, MQTT_PROP_VALIDATE_CONNECT ); MQTTPropAdd_PayloadFormat( &props, 1, MQTT_PROP_VALIDATE_PUBLISH ); MQTTPropAdd_UserProp( &props, &up, MQTT_PROP_NO_VALIDATE ); ``` -------------------------------- ### Get ACK packet size Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Calculates the size of an acknowledgment packet. ```c MQTTStatus_t MQTT_GetAckPacketSize( uint32_t * pRemainingLength, uint32_t * pPacketSize, uint32_t maxPacketSize, size_t ackPropertyLength ); ``` -------------------------------- ### Get User Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves a user property from the property builder. ```c MQTTStatus_t MQTTPropGet_UserProp( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, MQTTUserProperty_t * pUserProperty ); ``` -------------------------------- ### Subscribe to MQTT Topics Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_subscribe_function.html Demonstrates how to initialize a subscription list, add optional properties, and send a SUBSCRIBE packet. ```C // Variables used in this example. MQTTStatus_t status; MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 }; uint16_t packetId; // This context is assumed to be initialized and connected. MQTTContext_t * pContext; // This is assumed to be a list of filters we want to subscribe to. const char * filters[ NUMBER_OF_SUBSCRIPTIONS ]; // Set each subscription. for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ ) { subscriptionList[ i ].qos = MQTTQoS0; // Each subscription needs a topic filter. subscriptionList[ i ].pTopicFilter = filters[ i ]; subscriptionList[ i ].topicFilterLength = strlen( filters[ i ] ); } // Optional Properties to be sent in the SUBSCRIBE packet MQTTPropBuilder_t propertyBuilder; uint8_t propertyBuffer[ 100 ]; size_t propertyBufferLength = sizeof( propertyBuffer ); status = MQTTPropertyBuilder_Init( &propertyBuilder, propertyBuffer, propertyBufferLength ); status = MQTTPropAdd_SubscriptionId(&propertyBuilder, 1, &(uint8_t){ MQTT_PACKET_TYPE_SUBSCRIBE }); // Obtain a new packet id for the subscription. packetId = MQTT_GetPacketId( pContext ); status = MQTT_Subscribe( pContext, &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId, &propertyBuilder ); if( status == MQTTSuccess ) { // We must now call MQTT_ReceiveLoop() or MQTT_ProcessLoop() to receive the SUBACK. // If the broker accepts the subscription we can now receive publishes // on the requested topics. } ``` -------------------------------- ### Get Packet ID Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Generates a new unique packet identifier. ```c uint16_t MQTT_GetPacketId( MQTTContext_t * pContext ); ``` -------------------------------- ### Initialize MQTT Context and Retransmissions Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_initretransmits_function.html Demonstrates the sequence of initializing the MQTT context, configuring stateful QoS, and registering callbacks for retransmission management. ```c // Function for obtaining a timestamp. uint32_t getTimeStampMs(); // Callback function for receiving packets. bool eventCallback( MQTTContext_t * pContext, MQTTPacketInfo_t * pPacketInfo, MQTTDeserializedInfo_t * pDeserializedInfo, MQTTSuccessFailReasonCode_t * pReasonCode, MQTTPropBuilder_t * pSendPropsBuffer, MQTTPropBuilder_t * pGetPropsBuffer ); // Network send. int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes ); // Network receive. int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes ); // User defined callback used to store outgoing publishes bool publishStoreCallback(struct MQTTContext* pContext, uint16_t packetId, MQTTVec_t* pIoVec); // User defined callback used to retreive a copied publish for resend operation bool publishRetrieveCallback(struct MQTTContext* pContext, uint16_t packetId, TransportOutVector_t** pIoVec, size_t* ioVecCount); // User defined callback used to clear a particular copied publish packet bool publishClearCallback(struct MQTTContext* pContext, uint16_t packetId); // User defined callback used to clear all copied publish packets bool publishClearAllCallback(struct MQTTContext* pContext); MQTTContext_t mqttContext; TransportInterface_t transport; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ 1024 ]; const size_t outgoingPublishCount = 30; MQTTPubAckInfo_t outgoingPublishes[ outgoingPublishCount ]; // Clear context. memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) ); // Set transport interface members. transport.pNetworkContext = &someTransportContext; transport.send = networkSend; transport.recv = networkRecv; transport.writev = NULL; // Set buffer members. fixedBuffer.pBuffer = buffer; fixedBuffer.size = 1024; status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer ); if( status == MQTTSuccess ) { // We do not expect any incoming publishes in this example, therefore the incoming // publish pointer is NULL and the count is zero. uint8_t ackPropsBuf[ 500 ]; size_t ackPropsBufLength = sizeof( ackPropsBuf ); status = MQTT_InitStatefulQoS( &mqttContext, outgoingPublishes, outgoingPublishCount, NULL, 0, ackPropsBuf, ackPropsBufLength ); // Now QoS1 and/or QoS2 publishes can be sent with this context. } if( status == MQTTSuccess ) { status = MQTT_InitRetransmits( &mqttContext, publishStoreCallback, publishRetrieveCallback, publishClearCallback, publishClearAllCallback ); // Now unacked Publishes can be resent on an unclean session resumption. } ``` -------------------------------- ### Initialize MQTT Context and Stateful QoS Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_initstatefulqos_function.html Demonstrates the sequence of initializing the MQTT context with transport and buffer interfaces, followed by enabling stateful QoS tracking. ```c // Function for obtaining a timestamp. uint32_t getTimeStampMs(); // Callback function for receiving packets. bool eventCallback( MQTTContext_t * pContext, MQTTPacketInfo_t * pPacketInfo, MQTTDeserializedInfo_t * pDeserializedInfo, MQTTSuccessFailReasonCode_t * pReasonCode, MQTTPropBuilder_t * pSendPropsBuffer, MQTTPropBuilder_t * pGetPropsBuffer ); // Network send. int32_t networkSend( NetworkContext_t * pContext, const void * pBuffer, size_t bytes ); // Network receive. int32_t networkRecv( NetworkContext_t * pContext, void * pBuffer, size_t bytes ); MQTTContext_t mqttContext; TransportInterface_t transport; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ 1024 ]; const size_t outgoingPublishCount = 30; MQTTPubAckInfo_t outgoingPublishes[ outgoingPublishCount ]; // Clear context. memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) ); // Set transport interface members. transport.pNetworkContext = &someTransportContext; transport.send = networkSend; transport.recv = networkRecv; transport.writev = NULL; // Set buffer members. fixedBuffer.pBuffer = buffer; fixedBuffer.size = 1024; status = MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer ); if( status == MQTTSuccess ) { // We do not expect any incoming publishes in this example, therefore the incoming // publish pointer is NULL and the count is zero. // The buffer is used to store properties of outgoing publish-ACKS. uint8_t ackPropsBuf[ 500 ]; size_t ackPropsBufLength = sizeof( ackPropsBuf ); status = MQTT_InitStatefulQoS( &mqttContext, outgoingPublishes, outgoingPublishCount, NULL, 0, ackPropsBuf, ackPropsBufLength ); // Now QoS1 and/or QoS2 publishes can be sent with this context. } ``` -------------------------------- ### Initialize and Send MQTT CONNECT Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_connect_function.html Demonstrates setting up connection information, optional properties, and LWT settings before calling MQTT_Connect. ```c // Variables used in this example. MQTTStatus_t status; MQTTConnectInfo_t connectInfo = { 0 }; MQTTPublishInfo_t willInfo = { 0 }; bool sessionPresent; // This is assumed to have been initialized before calling this function. MQTTContext_t * pContext; // True for creating a new session with broker, false if we want to resume an old one. connectInfo.cleanSession = true; // Client ID must be unique to broker. This field is required. connectInfo.pClientIdentifier = "someClientID"; connectInfo.clientIdentifierLength = strlen( connectInfo.pClientIdentifier ); // The following fields are optional. // Value for keep alive. connectInfo.keepAliveSeconds = 60; // Optional username and password. connectInfo.pUserName = "someUserName"; connectInfo.userNameLength = strlen( connectInfo.pUserName ); connectInfo.pPassword = "somePassword"; connectInfo.passwordLength = strlen( connectInfo.pPassword ); // Optional properties to be sent in the CONNECT packet. MQTTPropBuilder_t connectPropsBuilder; uint8_t connectPropsBuffer[ 100 ]; size_t connectPropsBufferLength = sizeof( connectPropsBuffer ); status = MQTTPropertyBuilder_Init( &connectPropsBuilder, connectPropsBuffer, connectPropsBufferLength ); // Set a property in the connectPropsBuilder uint32_t maxPacketSize = 100 ; status = MQTTPropAdd_MaxPacketSize(&connectPropsBuilder, maxPacketSize, &(uint8_t){ MQTT_PACKET_TYPE_CONNECT }); // The last will and testament is optional, it will be published by the broker // should this client disconnect without sending a DISCONNECT packet. willInfo.qos = MQTTQoS0; willInfo.pTopicName = "/lwt/topic/name"; willInfo.topicNameLength = strlen( willInfo.pTopicName ); willInfo.pPayload = "LWT Message"; willInfo.payloadLength = strlen( "LWT Message" ); // Optional Will Properties to be sent in the CONNECT packet. MQTTPropBuilder_t willPropsBuilder; uint8_t willPropsBuffer[ 100 ]; size_t willPropsBufferLength = sizeof( willPropsBuffer ); status = MQTTPropertyBuilder_Init( &willPropsBuilder, willPropsBuffer, willPropsBufferLength ); // Set a property in the willPropsBuilder status = MQTTPropAdd_PayloadFormat( &willPropsBuilder, 1, NULL); // Send the connect packet. Use 100 ms as the timeout to wait for the CONNACK packet. status = MQTT_Connect( pContext, &connectInfo, &willInfo, 100, &sessionPresent, &connectPropsBuilder, &willPropsBuilder ); if( status == MQTTSuccess ) { // Since we requested a clean session, this must be false assert( sessionPresent == false ); // Do something with the connection. } ``` -------------------------------- ### Get UnsubAck Status Codes Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Extracts status codes from an UNSUBACK packet. ```c MQTTStatus_t MQTT_GetUnsubAckStatusCodes( const MQTTPacketInfo_t * pUnsubackPacket, uint8_t ** pPayloadStart, size_t * pPayloadSize ); ``` -------------------------------- ### Get SubAck Status Codes Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Extracts status codes from a SUBACK packet. ```c MQTTStatus_t MQTT_GetSubAckStatusCodes( const MQTTPacketInfo_t * pSubackPacket, uint8_t ** pPayloadStart, size_t * pPayloadSize ); ``` -------------------------------- ### MQTTStatus_t MQTT_InitStatefulQoS(MQTTContext_t *pContext, MQTTPubAckInfo_t *pOutgoingPublishRecords, size_t outgoingPublishRecordCount, MQTTPubAckInfo_t *pIncomingPublishRecords, size_t incomingPublishRecordCount, uint8_t *pAckPropsBuffer, size_t ackPropsBufferSize) Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_initstatefulqos_function.html Initializes the stateful QoS tracking for an MQTT context. This function must be called after MQTT_Init to enable tracking of QoS 1 and QoS 2 messages. ```APIDOC ## MQTT_InitStatefulQoS ### Description Initializes stateful QoS tracking for an MQTT context. This allows the library to track outgoing and incoming QoS 1 and QoS 2 publishes. ### Parameters - **pContext** (MQTTContext_t *) - The MQTT context to initialize. - **pOutgoingPublishRecords** (MQTTPubAckInfo_t *) - Pointer to an array of records for tracking outgoing publishes. - **outgoingPublishRecordCount** (size_t) - The number of records in the outgoing publish array. - **pIncomingPublishRecords** (MQTTPubAckInfo_t *) - Pointer to an array of records for tracking incoming publishes. - **incomingPublishRecordCount** (size_t) - The number of records in the incoming publish array. - **pAckPropsBuffer** (uint8_t *) - Buffer used to store properties of outgoing publish-ACKs. - **ackPropsBufferSize** (size_t) - The size of the property buffer. ### Returns - **MQTTStatus_t** - Returns MQTTSuccess if successful, or MQTTBadParameter if invalid parameters are provided. ``` -------------------------------- ### Get Retain Available Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves the retain available property from the property builder. ```c MQTTStatus_t MQTTPropGet_RetainAvailable( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, uint8_t * pRetainAvailable ); ``` -------------------------------- ### Get Maximum QoS Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves the maximum QoS property from the property builder. ```c MQTTStatus_t MQTTPropGet_MaxQos( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, uint8_t * pMaxQos ); ``` -------------------------------- ### Stateful QoS Initialization Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Configures stateful QoS tracking for incoming and outgoing publishes. ```c MQTTStatus_t MQTT_InitStatefulQoS( MQTTContext_t * pContext, MQTTPubAckInfo_t * pOutgoingPublishRecords, size_t outgoingPublishCount, MQTTPubAckInfo_t * pIncomingPublishRecords, size_t incomingPublishCount, uint8_t * pAckPropsBuf, size_t ackPropsBufLength ); ``` -------------------------------- ### Get Receive Maximum Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves the receive maximum property from the property builder. ```c MQTTStatus_t MQTTPropGet_ReceiveMax( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, uint16_t * pReceiveMax ); ``` -------------------------------- ### Get Session Expiry Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves the session expiry interval from the property builder. ```c MQTTStatus_t MQTTPropGet_SessionExpiry( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, uint32_t * pSessionExpiry ); ``` -------------------------------- ### Get Bytes in MQTT Vector Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Calculates the total number of bytes in an MQTT vector. ```c MQTTStatus_t MQTT_GetBytesInMQTTVec( const MQTTVec_t * pVec, size_t * pOutput ); ``` -------------------------------- ### Get Maximum Packet Size Property Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Retrieves the maximum packet size property from the property builder. ```c MQTTStatus_t MQTTPropGet_MaxPacketSize( const MQTTPropBuilder_t * pPropertyBuilder, size_t * currentIndex, uint32_t * pMaxPacketSize ); ``` -------------------------------- ### MQTT Connect Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initiates an MQTT connection to the broker. ```c MQTTStatus_t MQTT_Connect( MQTTContext_t * pContext, const MQTTConnectInfo_t * pConnectInfo, const MQTTPublishInfo_t * pWillInfo, uint32_t timeoutMs, bool * pSessionPresent, MQTTPropBuilder_t * pPropertyBuilder, const MQTTPropBuilder_t * pWillPropertyBuilder ); ``` -------------------------------- ### MQTT_Init Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initializes the MQTT context with transport interface, time function, callback, and network buffer. ```APIDOC ## MQTT_Init ### Description Initializes the MQTT context structure with the necessary transport interface, time-keeping function, user callback, and network buffer. ### Signature MQTTStatus_t MQTT_Init( MQTTContext_t * pContext, const TransportInterface_t * pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback, const MQTTFixedBuffer_t * pNetworkBuffer ); ``` -------------------------------- ### Get MQTT Packet Type String Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Returns a human-readable string representation of an MQTT packet type. ```c const char * MQTT_GetPacketTypeString(uint8_t packetType) ``` -------------------------------- ### Get MQTT Packet ID Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Retrieves a packet ID that is valid according to the MQTT 5.0 specification. ```c uint16_t MQTT_GetPacketId(MQTTContext_t *pContext) ``` -------------------------------- ### MQTTPropertyBuilder_Init Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_connect_function.html Initializes the MQTT property builder. ```APIDOC ## MQTTStatus_t MQTTPropertyBuilder_Init(MQTTPropBuilder_t *pPropertyBuilder, uint8_t *buffer, size_t length) ### Description Initializes the property builder with a provided buffer and length. ### Parameters - **pPropertyBuilder** (MQTTPropBuilder_t*) - Pointer to the property builder structure. - **buffer** (uint8_t*) - Buffer to be used by the builder. - **length** (size_t) - Length of the buffer. ``` -------------------------------- ### Establish MQTT Session Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initiates an MQTT connection session with the broker. ```c MQTTStatus_t MQTT_Connect(MQTTContext_t *pContext, const MQTTConnectInfo_t *pConnectInfo, const MQTTPublishInfo_t *pWillInfo, uint32_t timeoutMs, bool *pSessionPresent, MQTTPropBuilder_t *pPropertyBuilder, const MQTTPropBuilder_t *pWillPropertyBuilder) ``` -------------------------------- ### Implement TransportSend_t Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_transport_interface.html Defines the function signature and provides an implementation example for sending data over the transport layer. ```c typedef int32_t ( * TransportSend_t )( NetworkContext_t * pNetworkContext, const void * pBuffer, size_t bytesToSend ); ``` ```c int32_t myNetworkSendImplementation( NetworkContext_t * pNetworkContext, const void * pBuffer, size_t bytesToSend ) { int32_t bytesSent = 0; bytesSent = TLSSend( pNetworkContext->tlsContext, pBuffer, bytesToSend, MY_SOCKET_TIMEOUT ); // If underlying TCP buffer is full, set the return value to zero // so that caller can retry the send operation. if( bytesSent == MY_SOCKET_ERROR_BUFFER_FULL ) { bytesSent = 0; } else if( bytesSent < 0 ) { // Handle socket error. } // Handle other cases. return bytesSent; } ``` -------------------------------- ### Publishing an MQTT Message Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_publish_function.html Demonstrates the sequence for initializing publish information, adding properties, and sending a message with QoS 1. ```c // Variables used in this example. MQTTStatus_t status; MQTTPublishInfo_t publishInfo; uint16_t packetId; // This context is assumed to be initialized and connected. MQTTContext_t * pContext; // QoS of publish. publishInfo.qos = MQTTQoS1; publishInfo.pTopicName = "/some/topic/name"; publishInfo.topicNameLength = strlen( publishInfo.pTopicName ); publishInfo.pPayload = "Hello World!"; publishInfo.payloadLength = strlen( "Hello World!" ); // Optional properties to be sent in the PUBLISH packet. MQTTPropBuilder_t propertyBuilder; uint8_t propertyBuffer[ 100 ]; size_t propertyBufferLength = sizeof( propertyBuffer ); status = MQTTPropertyBuilder_Init( &propertyBuilder, propertyBuffer, propertyBufferLength ); // Set a property in the propertyBuilder status = MQTTPropAdd_PayloadFormat( &propertyBuilder, 1, &(uint8_t){ MQTT_PACKET_TYPE_PUBLISH }); // Packet ID is needed for QoS > 0. packetId = MQTT_GetPacketId( pContext ); status = MQTT_Publish( pContext, &publishInfo, packetId, &propertyBuilder ); if( status == MQTTSuccess ) { // Since the QoS is > 0, we will need to call MQTT_ReceiveLoop() // or MQTT_ProcessLoop() to process the publish acknowledgments. } ``` -------------------------------- ### Implement TransportRecv_t Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_transport_interface.html Defines the function signature and provides an implementation example for receiving data from the transport layer. ```c typedef int32_t ( * TransportRecv_t )( NetworkContext_t * pNetworkContext, void * pBuffer, size_t bytesToRecv ); ``` ```c int32_t myNetworkRecvImplementation( NetworkContext_t * pNetworkContext, void * pBuffer, size_t bytesToRecv ) { int32_t bytesReceived = 0; bool callTlsRecvFunc = true; // For a single byte read request, check if data is available on the network. if( bytesToRecv == 1 ) { // If no data is available on the network, do not call TLSRecv // to avoid blocking for socket timeout. if( TLSRecvCount( pNetworkContext->tlsContext ) == 0 ) { callTlsRecvFunc = false; } } if( callTlsRecvFunc == true ) { bytesReceived = TLSRecv( pNetworkContext->tlsContext, pBuffer, bytesToRecv, MY_SOCKET_TIMEOUT ); if( bytesReceived < 0 ) { // If the error code represents a timeout, then the return // code should be translated to zero so that the caller // can retry the read operation. if( bytesReceived == MY_SOCKET_ERROR_TIMEOUT ) { bytesReceived = 0; } } // Handle other cases. } return bytesReceived; } ``` -------------------------------- ### Deserialize MQTT Disconnect Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8c.html Example demonstrating how to deserialize an incoming MQTT DISCONNECT packet using MQTT_DeserializeDisconnect. ```c // Variables used in this example. MQTTStatus_t status; MQTTPacketInfo_t incomingPacket; MQTTReasonCodeInfo_t disconnectInfo; uint32_t maxPacketSize; MQTTPropBuilder_t propBuffer; // Assume this is initialized properly // Receive an incoming packet and populate all fields. The details are out of scope // for this example. receiveIncomingPacket( &incomingPacket ); // Deserialize disconnect information. if( ( incomingPacket.type) == MQTT_PACKET_TYPE_DISCONNECT ) { status = MQTT_DeserializeDisconnect(&incomingPacket, maxPacketSize, &disconnectInfo, &propBuffer); if( status == MQTTSuccess ) { // Disconnect information is available. } } ``` -------------------------------- ### Initialize Stateful QoS Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initializes the MQTT context to support QoS levels greater than 0. ```c MQTTStatus_t MQTT_InitStatefulQoS(MQTTContext_t *pContext, MQTTPubAckInfo_t *pOutgoingPublishRecords, size_t outgoingPublishCount, MQTTPubAckInfo_t *pIncomingPublishRecords, size_t incomingPublishCount, uint8_t *pAckPropsBuf, size_t ackPropsBufLength) ``` -------------------------------- ### MQTT_InitStatefulQoS Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_initstatefulqos_function.html Initializes an MQTT context for QoS > 0. This function must be called on an MQTTContext_t after MQTT_Init and before any other function. ```APIDOC ## MQTT_InitStatefulQoS ### Description Initializes an MQTT context for QoS > 0. This function must be called on an MQTTContext_t after MQTT_Init and before any other function. ### Signature MQTTStatus_t MQTT_InitStatefulQoS( MQTTContext_t * pContext, MQTTPubAckInfo_t * pOutgoingPublishRecords, size_t outgoingPublishCount, MQTTPubAckInfo_t * pIncomingPublishRecords, size_t incomingPublishCount, uint8_t * pAckPropsBuf, size_t ackPropsBufLength ); ### Parameters - **pContext** (MQTTContext_t *) - The context to initialize. - **pOutgoingPublishRecords** (MQTTPubAckInfo_t *) - Pointer to memory which will be used to store state of outgoing publishes. - **outgoingPublishCount** (size_t) - Maximum number of records which can be kept in the memory pointed to by pOutgoingPublishRecords. - **pIncomingPublishRecords** (MQTTPubAckInfo_t *) - Pointer to memory which will be used to store state of incoming publishes. - **incomingPublishCount** (size_t) - Maximum number of records which can be kept in the memory pointed to by pIncomingPublishRecords. - **pAckPropsBuf** (uint8_t *) - Pointer to memory which will be used to store properties of outgoing publish-ACKS. - **ackPropsBufLength** (size_t) - Length of the buffer pointed to by pBuffer. ### Returns - **MQTTStatus_t** - Return codes from MQTT functions. ``` -------------------------------- ### Decode 32-bit Unsigned Integer Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer__private_8h.html Decodes a 4-byte unsigned integer from a byte array starting at the provided pointer. ```c #define UINT32_DECODE( ptr ) ( ( uint32_t ) ( ( ( ( uint32_t ) ptr[ 0 ] ) << 24 ) | ( ( ( uint32_t ) ptr[ 1 ] ) << 16 ) | ( ( ( uint32_t ) ptr[ 2 ] ) << 8 ) | ( ( uint32_t ) ptr[ 3 ] ) ) ) ``` -------------------------------- ### Initialize the MQTT Property Builder Source: https://freertos.github.io/coreMQTT/v5.0.2/mqttpropertybuilder_init_function.html Initializes the property builder structure using a provided buffer and its length. ```c MQTTStatus_t MQTTPropertyBuilder_Init( MQTTPropBuilder_t * pPropertyBuilder, uint8_t * buffer, size_t length ); ``` -------------------------------- ### MQTT Get Publish Packet Size Function Signature Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_serializepublish_function.html Function signature for calculating the size of an MQTT PUBLISH packet. ```c MQTTStatus_t MQTT_GetPublishPacketSize(const MQTTPublishInfo_t *pPublishInfo, const MQTTPropBuilder_t *pPublishProperties, uint32_t *pRemainingLength, uint32_t *pPacketSize, uint32_t maxPacketSize) ``` -------------------------------- ### MQTT Initialization Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initializes the MQTT context with transport, time, and buffer interfaces. ```c MQTTStatus_t MQTT_Init( MQTTContext_t * pContext, const TransportInterface_t * pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback, const MQTTFixedBuffer_t * pNetworkBuffer ); ``` -------------------------------- ### MQTT Property Get Functions Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_propertygetfunctions.html A collection of functions provided by the coreMQTT library to retrieve specific MQTT 5.0 properties from a property buffer. ```APIDOC ## MQTT Property Get Functions ### Available Functions - **MQTTPropGet_PayloadFormatIndicator** - **MQTTPropGet_ResponseTopic** - **MQTTPropGet_CorrelationData** - **MQTTPropGet_MessageExpiryInterval** - **MQTTPropGet_ContentType** - **MQTTPropGet_SubscriptionId** - **MQTTPropGet_UserProp** - **MQTTPropGet_ReasonString** - **MQTTPropGet_SessionExpiry** - **MQTTPropGet_TopicAliasMax** - **MQTTPropGet_ReceiveMax** - **MQTTPropGet_MaxQos** - **MQTTPropGet_RetainAvailable** - **MQTTPropGet_MaxPacketSize** ### Description These functions are part of the coreMQTT library and are used to parse and retrieve specific properties from MQTT 5.0 packets. Users can invoke these functions to extract metadata associated with MQTT control packets. ``` -------------------------------- ### Include coreMQTT Configuration Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__config__defaults_8h.html Include the configuration header file to access the library macros. ```c #include "core_mqtt_config.h" ``` -------------------------------- ### MQTT_InitConnect Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Initializes an MQTTConnectionProperties_t structure. ```APIDOC ## MQTT_InitConnect ### Description Initialize an MQTTConnectionProperties_t. ### Signature MQTTStatus_t MQTT_InitConnect(MQTTConnectionProperties_t *pConnectProperties) ``` -------------------------------- ### Unsubscribe from MQTT Topics Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_unsubscribe_function.html Demonstrates how to prepare an unsubscribe list, generate a packet ID, add optional properties, and execute the MQTT_Unsubscribe function. ```c // Variables used in this example. MQTTStatus_t status; MQTTSubscribeInfo_t unsubscribeList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 }; uint16_t packetId; // This context is assumed to be initialized and connected. MQTTContext_t * pContext; // This is assumed to be a list of filters we want to unsubscribe from. const char * filters[ NUMBER_OF_SUBSCRIPTIONS ]; // Set information for each unsubscribe request. for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ ) { unsubscribeList[ i ].pTopicFilter = filters[ i ]; unsubscribeList[ i ].topicFilterLength = strlen( filters[ i ] ); // The QoS field of MQTT_SubscribeInfo_t is unused for unsubscribing. } // Obtain a new packet id for the unsubscribe request. packetId = MQTT_GetPacketId( pContext ); // Optional properties to be sent in the UNSUBSCRIBE packet. MQTTPropBuilder_t propertyBuilder; uint8_t propertyBuffer[ 100 ]; size_t propertyBufferLength = sizeof( propertyBuffer ); status = MQTTPropertyBuilder_Init( &propertyBuilder, propertyBuffer, propertyBufferLength ); // Set a property in the propertyBuilder MQTTUserProperty_t userProperty; userProperty.pKey = "key"; userProperty.keyLength = strlen( userProperty.pKey ); userProperty.pValue = "value"; userProperty.valueLength = strlen( userProperty.pValue ); status = MQTTPropAdd_UserProp( &propertyBuilder, &userProperty, &(uint8_t){ MQTT_PACKET_TYPE_UNSUBSCRIBE }); status = MQTT_Unsubscribe( pContext, &unsubscribeList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId, &propertyBuilder ); if( status == MQTTSuccess ) { // We must now call MQTT_ReceiveLoop() or MQTT_ProcessLoop() to receive the UNSUBACK. // After this the broker should no longer send publishes for these topics. } ``` -------------------------------- ### Initialize MQTT Context Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8h_source.html Initializes an MQTT context structure with transport and timing interfaces. ```c MQTTStatus_t MQTT_Init(MQTTContext_t *pContext, const TransportInterface_t *pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback, const MQTTFixedBuffer_t *pNetworkBuffer) ``` -------------------------------- ### Serializing an MQTT Publish Header Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_serializepublishheader_function.html Demonstrates initializing the necessary structures, calculating the required packet size, and serializing the header into a buffer before sending it over a socket. ```c // Variables used in this example. MQTTStatus_t status; MQTTPublishInfo_t publishInfo = { 0 }; MQTTPropBuilder_t publishProperties ; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ BUFFER_SIZE ]; size_t remainingLength = 0, packetSize = 0, headerSize = 0; uint16_t packetId; int32_t bytesSent; uint32_t maxPacketSize = pContext->connectionProperties.serverMaxPacketSize; fixedBuffer.pBuffer = buffer; fixedBuffer.size = BUFFER_SIZE; // A packet identifier is unused for QoS 0 publishes. Otherwise, a valid, unused packet // identifier must be used. packetId = 0; // Assume publishInfo and publishProperties have been initialized. Get the publish packet size. status = MQTT_GetPublishPacketSize( &publishInfo, &publishProperties, &remainingLength, &packetSize, maxPacketSize ); assert( status == MQTTSuccess ); // The payload will not be serialized, so the the fixed buffer does not need to hold it. assert( ( packetSize - publishInfo.payloadLength ) <= BUFFER_SIZE ); // Serialize the publish packet header into the fixed buffer. status = MQTT_SerializePublishHeader( &publishInfo, &publishProperties, packetId, remainingLength, &fixedBuffer, &headerSize ); if( status == MQTTSuccess ) { // The publish header and payload can now be sent to the broker. // mqttSocket here is a socket descriptor created and connected to the MQTT // broker outside of this function. bytesSent = send( mqttSocket, ( void * ) fixedBuffer.pBuffer, headerSize, 0 ); assert( bytesSent == headerSize ); bytesSent = send( mqttSocket, publishInfo.pPayload, publishInfo.payloadLength, 0 ); assert( bytesSent == publishInfo.payloadLength ); } ``` -------------------------------- ### Serialize MQTT CONNECT Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_serializeconnect_function.html Demonstrates calculating the required packet size and serializing the MQTT CONNECT packet into a fixed buffer. ```c // Variables used in this example. MQTTStatus_t status; MQTTConnectInfo_t connectInfo = { 0 }; MQTTPublishInfo_t willInfo = { 0 }; MQTTPropBuilder_t connectionProperties = { 0 }; MQTTPropBuilder_t willProperties = { 0 }; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ BUFFER_SIZE ]; size_t remainingLength = 0, packetSize = 0; fixedBuffer.pBuffer = buffer; fixedBuffer.size = BUFFER_SIZE; // Assume connectInfo, willInfo, and properties are initialized. // Get the size requirement for the connect packet. status = MQTT_GetConnectPacketSize( &connectInfo, &willInfo, &connectionProperties, &willProperties, &remainingLength, &packetSize ); assert( status == MQTTSuccess ); assert( packetSize <= BUFFER_SIZE ); // Serialize the connect packet into the fixed buffer. status = MQTT_SerializeConnect( &connectInfo, &willInfo, &connectionProperties, &willProperties, remainingLength, &fixedBuffer ); if( status == MQTTSuccess ) { // The connect packet can now be sent to the broker. } ``` -------------------------------- ### Protocol Configuration Macros Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__serializer_8h_source.html Constants defining packet sizes and QoS levels. ```c #define MQTT_PUBLISH_ACK_PACKET_SIZE ( 4UL ) #define MQTT_SUBSCRIBE_QOS1 ( 0U ) #define MQTT_SUBSCRIBE_QOS2 ( 1U ) ``` -------------------------------- ### Deserializing an MQTT Acknowledgment Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_deserializeack_function.html Example demonstrating the usage of MQTT_DeserializeAck to process an incoming acknowledgment packet. Ensure that required structures are initialized before calling the function. ```c // Variables used in this example. MQTTStatus_t status; MQTTPacketInfo_t incomingPacket; uint16_t packetId; MQTTReasonCodeInfo_t reasonCode ; // Can be set to NULL if the incoming packet is CONNACK or PINGRESP MQTTPropBuilder_t propBuffer; // Can be set to NULL if the user does not want any incoming properties. MQTTConnectionProperties_t connectionProperties = pContext->connectionProperties; // Cannot be set to NULL. // Receive an incoming packet and populate all fields. The details are out of scope // for this example. receiveIncomingPacket(&incomingPacket); // Deserialize ack information if the incoming packet is a publish ack. status = MQTT_DeserializeAck( &incomingPacket, &packetId, &reasonCode, &propBuffer, &connectionProperties ); if(status == MQTTSuccess) { // Ack information is now available. } ``` -------------------------------- ### Serialize an MQTT Acknowledgment Packet Source: https://freertos.github.io/coreMQTT/v5.0.2/mqtt_serializeack_function.html Demonstrates how to initialize a buffer and serialize a PUBACK packet using MQTT_SerializeAck. ```c // Variables used in this example. MQTTStatus_t status; MQTTFixedBuffer_t fixedBuffer; uint8_t buffer[ BUFFER_SIZE ]; uint16_t packetId; uint8_t packetType; fixedBuffer.pBuffer = buffer; fixedBuffer.size = BUFFER_SIZE; // The fixed buffer must be large enough to hold 4 bytes. assert( BUFFER_SIZE >= MQTT_PUBLISH_ACK_PACKET_SIZE ); // The packet ID must be the same as the original publish packet. packetId = publishPacketId; // The byte representing a packet of type ACK. This function accepts PUBACK, PUBREC, PUBREL, or PUBCOMP. packetType = MQTT_PACKET_TYPE_PUBACK; // Serialize the publish acknowledgment into the fixed buffer without any properties or reason code. status = MQTT_SerializeAck( &fixedBuffer, packetType, packetId, NULL, NULL ); if( status == MQTTSuccess ) { // The publish acknowledgment can now be sent to the broker. } ``` -------------------------------- ### Include Required Headers Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt_8c.html Standard library and coreMQTT internal headers required for the implementation. ```c #include #include #include #include #include #include #include "core_mqtt.h" #include "core_mqtt_serializer.h" #include "transport_interface.h" #include "core_mqtt_state.h" #include "private/core_mqtt_serializer_private.h" #include "core_mqtt_config_defaults.h" ``` -------------------------------- ### Define MQTT_DO_NOT_USE_CUSTOM_CONFIG Source: https://freertos.github.io/coreMQTT/v5.0.2/core__mqtt__config__defaults_8h.html Define this macro to build the library without a custom configuration file, forcing the use of default values. ```c #define MQTT_DO_NOT_USE_CUSTOM_CONFIG ```