coreMQTT
v1.1.0
Generated by Doxygen 1.8.20
Chapter 1
Overview
MQTT 3.1.1 client library
MQTT stands for MQ Telemetry Transport. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks. The design principles are to minimise network bandwidth and device resource requirements whilst also attempting to ensure reliability and some degree of assurance of delivery. These principles also turn out to make the protocol ideal of the emerging "machine-to-machine" (M2M) or "Internet of Things" world of connected devices, and for mobile applications where bandwidth and battery power are at a premium.
— Official description of MQTT from mqtt.org
This MQTT library implements the client side of the MQTT 3.1.1 protocol. This library is optimized for resource constrained embedded devices. Features of this library include:
• Fully synchronous API, to allow applications to completely manage their concurrency and multi-threading method.
• Operations on fixed buffers, so that applications may control their memory allocation strategy.
• Scalable performance and footprint. Theconfiguration settingsallow this library to be tailored to a system's resources.
Please see https://github.com/aws/aws-iot-device-sdk-embedded-C/tree/main/demos/mqtt for example code demonstrating integration with TLS.
1.1 Memory Requirements
Memory requirements of the MQTT library.
Code size of coreMQTT library files (sizes generated with GCC for ARM Cortex-M toolchain)
File No Optimization (as-
serts enabled)
With -O1 Optimization (asserts disabled)
With -Os Optimization (asserts disabled)
core_mqtt.c 13.6K 6.9K 6.3K
core_mqtt_state.c 6.0K 3.0K 2.3K
core_mqtt_serializer.c 12.3K 5.6K 5.1K
Total estimates 31.9K 15.5K 13.7K
2 Overview
Chapter 2
Design
Architecture of the MQTT library.
This MQTT client library provides an implementation of the MQTT 3.1.1 specification. It is optimized for resource constrained devices and does not allocate any memory.
2.1 Interfaces and Callbacks
The MQTT library relies on interfaces to dissociate itself from platform specific functionality, such as the transport layer or maintaining time. Interfaces used by MQTT are simply function pointers with expectations of behavior.
The MQTT library expects the application to provide implementations for the following interfaces:
Function Pointer Use
TransportRecv_t Receiving data from an established network connection.
TransportSend_t Sending data over an established network connection.
MQTTGetCurrentTimeFunc_t Obtaining timestamps for complying with user-specified timeouts and the MQTT keep-alive mechanism.
MQTTEventCallback_t Returning packets received from the network to the user application after dese- rialization.
2.2 Serializers and Deserializers
The managed MQTT API in core_mqtt.h uses a set of serialization and deserialization functions declared in core_mqtt_serializer.h. If a user does not want to use the functionality provided by the managed API, these low-level functions can be used directly:
• MQTT_GetConnectPacketSize
• MQTT_SerializeConnect
• MQTT_GetSubscribePacketSize
4 Design
• MQTT_SerializeSubscribe
• MQTT_GetUnsubscribePacketSize
• MQTT_SerializeUnsubscribe
• MQTT_GetPublishPacketSize
• MQTT_SerializePublish
• MQTT_SerializePublishHeader
• MQTT_SerializeAck
• MQTT_GetDisconnectPacketSize
• MQTT_SerializeDisconnect
• MQTT_GetPingreqPacketSize
• MQTT_SerializePingreq
• MQTT_DeserializePublish
• MQTT_DeserializeAck
• MQTT_GetIncomingPacketTypeAndLength
2.3 Sessions and State
The MQTT 3.1.1 protocol allows for a client and server to maintain persistent sessions, which can be resumed after a reconnect. The elements of a session stored by this client library consist of the states of incomplete pub- lishes with Quality of Service levels of 1 (at least once), or 2 (exactly once). These states are stored in the ar- raysMQTTContext_t::outgoingPublishRecordsand MQTTContext_t::incomingPublishRecords; the length of each of these arrays can be configured with MQTT_STATE_ARRAY_MAX_COUNT. This library does not store any subscription information, nor any information for QoS 0 publishes.
When resuming a persistent session, the client library will resend PUBRELs for all PUBRECs that had been received for incomplete outgoing QoS 2 publishes. If the broker does not resume the session, then all state information in the client will be reset.
Note
The library stores only the state of incomplete publishes and not the publish payloads. It is the responsibility of the user application to save publish payloads until the publish is complete. If a persistent session is resumed, thenMQTT_PublishToResendshould be called to obtain the packet identifiers of incomplete publishes, fol- lowed by a call toMQTT_Publishto resend the unacknowledged publish.
2.5 Keep-Alive 5
2.4 Packet Reception
MQTT Packets are received from the network with calls to MQTT_ProcessLooporMQTT_ReceiveLoop. These functions are mostly identical, with the exception of keep-alive; the former sends ping requests and processes ping responses to ensure the MQTT session does not remain idle for more than the keep-alive interval, while the latter does not. Since calls toMQTT_Publish,MQTT_Subscribe, andMQTT_Unsubscribeonly send packets and do not wait for acknowledgments, a call toMQTT_ProcessLoop orMQTT_ReceiveLoopmust follow in order to receive any expected acknowledgment. The exception isMQTT_Connect; since a MQTT session cannot be considered established until the server acknowledges a CONNECT packet with a CONNACK, the function waits until the CO←-
NNACK is received.
2.4.1 Runtime Timeouts passed to MQTT library
MQTT_Connect,MQTT_ProcessLoop, andMQTT_ReceiveLoopall accept a timeout parameter for packet recep- tion.
For theMQTT_Connect, if this value is set to 0, then instead of a time-based loop, it will attempt to call the transport
receive function up to a maximum number of retries, which is defined byMQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT.
ForMQTT_ProcessLoopandMQTT_ReceiveLoop, the timeout value represents the minimum duration that will be spent in the function, provided there are no network errors. Should the timeout be set to 0, then the loop will run for a single iteration. A single iteration of a loop consists of an attempt to receive a single byte from the network, and if the single byte receive was successful, then attempt(s) to receive the rest of the packet (with retry attempts governed byMQTT_RECV_POLLING_TIMEOUT_MS), followed by sending acknowledgement response, if needed (with retry attempts governed by MQTT_SEND_RETRY_TIMEOUT_MS), and then, finally deserialization of the packet received and a call to the application callback. If the first read did not succeed, then instead the library checks if a ping request needs to be sent (only for the process loop).
See the below diagrams for a representation of the above flows:
MQTT Connect Diagram MQTT ProcessLoop Diagram MQTT ReceiveLoop Diagram
2.5 Keep-Alive
The MQTT standard specifies a keep-alive mechanism to detect half-open or otherwise unusable network connec- tions. An MQTT client will send periodic ping requests (PINGREQ) to the server if the connection is idle. The MQTT server must respond to ping requests with a ping response (PINGRESP).
In this library,MQTT_ProcessLoophandles sending of PINGREQs and processing corresponding PINGRESPs to comply with the keep-alive interval set inMQTTContext_t::keepAliveIntervalSec.
The standard does not specify the time duration within which the server has to respond to a ping re- quest, noting only a "reasonable amount of time". If the response to a ping request is not received within MQTT_PINGRESP_TIMEOUT_MS, this library assumes that the connection is dead.
If MQTT_ReceiveLoopis used instead ofMQTT_ProcessLoop, then no ping requests are sent. The application must ensure the connection does not remain idle for more than the keep-alive interval by callingMQTT_Pingto send ping requests. The timestamp inMQTTContext_t::lastPacketTimeindicates when a packet was last sent by the library.
Sending any ping request sets the MQTTContext_t::waitingForPingResp flag. This flag is cleared by MQTT_ProcessLoop when a ping response is received. If MQTT_ReceiveLoop is used instead, then this flag must be cleared manually by the application's callback.
Generated by Doxygen
6 Design
Chapter 3
Configurations
Configurations of the MQTT Library.
configpagestyle
Some configuration settings are C pre-processor constants, and some are function-like macros for logging. They can be set with a#definein the config file (core_mqtt_config.h) or by using a compiler option such as -D in gcc.
3.1 MQTT_DO_NOT_USE_CUSTOM_CONFIG
Define this macro to build the MQTT library without the custom config file core_mqtt_config.h. Without the custom config, the MQTT library builds with default values of config macros defined incore_mqtt_config_defaults.hfile.
If a custom config is provided, then MQTT_DO_NOT_USE_CUSTOM_CONFIG should not be defined.
3.2 MQTT_STATE_ARRAY_MAX_COUNT
Determines the maximum number of MQTT PUBLISH messages, pending acknowledgment at a time, that are supported for incoming and outgoing direction of messages, separately. QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before they can be completed. While they are awaiting the acknowledgment, the client must maintain information about their state. The value of this macro sets the limit on how many simultaneous PUBLISH states an MQTT context maintains, separately, for both incoming and outgoing direction of PUBLISHes.
Note
The MQTT context maintains separate state records for outgoing and incoming PUBLISHes, and thus, 2∗ MQTT_STATE_ARRAY_MAX_COUNT amount of memory is statically allocated for the state records.
Possible values: Any positive 32 bit integer.
Default value:10
8 Configurations
3.3 MQTT_PINGRESP_TIMEOUT_MS
Number of milliseconds to wait for a ping response to a ping request as part of the keep-alive mechanism. If a ping response is not received before this timeout, thenMQTT_ProcessLoopwill returnMQTTKeepAliveTimeout.
Note
If a dummy implementation of theMQTTGetCurrentTimeFunc_ttimer function, is supplied to the library, then the keep-alive mechanism is not supported by theMQTT_ProcessLoopAPI function. In that case, the value ofMQTT_PINGRESP_TIMEOUT_MSis irrelevant to the behavior of the library.
Possible values: Any positive integer up to SIZE_MAX.
Default value:500
3.4 MQTT_RECV_POLLING_TIMEOUT_MS
The maximum duration between non-empty network reads while receiving an MQTT packet via the MQTT_ProcessLoop or MQTT_ReceiveLoop API functions. When an incoming MQTT packet is detected, the transport receive function may be called multiple times until all of the expected number of bytes of the packet are received. This timeout represents the maximum polling duration that is allowed without any data reception from the network for the incoming packet.
If the timeout expires, theMQTT_ProcessLoopandMQTT_ReceiveLoopfunctions returnMQTTRecvFailed.
Note
If a dummy implementation of theMQTTGetCurrentTimeFunc_ttimer function, is supplied to the library, then MQTT_RECV_POLLING_TIMEOUT_MSMUST be set to 0.
Possible values: Any positive 32 bit integer. Recommended to use a small timeout value.
Default value:10
3.5 MQTT_SEND_RETRY_TIMEOUT_MS
The maximum duration between non-empty network transmissions while sending an MQTT packet via the MQTT_ProcessLooporMQTT_ReceiveLoopAPI functions. When sending an MQTT packet, the transport send function may be called multiple times until all of the required number of bytes are sent. This timeout represents the maximum duration that is allowed for no data transmission over the network through the transport send function.
If the timeout expires, theMQTT_ProcessLoopandMQTT_ReceiveLoopfunctions returnMQTTSendFailed.
Note
If a dummy implementation of theMQTTGetCurrentTimeFunc_ttimer function, is supplied to the library, then MQTT_SEND_RETRY_TIMEOUT_MSMUST be set to 0.
Possible values: Any positive 32 bit integer. Recommended to use a small timeout value.
Default value:10
3.6 MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT 9
3.6 MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT
The number of retries for receiving CONNACK. The MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT will be used only when the timeoutMs parameter ofMQTT_Connectis passed as 0 . The transport receive for CONNACK will be retried MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT times before timing out. A value of 0 for this config will cause the transport receive for CONNACK to be invoked only once.
Possible values: Any positive 16 bit integer.
Default value:5
3.7 LogError
Macro that is called in the MQTT library for logging "Error" level messages. To enable error level logging in the MQTT library, this macro should be mapped to the application-specific logging implementation that supports error logging.
Note
This logging macro is called in the MQTT library with parameters wrapped in double parentheses to be I←-
SO C89/C90 standard compliant. For a reference POSIX implementation of the logging macros, refer to core_mqtt_config.h files, and the logging-stack in demos folder of the AWS IoT Embedded C SDK repository.
Default value: Error logging is turned off, and no code is generated for calls to the macro in the MQTT library on compilation.
3.8 LogWarn
Macro that is called in the MQTT library for logging "Warning" level messages. To enable warning level logging in the MQTT library, this macro should be mapped to the application-specific logging implementation that supports warning logging.
Note
This logging macro is called in the MQTT library with parameters wrapped in double parentheses to be I←-
SO C89/C90 standard compliant. For a reference POSIX implementation of the logging macros, refer to core_mqtt_config.h files, and the logging-stack in demos folder of the AWS IoT Embedded C SDK repository.
Default value: Warning logs are turned off, and no code is generated for calls to the macro in the MQTT library on compilation.
3.9 LogInfo
Macro that is called in the MQTT library for logging "Info" level messages. To enable info level logging in the MQTT library, this macro should be mapped to the application-specific logging implementation that supports info logging.
Note
This logging macro is called in the MQTT library with parameters wrapped in double parentheses to be I←-
SO C89/C90 standard compliant. For a reference POSIX implementation of the logging macros, refer to core_mqtt_config.h files, and the logging-stack in demos folder of the AWS IoT Embedded C SDK repository.
Default value: Info logging is turned off, and no code is generated for calls to the macro in the MQTT library on compilation.
Generated by Doxygen
10 Configurations
3.10 LogDebug
Macro that is called in the MQTT library for logging "Debug" level messages. To enable debug level logging from MQTT library, this macro should be mapped to the application-specific logging implementation that supports debug logging.
Note
This logging macro is called in the MQTT library with parameters wrapped in double parentheses to be I←-
SO C89/C90 standard compliant. For a reference POSIX implementation of the logging macros, refer to core_mqtt_config.h files, and the logging-stack in demos folder of the AWS IoT Embedded C SDK repository.
Default value: Debug logging is turned off, and no code is generated for calls to the macro in the MQTT library on compilation.
Chapter 4
Functions
Primary functions of the MQTT library:
MQTT_Init MQTT_Connect MQTT_Subscribe MQTT_Publish MQTT_Ping MQTT_Unsubscribe MQTT_Disconnect MQTT_ProcessLoop MQTT_ReceiveLoop MQTT_GetPacketId
MQTT_GetSubAckStatusCodes MQTT_Status_strerror
MQTT_PublishToResend
Serializer functions of the MQTT library:
MQTT_GetConnectPacketSize MQTT_SerializeConnect MQTT_GetSubscribePacketSize MQTT_SerializeSubscribe
MQTT_GetUnsubscribePacketSize MQTT_SerializeUnsubscribe MQTT_GetPublishPacketSize MQTT_SerializePublish MQTT_SerializePublishHeader MQTT_SerializeAck
MQTT_GetDisconnectPacketSize MQTT_SerializeDisconnect MQTT_GetPingreqPacketSize MQTT_SerializePingreq MQTT_DeserializePublish MQTT_DeserializeAck
MQTT_GetIncomingPacketTypeAndLength
12 Functions
4.1 MQTT_Init
Initialize an MQTT context.
MQTTStatus_t MQTT_Init( MQTTContext_t * pContext,
const TransportInterface_t* pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback,
const MQTTFixedBuffer_t * pNetworkBuffer );
This function must be called on aMQTTContext_tbefore any other function.
Note
The MQTTGetCurrentTimeFunc_t function for querying time must be defined. If there is no time imple- mentation, it is the responsibility of the application to provide a dummy function to always return 0, pro- vide 0 timeouts for all calls toMQTT_Connect, MQTT_ProcessLoop, andMQTT_ReceiveLoopand config- ure the MQTT_RECV_POLLING_TIMEOUT_MSand MQTT_SEND_RETRY_TIMEOUT_MSconfigurations to be 0. This will result in loop functions running for a single iteration, and MQTT_Connect relying on MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNTto receive the CONNACK packet.
Parameters
in pContext The context to initialize.
in pTransportInterface The transport interface to use with the context.
in getTimeFunction The time utility function to use with the context.
in userCallback The user callback to use with the context to notify about incoming packet events.
in pNetworkBuffer Network buffer provided for the context.
Returns
MQTTBadParameterif invalid parameters are passed;MQTTSuccessotherwise.
Example
// Function for obtaining a timestamp.
uint32_t getTimeStampMs();
// Callback function for receiving packets.
void eventCallback(
MQTTContext_t * pContext, MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo );
// 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_tbytes );
MQTTContext_t mqttContext;
TransportInterface_t transport;
MQTTFixedBuffer_t fixedBuffer;
uint8_t buffer[ 1024 ];
// Clear context.
memset( ( void * ) &mqttContext, 0x00, sizeof( MQTTContext_t ) );
// Set transport interface members.
transport.pNetworkInterface = &someNetworkInterface;
transport.send = networkSend;
transport.recv = networkRecv;
// 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.
}
4.2 MQTT_Connect 13
4.2 MQTT_Connect
Establish an MQTT session.
MQTTStatus_t MQTT_Connect( MQTTContext_t * pContext,
const MQTTConnectInfo_t * pConnectInfo, const MQTTPublishInfo_t * pWillInfo, uint32_t timeoutMs,
bool * pSessionPresent );
This function will send MQTT CONNECT packet and receive a CONNACK packet. The send and receive from the network is done through the transport interface.
The maximum time this function waits for a CONNACK is decided in one of the following ways:
1. IftimeoutMsis greater than 0:MQTTContext_t.getTimeis used to ensure that the function does not wait more thantimeoutMsfor CONNACK.
2. IftimeoutMsis 0: The network receive for CONNACK is retried up to the number of times configured by MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT.
Note
If a dummy MQTTGetCurrentTimeFunc_twas passed toMQTT_Init, then a timeout value of 0 MUST be passed to the API, and theMQTT_RECV_POLLING_TIMEOUT_MSandMQTT_SEND_RETRY_TIMEOUT_MS timeout configurations MUST be set to 0.
Parameters
in pContext Initialized MQTT context.
in pConnectInfo MQTT CONNECT packet information.
in pWillInfo Last Will and Testament. Pass NULL if Last Will and Testament is not used.
in timeoutMs Maximum time in milliseconds to wait for a CONNACK packet. A zero timeout makes use of the retries for receiving CONNACK as configured with
MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT.
out pSessionPresent Whether a previous session was present. Only relevant if not establishing a clean session.
Returns
MQTTNoMemoryif theMQTTContext_t.networkBufferis too small to hold the MQTT packet;MQTTBadParameter if invalid parameters are passed;MQTTSendFailedif transport send failed;MQTTRecvFailedif transport re- ceive failed for CONNACK; MQTTNoDataAvailable if no data available to receive in transport until the timeoutMsfor CONNACK;MQTTSuccessotherwise.
Note
This API may spend more time than provided in the timeoutMS parameters in certain conditions as listed below:
1. Timeouts are incorrectly configured - If the timeoutMS is less than the transport receive timeout and if a C←-
ONNACK packet is not received within the transport receive timeout, the API will spend the transport receive timeout (which is more time than the timeoutMs). It is the case of incorrect timeout configuration as the timeoutMs parameter passed to this API must be greater than the transport receive timeout. Please refer to the transport interface documentation for more details about timeout configurations.
Generated by Doxygen
14 Functions
2. Partial CONNACK packet is received right before the expiry of the timeout - It is possible that first two bytes of CONNACK packet (packet type and remaining length) are received right before the expiry of the timeoutMS.
In that case, the API makes one more network receive call in an attempt to receive the remaining 2 bytes. In the worst case, it can happen that the remaining 2 bytes are never received and this API will end up spending timeoutMs + transport receive timeout.
Example
// 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 );
// 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" );
// Send the connect packet. Use 100 ms as the timeout to wait for the CONNACK packet.
status = MQTT_Connect( pContext, &connectInfo, &willInfo, 100, &sessionPresent );
if( status == MQTTSuccess ) {
// Since we requested a clean session, this must be false assert( sessionPresent == false );
// Do something with the connection.
}
4.3 MQTT_Subscribe
Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.
MQTTStatus_t MQTT_Subscribe( MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
uint16_t packetId );
Parameters
in pContext Initialized MQTT context.
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
in packetId Packet ID generated byMQTT_GetPacketId.
Returns
MQTTNoMemoryif theMQTTContext_t.networkBufferis too small to hold the MQTT packet;MQTTBadParameter if invalid parameters are passed;MQTTSendFailedif transport write failed;MQTTSuccessotherwise.
Example
// Variables used in this example.
MQTTStatus_t status;
4.5 MQTT_Ping 15
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 ] );
}
// Obtain a new packet id for the subscription.
packetId = MQTT_GetPacketId( pContext );
status = MQTT_Subscribe( pContext, &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId );
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.
}
4.4 MQTT_Publish
Publishes a message to the given topic name.
MQTTStatus_t MQTT_Publish( MQTTContext_t * pContext,
const MQTTPublishInfo_t * pPublishInfo, uint16_t packetId );
Parameters
in pContext Initialized MQTT context.
in pPublishInfo MQTT PUBLISH packet parameters.
in packetId packet ID generated byMQTT_GetPacketId.
Returns
MQTTNoMemoryif pBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid parameters are passed;MQTTSendFailedif transport write failed;MQTTSuccessotherwise.
Example
// 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!" );
// Packet ID is needed for QoS > 0.
packetId = MQTT_GetPacketId( pContext );
status = MQTT_Publish( pContext, &publishInfo, packetId );
if( status == MQTTSuccess ) {
// Since the QoS is > 0, we will need to call MQTT_ReceiveLoop() // or MQTT_ProcessLoop() to process the publish acknowledgments.
}
4.5 MQTT_Ping
Sends an MQTT PINGREQ to broker.
MQTTStatus_t MQTT_Ping( MQTTContext_t * pContext );
Generated by Doxygen
16 Functions
Parameters
in pContext Initialized and connected MQTT context.
Returns
MQTTNoMemoryif pBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid parameters are passed;MQTTSendFailedif transport write failed;MQTTSuccessotherwise.
4.6 MQTT_Unsubscribe
Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.
MQTTStatus_t MQTT_Unsubscribe( MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
uint16_t packetId );
Parameters
in pContext Initialized MQTT context.
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
in packetId packet ID generated byMQTT_GetPacketId.
Returns
MQTTNoMemoryif theMQTTContext_t.networkBufferis too small to hold the MQTT packet;MQTTBadParameter if invalid parameters are passed;MQTTSendFailedif transport write failed;MQTTSuccessotherwise.
Example
// 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 );
status = MQTT_Unsubscribe( pContext, &unsubscribeList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId );
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.
}
4.7 MQTT_Disconnect
Disconnect an MQTT session.
MQTTStatus_t MQTT_Disconnect( MQTTContext_t* pContext );
4.8 MQTT_ProcessLoop 17
Parameters
in pContext Initialized and connected MQTT context.
Returns
MQTTNoMemoryif theMQTTContext_t.networkBufferis too small to hold the MQTT packet;MQTTBadParameter if invalid parameters are passed;MQTTSendFailedif transport send failed;MQTTSuccessotherwise.
4.8 MQTT_ProcessLoop
Loop to receive packets from the transport interface. Handles keep alive.
MQTTStatus_t MQTT_ProcessLoop( MQTTContext_t * pContext, uint32_t timeoutMs );
Note
Passing a timeout value of 0 will run the loop for a single iteration.
If a dummy timer function,MQTTGetCurrentTimeFunc_t, is passed to the library, then the keep-alive mech- anism is not supported by theMQTT_ProcessLoopAPI. In that case, theMQTT_ReceiveLoopAPI function should be used instead.
Parameters
in pContext Initialized and connected MQTT context.
in timeoutMs Minimum time in milliseconds that the receive loop will run, unless an error occurs.
Note
Calling this function blocks the calling context for a time period that depends on the passedtimeoutMs, the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MSandMQTT_SEND_RETRY_TIMEOUT_MS, and the underlying transport interface implementation timeouts, unless an error occurs. The blocking period also depends on the execution time of theMQTTEventCallback_tcallback supplied to the library. It is rec- ommended that the suppliedMQTTEventCallback_tcallback does not contain blocking operations to prevent potential non-deterministic blocking period of theMQTT_ProcessLoopAPI call.
Returns
MQTTBadParameter if context is NULL; MQTTRecvFailed if a network error occurs during reception;
MQTTSendFailed if a network error occurs while sending an ACK or PINGREQ; MQTTBadResponse if an invalid packet is received; MQTTKeepAliveTimeout if the server has not sent a PINGRESP before MQTT_PINGRESP_TIMEOUT_MSmilliseconds; MQTTIllegalStateif an incoming QoS 1/2 publish or ack causes an invalid transition for the internal state machine;MQTTSuccesson success.
Example
// Variables used in this example.
MQTTStatus_t status;
uint32_t timeoutMs = 100;
// This context is assumed to be initialized and connected.
MQTTContext_t * pContext;
while( true ) {
status = MQTT_ProcessLoop( pContext, timeoutMs );
if( status != MQTTSuccess )
Generated by Doxygen
18 Functions
{
// Determine the error. It’s possible we might need to disconnect // the underlying transport connection.
} else {
// Other application functions.
} }
4.9 MQTT_ReceiveLoop
Loop to receive packets from the transport interface. Does not handle keep alive.
MQTTStatus_t MQTT_ReceiveLoop( MQTTContext_t * pContext, uint32_t timeoutMs );
Note
Passing a timeout value of 0 will run the loop for a single iteration. If a dummyMQTTGetCurrentTimeFunc_t
was passed toMQTT_Init, then the timeout value passed to the API MUST be 0, and theMQTT_RECV_POLLING_TIMEOUT_MS andMQTT_SEND_RETRY_TIMEOUT_MStimeout configurations MUST be set to 0.
Parameters
in pContext Initialized and connected MQTT context.
in timeoutMs Minimum time in milliseconds that the receive loop will run, unless an error occurs.
Note
Calling this function blocks the calling context for a time period that depends on the passedtimeoutMs, the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MSandMQTT_SEND_RETRY_TIMEOUT_MS, and the underlying transport interface implementation timeouts, unless an error occurs. The blocking period also depends on the execution time of theMQTTEventCallback_tcallback supplied to the library. It is rec- ommended that the suppliedMQTTEventCallback_tcallback does not contain blocking operations to prevent potential non-deterministic blocking period of theMQTT_ReceiveLoopAPI call.
Returns
MQTTBadParameter if context is NULL; MQTTRecvFailed if a network error occurs during reception;
MQTTSendFailedif a network error occurs while sending an ACK or PINGREQ;MQTTBadResponseif an invalid packet is received;MQTTIllegalStateif an incoming QoS 1/2 publish or ack causes an invalid transition for the internal state machine;MQTTSuccesson success.
Example
// Variables used in this example.
MQTTStatus_t status;
uint32_t timeoutMs = 100;
uint32_t keepAliveMs = 60 * 1000;
// This context is assumed to be initialized and connected.
MQTTContext_t * pContext;
while( true ) {
status = MQTT_ReceiveLoop( pContext, timeoutMs );
if( status != MQTTSuccess ) {
// Determine the error. It’s possible we might need to disconnect // the underlying transport connection.
} else {
// Since this function does not send pings, the application may need
4.11 MQTT_GetSubAckStatusCodes 19
// to in order to comply with keep alive.
if( ( pContext->getTime() - pContext->lastPacketTime ) > keepAliveMs ) {
status = MQTT_Ping( pContext );
}
// Other application functions.
} }
4.10 MQTT_GetPacketId
Get a packet ID that is valid according to the MQTT 3.1.1 spec.
uint16_t MQTT_GetPacketId( MQTTContext_t * pContext );
Parameters
in pContext Initialized MQTT context.
Returns
A non-zero number.
4.11 MQTT_GetSubAckStatusCodes
Parses the payload of an MQTT SUBACK packet that contains status codes corresponding to topic filter subscription requests from the original subscribe packet.
MQTTStatus_t MQTT_GetSubAckStatusCodes( const MQTTPacketInfo_t * pSubackPacket, uint8_t ** pPayloadStart,
size_t * pPayloadSize );
Each return code in the SUBACK packet corresponds to a topic filter in the SUBSCRIBE Packet being acknowl- edged. The status codes can be one of the following:
• 0x00 - Success - Maximum QoS 0
• 0x01 - Success - Maximum QoS 1
• 0x02 - Success - Maximum QoS 2
• 0x80 - Failure Refer toMQTTSubAckStatus_tfor the status codes.
Parameters
in pSubackPacket The SUBACK packet whose payload is to be parsed.
out pPayloadStart This is populated with the starting address of the payload (or return codes for topic filters) in the SUBACK packet.
out pPayloadSize This is populated with the size of the payload in the SUBACK packet. It represents the number of topic filters whose SUBACK status is present in the packet.
Returns
Returns one of the following:
• MQTTBadParameterif the input SUBACK packet is invalid.
Generated by Doxygen
20 Functions
• MQTTSuccessif parsing the payload was successful.
Example
// Global variable used in this example.
// This is assumed to be the subscription list in the original SUBSCRIBE packet.
MQTTSubscribeInfo_t pSubscribes[ NUMBER_OF_SUBSCRIPTIONS ];
// MQTT_GetSubAckStatusCodes is intended to be used from the application
// callback that is called by the library in MQTT_ProcessLoop or MQTT_ReceiveLoop.
void eventCallback(
MQTTContext_t * pContext, MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo )
{
MQTTStatus_t status = MQTTSuccess;
uint8_t * pCodes;
size_t numCodes;
if( pPacketInfo->type == MQTT_PACKET_TYPE_SUBACK ) {
status = MQTT_GetSubAckStatusCodes( pPacketInfo, &pCodes, &numCodes );
// Since the pointers to the payload and payload size are not NULL, and // we use the packet info struct passed to the app callback (verified // to be valid by the library), this function must return success.
assert( status == MQTTSuccess );
// The server must send a response code for each topic filter in the // original SUBSCRIBE packet.
assert( numCodes == NUMBER_OF_SUBSCRIPTIONS );
for( int i = 0; i < numCodes; i++ ) {
// The only failure code is 0x80 = MQTTSubAckFailure.
if( pCodes[ i ] == MQTTSubAckFailure ) {
// The subscription failed, we may want to retry the
// subscription in pSubscribes[ i ] outside of this callback.
} else {
// The subscription was granted, but the maximum QoS may be // lower than what was requested. We can verify the granted QoS.
if( pSubscribes[ i ].qos != pCodes[ i ] ) {
LogWarn( (
"Requested QoS %u, but granted QoS %u for %s",
pSubscribes[ i ].qos, pCodes[ i ], pSubscribes[ i ].pTopicFilter ) );
} } } }
// Handle other packet types.
}
4.12 MQTT_Status_strerror
Error code to string conversion for MQTT statuses.
const char * MQTT_Status_strerror( MQTTStatus_t status );
Parameters
in status The status to convert to a string.
Returns
The string representation of the status.
4.13 MQTT_PublishToResend
Get the packet ID of next pending publish to be resent.
4.14 MQTT_GetConnectPacketSize 21
uint16_t MQTT_PublishToResend( const MQTTContext_t* pMqttContext, MQTTStateCursor_t * pCursor );
This function will need to be called to get the packet for which a publish need to be sent when a session is reestab- lished. Calling this function repeatedly until packet id is 0 will give all the packets for which a publish need to be resent in the correct order.
Parameters
in pMqttContext Initialized MQTT context.
in,out pCursor Index at which to start searching.
Example
// For this example assume this function returns an outgoing unacknowledged // QoS 1 or 2 publish from its packet identifier.
MQTTPublishInfo_t * getPublish( uint16_t packetID );
// Variables used in this example.
MQTTStatus_t status;
MQTTStateCursor_t cursor = MQTT_STATE_CURSOR_INITIALIZER;
bool sessionPresent;
uint16_t packetID;
MQTTPublishInfo_t * pResendPublish = NULL;
MQTTConnectInfo_t connectInfo = { 0 };
// This is assumed to have been initialized before the call to MQTT_Connect().
MQTTContext_t * pContext;
// Set clean session to false to attempt session resumption.
connectInfo.cleanSession = false;
connectInfo.pClientIdentifier = "someClientID";
connectInfo.clientIdentifierLength = strlen( connectInfo.pClientIdentifier );
connectInfo.keepAliveSeconds = 60;
// Optional connect parameters are not relevant to this example.
// Create an MQTT connection. Use 100 milliseconds as a timeout.
status = MQTT_Connect( pContext, &connectInfo, NULL, 100, &sessionPresent );
if( status == MQTTSuccess ) {
if( sessionPresent ) {
// Loop while packet ID is nonzero.
while( ( packetID = MQTT_PublishToResend( pContext, &cursor ) ) != 0 ) {
// Assume this function will succeed.
pResendPublish = getPublish( packetID );
// Set DUP flag.
pResendPublish->dup = true;
status = MQTT_Publish( pContext, pResendPublish, packetID );
if( status != MQTTSuccess ) {
// Application can decide how to handle a failure.
} } } else {
// The broker did not resume a session, so we can clean up the // list of outgoing publishes.
} }
4.14 MQTT_GetConnectPacketSize
Get the size and Remaining Length of an MQTT CONNECT packet.
MQTTStatus_t MQTT_GetConnectPacketSize( const MQTTConnectInfo_t * pConnectInfo, const MQTTPublishInfo_t * pWillInfo, size_t * pRemainingLength,
size_t * pPacketSize );
This function must be called beforeMQTT_SerializeConnectin order to get the size of the MQTT CONNECT packet that is generated fromMQTTConnectInfo_tand optionalMQTTPublishInfo_t. The size of theMQTTFixedBuffer_t supplied toMQTT_SerializeConnectmust be at leastpPacketSize. The providedpConnectInfoandp←-
WillInfoare valid for serialization withMQTT_SerializeConnectonly if this function returnsMQTTSuccess. The remaining length returned inpRemainingLengthand the packet size returned inpPacketSizeare valid only if this function returnsMQTTSuccess.
Generated by Doxygen
22 Functions
Parameters
in pConnectInfo MQTT CONNECT packet parameters.
in pWillInfo Last Will and Testament. Pass NULL if not used.
out pRemainingLength The Remaining Length of the MQTT CONNECT packet.
out pPacketSize The total size of the MQTT CONNECT packet.
Returns
MQTTBadParameterif the packet would exceed the size allowed by the MQTT spec;MQTTSuccessother- wise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTConnectInfo_t connectInfo = { 0 };
MQTTPublishInfo_t willInfo = { 0 };
size_t remainingLength = 0, packetSize = 0;
// Initialize the connection info, the details are out of scope for this example.
initializeConnectInfo( &connectInfo );
// Initialize the optional will info, the details are out of scope for this example.
initializeWillInfo( &willInfo );
// Get the size requirement for the connect packet.
status = MQTT_GetConnectPacketSize(
&connectInfo, &willInfo, &remainingLength, &packetSize );
if( status == MQTTSuccess ) {
// The application should allocate or use a static #MQTTFixedBuffer_t // of size >= packetSize to serialize the connect request.
}
4.15 MQTT_SerializeConnect
Serialize an MQTT CONNECT packet in the given fixed bufferpFixedBuffer.
MQTTStatus_t MQTT_SerializeConnect( const MQTTConnectInfo_t * pConnectInfo, const MQTTPublishInfo_t * pWillInfo, size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
MQTT_GetConnectPacketSizeshould be called withpConnectInfoandpWillInfobefore invoking this func- tion to get the size of the requiredMQTTFixedBuffer_tandremainingLength. TheremainingLengthmust be the same as returned byMQTT_GetConnectPacketSize. TheMQTTFixedBuffer_tmust be at least as large as the size returned byMQTT_GetConnectPacketSize.
Parameters
in pConnectInfo MQTT CONNECT packet parameters.
in pWillInfo Last Will and Testament. Pass NULL if not used.
in remainingLength Remaining Length provided byMQTT_GetConnectPacketSize.
out pFixedBuffer Buffer for packet serialization.
Returns
MQTTNoMemoryif pFixedBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid param- eters are passed;MQTTSuccessotherwise.
Example
4.16 MQTT_GetSubscribePacketSize 23
// Variables used in this example.
MQTTStatus_t status;
MQTTConnectInfo_t connectInfo = { 0 };
MQTTPublishInfo_t willInfo = { 0 };
MQTTFixedBuffer_t fixedBuffer;
uint8_t buffer[ BUFFER_SIZE ];
size_t remainingLength = 0, packetSize = 0;
fixedBuffer.pBuffer = buffer;
fixedBuffer.size = BUFFER_SIZE;
// Assume connectInfo and willInfo are initialized. Get the size requirement for // the connect packet.
status = MQTT_GetConnectPacketSize(
&connectInfo, &willInfo, &remainingLength, &packetSize );
assert( status == MQTTSuccess );
assert( packetSize <= BUFFER_SIZE );
// Serialize the connect packet into the fixed buffer.
status = MQTT_SerializeConnect( &connectInfo, &willInfo, remainingLength, &fixedBuffer );
if( status == MQTTSuccess ) {
// The connect packet can now be sent to the broker.
}
4.16 MQTT_GetSubscribePacketSize
Get packet size and Remaining Length of an MQTT SUBSCRIBE packet.
MQTTStatus_t MQTT_GetSubscribePacketSize( const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
size_t * pRemainingLength, size_t * pPacketSize );
This function must be called beforeMQTT_SerializeSubscribein order to get the size of the MQTT SUBSCRI←-
BE packet that is generated from the list ofMQTTSubscribeInfo_t. The size of theMQTTFixedBuffer_t supplied to MQTT_SerializeSubscribemust be at least pPacketSize. The providedpSubscriptionListis valid for serialization withMQTT_SerializeSubscribeonly if this function returnsMQTTSuccess. The remaining length returned inpRemainingLengthand the packet size returned inpPacketSizeare valid only if this function returnsMQTTSuccess.
Parameters
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
out pRemainingLength The Remaining Length of the MQTT SUBSCRIBE packet.
out pPacketSize The total size of the MQTT SUBSCRIBE packet.
Returns
MQTTBadParameterif the packet would exceed the size allowed by the MQTT spec;MQTTSuccessother- wise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 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 ] );
}
// Get the size requirement for the subscribe packet.
Generated by Doxygen
24 Functions
status = MQTT_GetSubscribePacketSize(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &remainingLength, &packetSize );
if( status == MQTTSuccess ) {
// The application should allocate or use a static #MQTTFixedBuffer_t // of size >= packetSize to serialize the subscribe request.
}
4.17 MQTT_SerializeSubscribe
Serialize an MQTT SUBSCRIBE packet in the given buffer.
MQTTStatus_t MQTT_SerializeSubscribe( const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
uint16_t packetId, size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
MQTT_GetSubscribePacketSizeshould be called withpSubscriptionListbefore invoking this function to get the size of the requiredMQTTFixedBuffer_tandremainingLength. TheremainingLengthmust be the same as returned byMQTT_GetSubscribePacketSize. TheMQTTFixedBuffer_tmust be at least as large as the size returned byMQTT_GetSubscribePacketSize.
Parameters
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
in packetId packet ID generated byMQTT_GetPacketId.
in remainingLength Remaining Length provided byMQTT_GetSubscribePacketSize.
out pFixedBuffer Buffer for packet serialization.
Returns
MQTTNoMemoryif pFixedBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid param- eters are passed;MQTTSuccessotherwise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 };
MQTTFixedBuffer_t fixedBuffer;
uint8_t buffer[ BUFFER_SIZE ];
size_t remainingLength = 0, packetSize = 0;
uint16_t packetId;
fixedBuffer.pBuffer = buffer;
fixedBuffer.size = BUFFER_SIZE;
// Function to return a valid, unused packet identifier. The details are out of // scope for this example.
packetId = getNewPacketId();
// Assume subscriptionList has been initialized. Get the subscribe packet size.
status = MQTT_GetSubscribePacketSize(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &remainingLength, &packetSize );
assert( status == MQTTSuccess );
assert( packetSize <= BUFFER_SIZE );
// Serialize the subscribe packet into the fixed buffer.
status = MQTT_SerializeSubscribe(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId,
remainingLength,
&fixedBuffer );
if( status == MQTTSuccess ) {
// The subscribe packet can now be sent to the broker.
}
4.19 MQTT_SerializeUnsubscribe 25
4.18 MQTT_GetUnsubscribePacketSize
Get packet size and Remaining Length of an MQTT UNSUBSCRIBE packet.
MQTTStatus_t MQTT_GetUnsubscribePacketSize( const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
size_t * pRemainingLength, size_t * pPacketSize );
This function must be called beforeMQTT_SerializeUnsubscribein order to get the size of the MQTT UNSUBSC←-
RIBE packet that is generated from the list ofMQTTSubscribeInfo_t. The size of theMQTTFixedBuffer_tsupplied toMQTT_SerializeUnsubscribemust be at leastpPacketSize. The providedpSubscriptionListis valid for serialization withMQTT_SerializeUnsubscribeonly if this function returnsMQTTSuccess. The remaining length returned inpRemainingLengthand the packet size returned inpPacketSizeare valid only if this function returnsMQTTSuccess.
Parameters
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
out pRemainingLength The Remaining Length of the MQTT UNSUBSCRIBE packet.
out pPacketSize The total size of the MQTT UNSUBSCRIBE packet.
Returns
MQTTBadParameterif the packet would exceed the size allowed by the MQTT spec;MQTTSuccessother- wise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 };
size_t remainingLength = 0, packetSize = 0;
// Initialize the subscribe info. The details are out of scope for this example.
initializeSubscribeInfo( &subscriptionList[ 0 ] );
// Get the size requirement for the unsubscribe packet.
status = MQTT_GetUnsubscribePacketSize(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &remainingLength, &packetSize );
if( status == MQTTSuccess ) {
// The application should allocate or use a static #MQTTFixedBuffer_t // of size >= packetSize to serialize the unsubscribe request.
}
4.19 MQTT_SerializeUnsubscribe
Serialize an MQTT UNSUBSCRIBE packet in the given buffer.
MQTTStatus_t MQTT_SerializeUnsubscribe( const MQTTSubscribeInfo_t * pSubscriptionList, size_t subscriptionCount,
uint16_t packetId, size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
MQTT_GetUnsubscribePacketSizeshould be called withpSubscriptionListbefore invoking this function to get the size of the requiredMQTTFixedBuffer_tand remainingLength. TheremainingLengthmust be the same as returned byMQTT_GetUnsubscribePacketSize. TheMQTTFixedBuffer_tmust be at least as large as the size returned byMQTT_GetUnsubscribePacketSize.
Generated by Doxygen
26 Functions
Parameters
in pSubscriptionList List of MQTT subscription info.
in subscriptionCount The number of elements in pSubscriptionList.
in packetId packet ID generated byMQTT_GetPacketId.
in remainingLength Remaining Length provided byMQTT_GetUnsubscribePacketSize.
out pFixedBuffer Buffer for packet serialization.
Returns
MQTTNoMemoryif pFixedBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid param- eters are passed;MQTTSuccessotherwise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTSubscribeInfo_t subscriptionList[ NUMBER_OF_SUBSCRIPTIONS ] = { 0 };
MQTTFixedBuffer_t fixedBuffer;
uint8_t buffer[ BUFFER_SIZE ];
size_t remainingLength = 0, packetSize = 0;
uint16_t packetId;
fixedBuffer.pBuffer = buffer;
fixedBuffer.size = BUFFER_SIZE;
// Function to return a valid, unused packet identifier. The details are out of // scope for this example.
packetId = getNewPacketId();
// Assume subscriptionList has been initialized. Get the unsubscribe packet size.
status = MQTT_GetUnsubscribePacketSize(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, &remainingLength, &packetSize );
assert( status == MQTTSuccess );
assert( packetSize <= BUFFER_SIZE );
// Serialize the unsubscribe packet into the fixed buffer.
status = MQTT_SerializeUnsubscribe(
&subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId,
remainingLength,
&fixedBuffer );
if( status == MQTTSuccess ) {
// The unsubscribe packet can now be sent to the broker.
}
4.20 MQTT_GetPublishPacketSize
Get the packet size and remaining length of an MQTT PUBLISH packet.
MQTTStatus_t MQTT_GetPublishPacketSize( const MQTTPublishInfo_t * pPublishInfo, size_t * pRemainingLength,
size_t * pPacketSize );
This function must be called before MQTT_SerializePublish in order to get the size of the MQTT PUB←-
LISH packet that is generated from MQTTPublishInfo_t. The size of the MQTTFixedBuffer_t supplied to MQTT_SerializePublish must be at least pPacketSize. The provided pPublishInfois valid for serial- ization with MQTT_SerializePublish only if this function returns MQTTSuccess. The remaining length returned in pRemainingLengthand the packet size returned inpPacketSizeare valid only if this function returns MQTTSuccess.
Parameters
in pPublishInfo MQTT PUBLISH packet parameters.
out pRemainingLength The Remaining Length of the MQTT PUBLISH packet.
out pPacketSize The total size of the MQTT PUBLISH packet.
4.21 MQTT_SerializePublish 27
Returns
MQTTBadParameterif the packet would exceed the size allowed by the MQTT spec or if invalid parameters are passed;MQTTSuccessotherwise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTPublishInfo_t publishInfo = { 0 };
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!" );
// Get the size requirement for the publish packet.
status = MQTT_GetPublishPacketSize(
&publishInfo, &remainingLength, &packetSize );
if( status == MQTTSuccess ) {
// The application should allocate or use a static #MQTTFixedBuffer_t // of size >= packetSize to serialize the publish.
}
4.21 MQTT_SerializePublish
Serialize an MQTT PUBLISH packet in the given buffer.
MQTTStatus_t MQTT_SerializePublish( const MQTTPublishInfo_t * pPublishInfo, uint16_t packetId,
size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
This function will serialize complete MQTT PUBLISH packet into the given buffer. If the PUBLISH payload can be sent separately, consider usingMQTT_SerializePublishHeader, which will serialize only the PUBLISH header into the buffer.
MQTT_GetPublishPacketSizeshould be called withpPublishInfobefore invoking this function to get the size of the requiredMQTTFixedBuffer_tandremainingLength. TheremainingLengthmust be the same as returned byMQTT_GetPublishPacketSize. TheMQTTFixedBuffer_tmust be at least as large as the size returned byMQTT_GetPublishPacketSize.
Parameters
in pPublishInfo MQTT PUBLISH packet parameters.
in packetId packet ID generated byMQTT_GetPacketId.
in remainingLength Remaining Length provided byMQTT_GetPublishPacketSize.
out pFixedBuffer Buffer for packet serialization.
Returns
MQTTNoMemoryif pFixedBuffer is too small to hold the MQTT packet;MQTTBadParameterif invalid param- eters are passed;MQTTSuccessotherwise.
Example
// Variables used in this example.
MQTTStatus_t status;
MQTTPublishInfo_t publishInfo = { 0 };
MQTTFixedBuffer_t fixedBuffer;
uint8_t buffer[ BUFFER_SIZE ];
size_t remainingLength = 0, packetSize = 0;
uint16_t packetId;
Generated by Doxygen