coreMQTT v5.0.0
MQTT 5.0 Client Library
 
Loading...
Searching...
No Matches
core_mqtt.c File Reference

Implements the user-facing functions in core_mqtt.h. More...

#include <string.h>
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <stddef.h>
#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"

Data Structures

struct  MQTTVec_t
 An opaque structure provided by the library to the MQTTStorePacketForRetransmit function when using MQTTStorePacketForRetransmit. More...
 
struct  IoVecState_t
 Tracks the state of building a scatter-gather IO vector list. More...
 

Macros

#define MQTT_PRE_STATE_UPDATE_HOOK(pContext)
 Hook called just before an update to the MQTT state is made.
 
#define MQTT_POST_STATE_UPDATE_HOOK(pContext)
 Hook called just after an update to the MQTT state has been made.
 
#define CORE_MQTT_SERIALIZED_LENGTH_FIELD_BYTES   ( 2U )
 Bytes required to encode any string length in an MQTT packet header. Length is always encoded in two bytes according to the MQTT specification.
 
#define CORE_MQTT_SUBSCRIBE_PER_TOPIC_VECTOR_LENGTH   ( 3U )
 Number of vectors required to encode one topic filter in a subscribe request. Three vectors are required as there are three fields in the subscribe request namely:
 
#define CORE_MQTT_UNSUBSCRIBE_PER_TOPIC_VECTOR_LENGTH   ( 2U )
 Number of vectors required to encode one topic filter in an unsubscribe request. Two vectors are required as there are two fields in the unsubscribe request namely:
 
#define SET_INCOMING_PUB_FLAG(packetID)   ( ( uint32_t ) ( ( ( uint32_t ) packetID ) | ( ( ( uint32_t ) 1U ) << 16U ) ) )
 Set flag in the packet ID just beyond the actual packet ID.
 

Functions

static int32_t sendBuffer (MQTTContext_t *pContext, const uint8_t *pBufferToSend, size_t bytesToSend)
 Sends provided buffer to network using transport send.
 
static MQTTStatus_t sendConnectWithoutCopy (MQTTContext_t *pContext, const MQTTConnectInfo_t *pConnectInfo, const MQTTPublishInfo_t *pWillInfo, uint32_t remainingLength, const MQTTPropBuilder_t *pPropertyBuilder, const MQTTPropBuilder_t *pWillPropertyBuilder)
 Sends MQTT connect without copying the users data into any buffer.
 
static int32_t sendMessageVector (MQTTContext_t *pContext, TransportOutVector_t *pIoVec, size_t ioVecCount)
 Sends the vector array passed through the parameters over the network.
 
static size_t addEncodedStringToVector (uint8_t serializedLength[CORE_MQTT_SERIALIZED_LENGTH_FIELD_BYTES], const char *const string, uint16_t length, TransportOutVector_t *iterator, uint32_t *updatedLength)
 Add a string and its length after serializing it in a manner outlined by the MQTT specification.
 
static MQTTStatus_t sendSubscribeWithoutCopy (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, uint32_t remainingLength, const MQTTPropBuilder_t *pPropertyBuilder)
 Send Subscribe without copying the users data into any buffer.
 
static MQTTStatus_t sendUnsubscribeWithoutCopy (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, uint32_t remainingLength, const MQTTPropBuilder_t *pPropertyBuilder)
 Send Unsubscribe without copying the users data into any buffer.
 
static uint32_t calculateElapsedTime (uint32_t later, uint32_t start)
 Calculate the interval between two millisecond timestamps, including when the later value has overflowed.
 
static MQTTPubAckType_t getAckFromPacketType (uint8_t packetType)
 Convert a byte indicating a publish ack type to an MQTTPubAckType_t.
 
static int32_t recvExact (MQTTContext_t *pContext, size_t bytesToRecv)
 Receive bytes into the network buffer.
 
static MQTTStatus_t receiveConnackPacket (MQTTContext_t *pContext, MQTTPacketInfo_t incomingPacket)
 Receive a CONNACK packet from the transport interface.
 
static uint8_t getAckTypeToSend (MQTTPublishState_t state)
 Get the correct ack type to send.
 
static MQTTStatus_t sendPublishAcks (MQTTContext_t *pContext, uint16_t packetId, MQTTPublishState_t publishState)
 Send acks for received QoS 1/2 publishes.
 
static MQTTStatus_t handleKeepAlive (MQTTContext_t *pContext)
 Send a keep alive PINGREQ if the keep alive interval has elapsed.
 
static MQTTStatus_t handleIncomingPublish (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket)
 Handle received MQTT PUBLISH packet.
 
static MQTTStatus_t handlePublishAcks (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket)
 Handle received MQTT publish acks.
 
static MQTTStatus_t handleIncomingAck (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket, bool manageKeepAlive)
 Handle received MQTT ack.
 
static MQTTStatus_t receiveSingleIteration (MQTTContext_t *pContext, bool manageKeepAlive)
 Run a single iteration of the receive loop.
 
static MQTTStatus_t validateSubscribeUnsubscribeParams (const MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, MQTTSubscriptionType_t subscriptionType)
 Validates parameters of MQTT_Subscribe or MQTT_Unsubscribe.
 
static MQTTStatus_t receiveConnack (MQTTContext_t *pContext, uint32_t timeoutMs, bool cleanSession, MQTTPacketInfo_t *pIncomingPacket, bool *pSessionPresent)
 Receives a CONNACK MQTT packet.
 
static MQTTStatus_t handleUncleanSessionResumption (MQTTContext_t *pContext)
 Resends pending acks for a re-established MQTT session.
 
static MQTTStatus_t handleCleanSession (MQTTContext_t *pContext)
 Clears existing state records for a clean session.
 
static MQTTStatus_t sendPublishWithoutCopy (MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint8_t *pMqttHeader, size_t headerSize, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
 Send the publish packet without copying the topic string and payload in the buffer.
 
static MQTTStatus_t validatePublishParams (const MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId)
 Function to validate MQTT_Publish parameters.
 
static bool matchEndWildcardsSpecialCases (const char *pTopicFilter, uint16_t topicFilterLength, uint16_t filterIndex)
 Performs matching for special cases when a topic filter ends with a wildcard character.
 
static bool matchWildcards (const char *pTopicName, uint16_t topicNameLength, const char *pTopicFilter, uint16_t topicFilterLength, uint16_t *pNameIndex, uint16_t *pFilterIndex, bool *pMatch)
 Attempt to match topic name with a topic filter starting with a wildcard.
 
static bool matchTopicFilter (const char *pTopicName, uint16_t topicNameLength, const char *pTopicFilter, uint16_t topicFilterLength)
 Match a topic name and topic filter allowing the use of wildcards.
 
static MQTTStatus_t validateTopicFilter (const MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t iterator, MQTTSubscriptionType_t subscriptionType)
 Validate the topic filter in a subscription.
 
static bool checkWildcardSubscriptions (uint8_t isWildcardAvailable, const MQTTSubscribeInfo_t *pSubscriptionList, size_t iterator)
 Check if wildcard subscriptions are allowed and valid.
 
static MQTTStatus_t validateSharedSubscriptions (const MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, const size_t iterator)
 Validate Shared Subscriptions.
 
static void addSubscriptionOptions (const MQTTSubscribeInfo_t subscriptionInfo, uint8_t *pSubscriptionOptionsArray, size_t currentOptionIndex)
 Add subscription options to the options array.
 
static MQTTStatus_t handleSubUnsubAck (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket)
 Handle Incoming Subscribe ACK.
 
static MQTTStatus_t sendPublishAcksWithoutProperty (MQTTContext_t *pContext, uint16_t packetId, MQTTPublishState_t publishState)
 Send acks for received QoS 1/2 publishes. This function is used to send Publish Acks without any properties or reason codes.
 
static MQTTStatus_t sendPublishAcksWithProperty (MQTTContext_t *pContext, uint16_t packetId, MQTTPublishState_t publishState, MQTTSuccessFailReasonCode_t reasonCode)
 Send acks for received QoS 1/2 publishes with properties.
 
static MQTTStatus_t validatePublishAckReasonCode (MQTTSuccessFailReasonCode_t reasonCode, uint8_t packetType)
 Validate Publish Ack Reason Code.
 
static MQTTStatus_t sendDisconnectWithoutCopy (MQTTContext_t *pContext, const MQTTSuccessFailReasonCode_t *pReasonCode, uint32_t remainingLength, const MQTTPropBuilder_t *pPropertyBuilder)
 Send the disconnect packet without copying the reason code and properties in the buffer.
 
static MQTTStatus_t handleIncomingDisconnect (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket)
 Handle Incoming Disconnect.
 
static MQTTStatus_t buildAndSendAckWithProps (MQTTContext_t *pContext, uint8_t packetTypeByte, uint16_t packetId, MQTTSuccessFailReasonCode_t reasonCode, uint32_t remainingLength, size_t ackPropertyLength)
 Build the IO vector for a publish ACK with properties and send it. Returns MQTTSuccess, MQTTSendFailed, MQTTBadParameter, or MQTTPublishStoreFailed.
 
static MQTTStatus_t addStringToVectorChecked (uint8_t *pLenBuf, const char *pStr, uint16_t strLen, IoVecState_t *pVecState)
 Add an encoded string to the IO vector if it fits within maxPacketSize. Returns MQTTBadParameter if the addition would overflow.
 
static MQTTStatus_t appendWillVectors (const MQTTPublishInfo_t *pWillInfo, const MQTTPropBuilder_t *pWillPropertyBuilder, IoVecState_t *pVecState, uint8_t *pWillPropertyLength, uint8_t *pSerializedTopicLength, uint8_t *pSerializedPayloadLength)
 Append will properties, topic, and payload vectors to the IO vector.
 
MQTTStatus_t MQTT_Init (MQTTContext_t *pContext, const TransportInterface_t *pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback, const MQTTFixedBuffer_t *pNetworkBuffer)
 Initialize an MQTT context.
 
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)
 Initialize an MQTT context for QoS > 0.
 
MQTTStatus_t MQTT_InitRetransmits (MQTTContext_t *pContext, MQTTStorePacketForRetransmit storeFunction, MQTTRetrievePacketForRetransmit retrieveFunction, MQTTClearPacketForRetransmit clearFunction)
 Initialize an MQTT context for publish retransmits for QoS > 0.
 
MQTTStatus_t MQTT_CancelCallback (const MQTTContext_t *pContext, uint16_t packetId)
 Cancels an outgoing publish callback (only for QoS > QoS0) by removing it from the pending ACK list.
 
MQTTStatus_t MQTT_CheckConnectStatus (const MQTTContext_t *pContext)
 Checks the MQTT connection status with the broker.
 
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)
 Establish an MQTT session.
 
MQTTStatus_t MQTT_Subscribe (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
 Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.
 
MQTTStatus_t MQTT_Publish (MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
 Publishes a message to the given topic name.
 
MQTTStatus_t MQTT_Ping (MQTTContext_t *pContext)
 Sends an MQTT PINGREQ to broker.
 
MQTTStatus_t MQTT_Unsubscribe (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
 Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.
 
MQTTStatus_t MQTT_Disconnect (MQTTContext_t *pContext, const MQTTPropBuilder_t *pPropertyBuilder, const MQTTSuccessFailReasonCode_t *pReasonCode)
 Sends MQTT DISCONNECT for a given reason code.
 
MQTTStatus_t MQTT_ProcessLoop (MQTTContext_t *pContext)
 Loop to receive packets from the transport interface. Handles keep alive.
 
MQTTStatus_t MQTT_ReceiveLoop (MQTTContext_t *pContext)
 Loop to receive packets from the transport interface. Does not handle keep alive.
 
uint16_t MQTT_GetPacketId (MQTTContext_t *pContext)
 Get a packet ID that is valid according to the MQTT 5.0 spec.
 
MQTTStatus_t MQTT_MatchTopic (const char *pTopicName, const size_t topicNameLength, const char *pTopicFilter, const size_t topicFilterLength, bool *pIsMatch)
 A utility function that determines whether the passed topic filter and topic name match according to the MQTT 5.0 protocol specification.
 
MQTTStatus_t MQTT_GetSubAckStatusCodes (const MQTTPacketInfo_t *pSubackPacket, uint8_t **pPayloadStart, size_t *pPayloadSize)
 Parses the payload of an MQTT SUBACK packet that contains status codes corresponding to topic filter subscription requests from the original subscribe packet.
 
const char * MQTT_Status_strerror (MQTTStatus_t status)
 Error code to string conversion for MQTT statuses.
 
MQTTStatus_t MQTT_GetBytesInMQTTVec (const MQTTVec_t *pVec, size_t *pOutput)
 Get the bytes in a MQTTVec pointer which can store the whole array as a an MQTT packet when calling MQTT_SerializeMQTTVec( void * pAllocatedMem, MQTTVec_t *pVec ) function.
 
void MQTT_SerializeMQTTVec (uint8_t *pAllocatedMem, const MQTTVec_t *pVec)
 Serialize the bytes in an array of MQTTVec in the provided pAllocatedMem.
 
const char * MQTT_GetPacketTypeString (uint8_t packetType)
 Get a human-readable string representation of an MQTT packet type.
 

Detailed Description

Implements the user-facing functions in core_mqtt.h.

Macro Definition Documentation

◆ CORE_MQTT_SUBSCRIBE_PER_TOPIC_VECTOR_LENGTH

#define CORE_MQTT_SUBSCRIBE_PER_TOPIC_VECTOR_LENGTH   ( 3U )

Number of vectors required to encode one topic filter in a subscribe request. Three vectors are required as there are three fields in the subscribe request namely:

  1. Topic filter length; 2. Topic filter; and 3. Subscription options in this order.

◆ CORE_MQTT_UNSUBSCRIBE_PER_TOPIC_VECTOR_LENGTH

#define CORE_MQTT_UNSUBSCRIBE_PER_TOPIC_VECTOR_LENGTH   ( 2U )

Number of vectors required to encode one topic filter in an unsubscribe request. Two vectors are required as there are two fields in the unsubscribe request namely:

  1. Topic filter length; and 2. Topic filter in this order.

Function Documentation

◆ sendBuffer()

static int32_t sendBuffer ( MQTTContext_t pContext,
const uint8_t *  pBufferToSend,
size_t  bytesToSend 
)
static

Sends provided buffer to network using transport send.

param[in] pContext Initialized MQTT context.

param[in] pBufferToSend Buffer to be sent to network.

param[in] bytesToSend Number of bytes to be sent.

Note
This operation may call the transport send function repeatedly to send bytes over the network until either:
  1. The requested number of bytes bytesToSend have been sent. OR
  2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this function. OR
  3. There is an error in sending data over the network.
Returns
Total number of bytes sent, or negative value on network error.

◆ sendConnectWithoutCopy()

static MQTTStatus_t sendConnectWithoutCopy ( MQTTContext_t pContext,
const MQTTConnectInfo_t pConnectInfo,
const MQTTPublishInfo_t pWillInfo,
uint32_t  remainingLength,
const MQTTPropBuilder_t pPropertyBuilder,
const MQTTPropBuilder_t pWillPropertyBuilder 
)
static

Sends MQTT connect without copying the users data into any buffer.

Parameters
[in]pContextInitialized MQTT context.
[in]pConnectInfoMQTT CONNECT packet information.
[in]pWillInfoLast Will and Testament. Pass NULL if Last Will and Testament is not used.
[in]remainingLengththe length of the connect packet.
[in]pPropertyBuilderProperty builder containing CONNECT properties.
[in]pWillPropertyBuilderProperty builder containing Last Will And Testament properties.
Note
This operation may call the transport send function repeatedly to send bytes over the network until either:
  1. The requested number of bytes remainingLength have been sent. OR
  2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this function. OR
  3. There is an error in sending data over the network.
Returns
MQTTSendFailed, MQTTBadParameter, MQTTBadResponse or MQTTSuccess.

Maximum number of bytes to send the Property Length. Property Length 0 + 4 = 4

◆ sendMessageVector()

static int32_t sendMessageVector ( MQTTContext_t pContext,
TransportOutVector_t pIoVec,
size_t  ioVecCount 
)
static

Sends the vector array passed through the parameters over the network.

Note
The preference is given to 'writev' function if it is present in the transport interface. Otherwise, a send call is made repeatedly to achieve the result.
Parameters
[in]pContextInitialized MQTT context.
[in]pIoVecThe vector array to be sent.
[in]ioVecCountThe number of elements in the array.
Note
This operation may call the transport send or writev functions repeatedly to send bytes over the network until either:
  1. The requested number of bytes have been sent. OR
  2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this function. OR
  3. There is an error in sending data over the network.
Returns
The total number of bytes sent or the error code as received from the transport interface.

◆ addEncodedStringToVector()

static size_t addEncodedStringToVector ( uint8_t  serializedLength[CORE_MQTT_SERIALIZED_LENGTH_FIELD_BYTES],
const char *const  string,
uint16_t  length,
TransportOutVector_t iterator,
uint32_t *  updatedLength 
)
static

Add a string and its length after serializing it in a manner outlined by the MQTT specification.

Parameters
[in]serializedLengthArray of two bytes to which the vector will point. The array must remain in scope until the message has been sent.
[in]stringThe string to be serialized.
[in]lengthThe length of the string to be serialized.
[in]iteratorThe iterator pointing to the first element in the transport interface IO array.
[out]updatedLengthThis parameter will be added to with the number of bytes added to the vector.
Returns
The number of vectors added.

◆ sendSubscribeWithoutCopy()

static MQTTStatus_t sendSubscribeWithoutCopy ( MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  subscriptionCount,
uint16_t  packetId,
uint32_t  remainingLength,
const MQTTPropBuilder_t pPropertyBuilder 
)
static

Send Subscribe without copying the users data into any buffer.

Parameters
[in]pContextInitialized MQTT context.
[in]pSubscriptionListList of MQTT subscription info.
[in]subscriptionCountNumber of elements in pSubscriptionList.
[in]packetIdPacket identifier.
[in]remainingLengthRemaining length of the packet.
[in]pPropertyBuilderMQTT property builder.
Note
This operation may call the transport send function repeatedly to send bytes over the network until either:
  1. The requested number of bytes remainingLength have been sent. OR
  2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this function. OR
  3. There is an error in sending data over the network.
Returns
MQTTSendFailed or MQTTSuccess.

Fixed Size Properties

Maximum number of bytes by the fixed header of a SUBSCRIBE packet. MQTT Control Byte 0 + 1 = 1 Remaining Length + 4 = 5 Packet Id + 2 = 7

Maximum number of bytes to send the Property Length. Property Length 0 + 4 = 4

Sending Property Buffer

◆ sendUnsubscribeWithoutCopy()

static MQTTStatus_t sendUnsubscribeWithoutCopy ( MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  subscriptionCount,
uint16_t  packetId,
uint32_t  remainingLength,
const MQTTPropBuilder_t pPropertyBuilder 
)
static

Send Unsubscribe without copying the users data into any buffer.

Parameters
[in]pContextInitialized MQTT context.
[in]pSubscriptionListList of MQTT subscription info.
[in]subscriptionCountNumber of elements in pSubscriptionList.
[in]packetIdPacket identifier.
[in]remainingLengthRemaining length of the packet.
[in]pPropertyBuilderMQTT property builder.
Note
This operation may call the transport send function repeatedly to send bytes over the network until either:
  1. The requested number of bytes remainingLength have been sent. OR
  2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this function. OR
  3. There is an error in sending data over the network.
Returns
MQTTSendFailed or MQTTSuccess.

Fixed Size Properties

Maximum number of bytes by the fixed header of a SUBSCRIBE packet. MQTT Control Byte 0 + 1 = 1 Remaining Length + 4 = 5 Packet Id + 2 = 7

Maximum number of bytes to send the Property Length. Property Length 0 + 4 = 4

Sending Property Buffer

◆ calculateElapsedTime()

static uint32_t calculateElapsedTime ( uint32_t  later,
uint32_t  start 
)
static

Calculate the interval between two millisecond timestamps, including when the later value has overflowed.

Note
In C, the operands are promoted to signed integers in subtraction. Using this function avoids the need to cast the result of subtractions back to uint32_t.
Parameters
[in]laterThe later time stamp, in milliseconds.
[in]startThe earlier time stamp, in milliseconds.
Returns
later - start.

◆ getAckFromPacketType()

static MQTTPubAckType_t getAckFromPacketType ( uint8_t  packetType)
static

Convert a byte indicating a publish ack type to an MQTTPubAckType_t.

Parameters
[in]packetTypeFirst byte of fixed header.
Returns
Type of ack.

◆ recvExact()

static int32_t recvExact ( MQTTContext_t pContext,
size_t  bytesToRecv 
)
static

Receive bytes into the network buffer.

Parameters
[in]pContextInitialized MQTT Context.
[in]bytesToRecvNumber of bytes to receive.
Note
This operation calls the transport receive function repeatedly to read bytes from the network until either:
  1. The requested number of bytes bytesToRecv are read. OR
  2. No data is received from the network for MQTT_RECV_POLLING_TIMEOUT_MS duration.
                OR
    
  3. There is an error in reading from the network.
Returns
Number of bytes received, or negative number on network error.

◆ receiveConnackPacket()

static MQTTStatus_t receiveConnackPacket ( MQTTContext_t pContext,
MQTTPacketInfo_t  incomingPacket 
)
static

Receive a CONNACK packet from the transport interface.

Parameters
[in]pContextMQTT Connection context.
[in]incomingPacketpacket struct with remaining length.
Returns
MQTTSuccess or MQTTRecvFailed.

◆ getAckTypeToSend()

static uint8_t getAckTypeToSend ( MQTTPublishState_t  state)
static

Get the correct ack type to send.

Parameters
[in]stateCurrent state of publish.
Returns
Packet Type byte of PUBACK, PUBREC, PUBREL, or PUBCOMP if one of those should be sent, else 0.

◆ sendPublishAcks()

static MQTTStatus_t sendPublishAcks ( MQTTContext_t pContext,
uint16_t  packetId,
MQTTPublishState_t  publishState 
)
static

Send acks for received QoS 1/2 publishes.

Parameters
[in]pContextMQTT Connection context.
[in]packetIdpacket ID of original PUBLISH.
[in]publishStateCurrent publish state in record.
Returns
MQTTSuccess, MQTTIllegalState or MQTTSendFailed.

◆ handleKeepAlive()

static MQTTStatus_t handleKeepAlive ( MQTTContext_t pContext)
static

Send a keep alive PINGREQ if the keep alive interval has elapsed.

Parameters
[in]pContextInitialized MQTT Context.
Returns
MQTTKeepAliveTimeout if a PINGRESP is not received in time, MQTTSendFailed if the PINGREQ cannot be sent, or MQTTSuccess.

◆ handleIncomingPublish()

static MQTTStatus_t handleIncomingPublish ( MQTTContext_t pContext,
MQTTPacketInfo_t pIncomingPacket 
)
static

Handle received MQTT PUBLISH packet.

Parameters
[in]pContextMQTT Connection context.
[in]pIncomingPacketIncoming packet.
Returns
MQTTSuccess, MQTTIllegalState or deserialization error.

◆ handlePublishAcks()

static MQTTStatus_t handlePublishAcks ( MQTTContext_t pContext,
MQTTPacketInfo_t pIncomingPacket 
)
static

Handle received MQTT publish acks.

Parameters
[in]pContextMQTT Connection context.
[in]pIncomingPacketIncoming packet.
Returns
MQTTSuccess, MQTTIllegalState, or deserialization error.

◆ handleIncomingAck()

static MQTTStatus_t handleIncomingAck ( MQTTContext_t pContext,
MQTTPacketInfo_t pIncomingPacket,
bool  manageKeepAlive 
)
static

Handle received MQTT ack.

Parameters
[in]pContextMQTT Connection context.
[in]pIncomingPacketIncoming packet.
[in]manageKeepAliveFlag indicating if PINGRESPs should not be given to the application
Returns
MQTTSuccess, MQTTIllegalState, or deserialization error.

◆ receiveSingleIteration()

static MQTTStatus_t receiveSingleIteration ( MQTTContext_t pContext,
bool  manageKeepAlive 
)
static

Run a single iteration of the receive loop.

Parameters
[in]pContextMQTT Connection context.
[in]manageKeepAliveFlag indicating if keep alive should be handled.
Returns
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_MS milliseconds; MQTTIllegalState if an incoming QoS 1/2 publish or ack causes an invalid transition for the internal state machine; MQTTSuccess on success.

◆ validateSubscribeUnsubscribeParams()

static MQTTStatus_t validateSubscribeUnsubscribeParams ( const MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  subscriptionCount,
uint16_t  packetId,
MQTTSubscriptionType_t  subscriptionType 
)
static

Validates parameters of MQTT_Subscribe or MQTT_Unsubscribe.

Parameters
[in]pContextInitialized MQTT context.
[in]pSubscriptionListList of MQTT subscription info.
[in]subscriptionCountThe number of elements in pSubscriptionList.
[in]packetIdPacket identifier.
[in]subscriptionTypeEither MQTT_TYPE_SUBSCRIBE or MQTT_TYPE_UNSUBSCRIBE.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.

◆ receiveConnack()

static MQTTStatus_t receiveConnack ( MQTTContext_t pContext,
uint32_t  timeoutMs,
bool  cleanSession,
MQTTPacketInfo_t pIncomingPacket,
bool *  pSessionPresent 
)
static

Receives a CONNACK MQTT packet.

Parameters
[in]pContextInitialized MQTT context.
[in]timeoutMsTimeout for waiting for CONNACK packet.
[in]cleanSessionClean session flag set by application.
[out]pIncomingPacketList of MQTT subscription info.
[out]pSessionPresentWhether a previous session was present. Only relevant if not establishing a clean session.
Returns
MQTTBadResponse if a bad response is received; MQTTNoDataAvailable if no data available for transport recv;

MQTTRecvFailed if transport recv failed;

MQTTSuccess otherwise.

◆ handleUncleanSessionResumption()

static MQTTStatus_t handleUncleanSessionResumption ( MQTTContext_t pContext)
static

Resends pending acks for a re-established MQTT session.

Parameters
[in]pContextInitialized MQTT context.
Returns
MQTTSendFailed if transport send during resend failed; MQTTSuccess otherwise.

◆ handleCleanSession()

static MQTTStatus_t handleCleanSession ( MQTTContext_t pContext)
static

Clears existing state records for a clean session.

Parameters
[in]pContextInitialized MQTT context.
Returns
MQTTSuccess always otherwise.

◆ sendPublishWithoutCopy()

static MQTTStatus_t sendPublishWithoutCopy ( MQTTContext_t pContext,
const MQTTPublishInfo_t pPublishInfo,
uint8_t *  pMqttHeader,
size_t  headerSize,
uint16_t  packetId,
const MQTTPropBuilder_t pPropertyBuilder 
)
static

Send the publish packet without copying the topic string and payload in the buffer.

Parameters
[in]pContextInitialized MQTT context.
[in]pPublishInfoMQTT PUBLISH packet parameters.
[in]pMqttHeaderthe serialized MQTT header with the header byte; the encoded length of the packet; and the encoded length of the topic string.
[in]headerSizeSize of the serialized PUBLISH header.
[in]packetIdPacket Id of the publish packet.
[in]pPropertyBuilderMQTT Publish property builder.
Returns
MQTTSendFailed if transport send during resend failed; MQTTPublishStoreFailed if storing the outgoing publish failed in the case of QoS 1/2 MQTTSuccess otherwise.

Maximum number of bytes to send the Property Length. Property Length 0 + 4 = 4

◆ validatePublishParams()

static MQTTStatus_t validatePublishParams ( const MQTTContext_t pContext,
const MQTTPublishInfo_t pPublishInfo,
uint16_t  packetId 
)
static

Function to validate MQTT_Publish parameters.

Parameters
[in]pContextInitialized MQTT context.
[in]pPublishInfoMQTT PUBLISH packet parameters.
[in]packetIdPacket Id for the MQTT PUBLISH packet.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.

◆ matchEndWildcardsSpecialCases()

static bool matchEndWildcardsSpecialCases ( const char *  pTopicFilter,
uint16_t  topicFilterLength,
uint16_t  filterIndex 
)
static

Performs matching for special cases when a topic filter ends with a wildcard character.

When the topic name has been consumed but there are remaining characters to to match in topic filter, this function handles the following 2 cases:

  • When the topic filter ends with "/+" or "/#" characters, but the topic name only ends with '/'.
  • When the topic filter ends with "/#" characters, but the topic name ends at the parent level.
Note
This function ASSUMES that the topic name been consumed in linear matching with the topic filer, but the topic filter has remaining characters to be matched.
Parameters
[in]pTopicFilterThe topic filter containing the wildcard.
[in]topicFilterLengthLength of the topic filter being examined.
[in]filterIndexIndex of the topic filter being examined.
Returns
Returns whether the topic filter and the topic name match.

◆ matchWildcards()

static bool matchWildcards ( const char *  pTopicName,
uint16_t  topicNameLength,
const char *  pTopicFilter,
uint16_t  topicFilterLength,
uint16_t *  pNameIndex,
uint16_t *  pFilterIndex,
bool *  pMatch 
)
static

Attempt to match topic name with a topic filter starting with a wildcard.

If the topic filter starts with a '+' (single-level) wildcard, the function advances the pNameIndex by a level in the topic name. If the topic filter starts with a '#' (multi-level) wildcard, the function concludes that both the topic name and topic filter match.

Parameters
[in]pTopicNameThe topic name to match.
[in]topicNameLengthLength of the topic name.
[in]pTopicFilterThe topic filter to match.
[in]topicFilterLengthLength of the topic filter.
[in,out]pNameIndexCurrent index in the topic name being examined. It is advanced by one level for + wildcards.
[in,out]pFilterIndexCurrent index in the topic filter being examined. It is advanced to position of '/' level separator for '+' wildcard.
[out]pMatchWhether the topic filter and topic name match.
Returns
true if the caller of this function should exit; false if the caller should continue parsing the topics.

◆ matchTopicFilter()

static bool matchTopicFilter ( const char *  pTopicName,
uint16_t  topicNameLength,
const char *  pTopicFilter,
uint16_t  topicFilterLength 
)
static

Match a topic name and topic filter allowing the use of wildcards.

Parameters
[in]pTopicNameThe topic name to check.
[in]topicNameLengthLength of the topic name.
[in]pTopicFilterThe topic filter to check.
[in]topicFilterLengthLength of topic filter.
Returns
true if the topic name and topic filter match; false otherwise.

◆ validateTopicFilter()

static MQTTStatus_t validateTopicFilter ( const MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  iterator,
MQTTSubscriptionType_t  subscriptionType 
)
static

Validate the topic filter in a subscription.

Parameters
[in]pContextMQTT Connection context.
[in]pSubscriptionListList of MQTT subscription info.
[in]iteratorThe iterator pointing to a topic filter in pSubscriptionList.
[in]subscriptionTypeThe type of subscription, either MQTT_TYPE_SUBSCRIBE or MQTT_TYPE_UNSUBSCRIBE.
Returns
Returns one of the following:

◆ checkWildcardSubscriptions()

static bool checkWildcardSubscriptions ( uint8_t  isWildcardAvailable,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  iterator 
)
static

Check if wildcard subscriptions are allowed and valid.

Parameters
[in]isWildcardAvailableFlag indicating if wildcard subscriptions are supported.
[in]pSubscriptionListList of MQTT subscription info.
[in]iteratorThe iterator pointing to a topic filter in pSubscriptionList.
Returns
true if wildcard subscriptions are valid or not present; false if wildcards are used but not supported

◆ validateSharedSubscriptions()

static MQTTStatus_t validateSharedSubscriptions ( const MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
const size_t  iterator 
)
static

Validate Shared Subscriptions.

Parameters
[in]pContextMQTT Connection context.
[in]pSubscriptionListList of MQTT subscription info.
[in]iteratorThe iterator pointing to a topic filter in pSubscriptionList.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise

◆ addSubscriptionOptions()

static void addSubscriptionOptions ( const MQTTSubscribeInfo_t  subscriptionInfo,
uint8_t *  pSubscriptionOptionsArray,
size_t  currentOptionIndex 
)
static

Add subscription options to the options array.

Parameters
[in]subscriptionInfoMQTT subscription information.
[out]pSubscriptionOptionsArrayArray to store subscription options.
[in]currentOptionIndexCurrent index in the options array.
Note
This function does not return a status as it performs a direct array update.

◆ handleSubUnsubAck()

static MQTTStatus_t handleSubUnsubAck ( MQTTContext_t pContext,
MQTTPacketInfo_t pIncomingPacket 
)
static

Handle Incoming Subscribe ACK.

Parameters
[in]pContextMQTT Connection context.
[in]pIncomingPacketInformation of incoming packet
Returns
MQTTSuccess, MQTTServerRefused, MQTTBadResponse, MQTTBadParameter, MQTTEventCallbackFailed.

◆ sendPublishAcksWithoutProperty()

static MQTTStatus_t sendPublishAcksWithoutProperty ( MQTTContext_t pContext,
uint16_t  packetId,
MQTTPublishState_t  publishState 
)
static

Send acks for received QoS 1/2 publishes. This function is used to send Publish Acks without any properties or reason codes.

Parameters
[in]pContextMQTT Connection context.
[in]packetIdpacket ID of original PUBLISH.
[in]publishStateCurrent publish state in record.
Returns
MQTTSuccess, MQTTBadParameter, MQTTBadResponse, MQTTIllegalState, MQTTSendFailed, MQTTStatusNotConnected, MQTTStatusDisconnectPending or MQTTNoMemory.

◆ sendPublishAcksWithProperty()

static MQTTStatus_t sendPublishAcksWithProperty ( MQTTContext_t pContext,
uint16_t  packetId,
MQTTPublishState_t  publishState,
MQTTSuccessFailReasonCode_t  reasonCode 
)
static

Send acks for received QoS 1/2 publishes with properties.

Parameters
[in]pContextMQTT Connection context.
[in]packetIdpacket ID of original PUBLISH.
[in]publishStateCurrent publish state in record.
[in]reasonCodeReason code to be sent in the Publish Ack.
Returns
MQTTSuccess, MQTTBadParameter, MQTTIllegalState, MQTTSendFailed, MQTTStatusNotConnected, MQTTStatusDisconnectPending or MQTTBadResponse.

◆ validatePublishAckReasonCode()

static MQTTStatus_t validatePublishAckReasonCode ( MQTTSuccessFailReasonCode_t  reasonCode,
uint8_t  packetType 
)
static

Validate Publish Ack Reason Code.

Parameters
[in]reasonCodeReason Code to validate
[in]packetTypePacket Type byte of the publish ack packet. (PUBACK, PUBREC, PUBREL, PUBCOMP)
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise

◆ sendDisconnectWithoutCopy()

static MQTTStatus_t sendDisconnectWithoutCopy ( MQTTContext_t pContext,
const MQTTSuccessFailReasonCode_t pReasonCode,
uint32_t  remainingLength,
const MQTTPropBuilder_t pPropertyBuilder 
)
static

Send the disconnect packet without copying the reason code and properties in the buffer.

Parameters
[in]pContextMQTT Connection context.
[in]pReasonCodeOptional reason code to be sent in the Disconnect packet.
[in]remainingLengthRemaining length of the packet.
[in]pPropertyBuilderMQTT Disconnect property builder.
Returns
MQTTSendFailed if transport send during resend failed; MQTTSuccess otherwise.

Maximum number of bytes to send the Property Length. Property Length 0 + 4 = 4

◆ handleIncomingDisconnect()

static MQTTStatus_t handleIncomingDisconnect ( MQTTContext_t pContext,
MQTTPacketInfo_t pIncomingPacket 
)
static

Handle Incoming Disconnect.

Parameters
[in]pContextMQTT Connection context.
[in]pIncomingPacketInformation of incoming packet
Returns
MQTTSuccess, MQTTBadResponse, MQTTBadParameter, MQTTEventCallbackFailed,

◆ MQTT_Init()

MQTTStatus_t MQTT_Init ( MQTTContext_t pContext,
const TransportInterface_t pTransportInterface,
MQTTGetCurrentTimeFunc_t  getTimeFunction,
MQTTEventCallback_t  userCallback,
const MQTTFixedBuffer_t pNetworkBuffer 
)

Initialize an MQTT context.

This function must be called on an MQTTContext_t before any other function.

Note
The MQTTGetCurrentTimeFunc_t function for querying time must be defined. If there is no time implementation, it is the responsibility of the application to provide a dummy function to always return 0, provide 0 timeouts for all calls to MQTT_Connect, MQTT_ProcessLoop, and MQTT_ReceiveLoop and configure the MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_TIMEOUT_MS configurations to be 0. This will result in loop functions running for a single iteration, and MQTT_Connect relying on MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT to receive the CONNACK packet.
Parameters
[in]pContextThe context to initialize.
[in]pTransportInterfaceThe transport interface to use with the context.
[in]getTimeFunctionThe time utility function which can return the amount of time (in milliseconds) elapsed since a given epoch. This function will be used to ensure that timeouts in the API calls are met and keep-alive messages are sent on time.
[in]userCallbackThe user callback to use with the context to notify about incoming packet events.
[in]pNetworkBufferNetwork buffer provided for the context. This buffer will be used to receive incoming messages from the broker. This buffer must remain valid and in scope for the entire lifetime of the pContext and must not be used by another context and/or application.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTSuccess otherwise.

Example

// Function for obtaining a timestamp.
uint32_t getTimeStampMs();
// Callback function for receiving packets.
bool eventCallback(
MQTTContext_t * pContext,
MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo,
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;
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.
}
MQTTStatus_t MQTT_Init(MQTTContext_t *pContext, const TransportInterface_t *pTransportInterface, MQTTGetCurrentTimeFunc_t getTimeFunction, MQTTEventCallback_t userCallback, const MQTTFixedBuffer_t *pNetworkBuffer)
Initialize an MQTT context.
Definition: core_mqtt.c:4158
MQTTSuccessFailReasonCode_t
MQTT reason codes.
Definition: core_mqtt_serializer.h:583
@ MQTTSuccess
Definition: core_mqtt_serializer.h:240
struct NetworkContext NetworkContext_t
The NetworkContext is an incomplete type. An implementation of this interface must define struct Netw...
Definition: transport_interface.h:192
A struct representing an MQTT connection.
Definition: core_mqtt.h:305
Struct to hold deserialized packet information for an MQTTEventCallback_t callback.
Definition: core_mqtt.h:414
Buffer passed to MQTT library.
Definition: core_mqtt_serializer.h:284
size_t size
Size of buffer.
Definition: core_mqtt_serializer.h:286
uint8_t * pBuffer
Pointer to buffer.
Definition: core_mqtt_serializer.h:285
MQTT incoming packet parameters.
Definition: core_mqtt_serializer.h:443
Property builder for MQTT packets.
Definition: core_mqtt_serializer.h:470
The transport layer interface.
Definition: transport_interface.h:303
TransportSend_t send
Definition: transport_interface.h:305
TransportRecv_t recv
Definition: transport_interface.h:304
TransportWritev_t writev
Definition: transport_interface.h:306
NetworkContext_t * pNetworkContext
Definition: transport_interface.h:307

◆ MQTT_InitStatefulQoS()

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 
)

Initialize an MQTT context for QoS > 0.

This function must be called on an MQTTContext_t after MQTT_Init and before any other function.

Parameters
[in]pContextThe context to initialize.
[in]pOutgoingPublishRecordsPointer to memory which will be used to store state of outgoing publishes.
[in]outgoingPublishCountMaximum number of records which can be kept in the memory pointed to by pOutgoingPublishRecords.
[in]pIncomingPublishRecordsPointer to memory which will be used to store state of incoming publishes.
[in]incomingPublishCountMaximum number of records which can be kept in the memory pointed to by pIncomingPublishRecords.
[in]pAckPropsBufPointer to memory which will be used to store properties of outgoing publish-ACKS.
[in]ackPropsBufLengthLength of the buffer pointed to by pBuffer.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTSuccess otherwise.

Example

// Function for obtaining a timestamp.
uint32_t getTimeStampMs();
// Callback function for receiving packets.
bool eventCallback(
MQTTContext_t * pContext,
MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo,
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;
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.
}
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)
Initialize an MQTT context for QoS > 0.
Definition: core_mqtt.c:4221
An element of the state engine records for QoS 1 or Qos 2 publishes.
Definition: core_mqtt.h:294

◆ MQTT_InitRetransmits()

MQTTStatus_t MQTT_InitRetransmits ( MQTTContext_t pContext,
MQTTStorePacketForRetransmit  storeFunction,
MQTTRetrievePacketForRetransmit  retrieveFunction,
MQTTClearPacketForRetransmit  clearFunction 
)

Initialize an MQTT context for publish retransmits for QoS > 0.

This function must be called on an MQTTContext_t after MQTT_InitstatefulQoS and before any other function.

Parameters
[in]pContextThe context to initialize.
[in]storeFunctionUser defined API used to store outgoing publishes.
[in]retrieveFunctionUser defined API used to retreive a copied publish for resend operation.
[in]clearFunctionUser defined API used to clear a particular copied publish packet.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.

Example

// Function for obtaining a timestamp.
uint32_t getTimeStampMs();
// Callback function for receiving packets.
bool eventCallback(
MQTTContext_t * pContext,
MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo,
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,
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;
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.
}
MQTTStatus_t MQTT_InitRetransmits(MQTTContext_t *pContext, MQTTStorePacketForRetransmit storeFunction, MQTTRetrievePacketForRetransmit retrieveFunction, MQTTClearPacketForRetransmit clearFunction)
Initialize an MQTT context for publish retransmits for QoS > 0.
Definition: core_mqtt.c:4290
Transport vector structure for sending multiple messages.
Definition: transport_interface.h:253

◆ MQTT_CancelCallback()

MQTTStatus_t MQTT_CancelCallback ( const MQTTContext_t pContext,
uint16_t  packetId 
)

Cancels an outgoing publish callback (only for QoS > QoS0) by removing it from the pending ACK list.

Note
This cannot cancel the actual publish as that might have already been sent to the broker. This only removes the details of the given packet ID from the list of unACKed packet. That allows the caller to free any memory associated with the publish payload, topic string etc. Also, after this API call, the user provided callback will not be invoked when the ACK packet is received.
Parameters
[in]pContextInitialized MQTT context.
[in]packetIdpacket ID corresponding to the outstanding publish.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.

◆ MQTT_CheckConnectStatus()

MQTTStatus_t MQTT_CheckConnectStatus ( const MQTTContext_t pContext)

Checks the MQTT connection status with the broker.

Parameters
[in]pContextInitialized MQTT context.
Returns
MQTTBadParameter if invalid parameters are passed; MQTTStatusConnected if the MQTT connection is established with the broker. MQTTStatusNotConnected if the MQTT connection is broker. MQTTStatusDisconnectPending if Transport Interface has failed and MQTT connection needs to be closed.

Example

◆ MQTT_Connect()

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 
)

Establish an MQTT session.

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. If timeoutMs is greater than 0: MQTTContext_t.getTime is used to ensure that the function does not wait more than timeoutMs for CONNACK.
  2. If timeoutMs is 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_t was passed to MQTT_Init, then a timeout value of 0 MUST be passed to the API, and the MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_TIMEOUT_MS timeout configurations MUST be set to 0.
Parameters
[in]pContextInitialized MQTT context.
[in]pConnectInfoMQTT CONNECT packet information.
[in]pWillInfoLast Will and Testament. Pass NULL if Last Will and Testament is not used.
[in]timeoutMsMaximum 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.
[in]pPropertyBuilderProperties to be sent in the outgoing packet.
[in]pWillPropertyBuilderWill Properties to be sent in the outgoing packet.
[out]pSessionPresentThis value will be set to true if a previous session was present; otherwise it will be set to false. It is only relevant if not establishing a clean session.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTSendFailed if transport send failed;
MQTTRecvFailed if transport receive failed for CONNACK;
MQTTNoDataAvailable if no data available to receive in transport until the timeoutMs for CONNACK;
MQTTStatusConnected if the connection is already established
MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API
MQTTPublishRetrieveFailed if on an unclean session connection, the copied publishes are not retrieved successfully for retransmission
MQTTBadResponse if the received CONNACK packet is malformed
MQTTServerRefused if the server refuses the connection in the CONNACK.
MQTTEventCallbackFailed if the user defined callback fails.
MQTTSuccess otherwise.
Note
If no properties are provided (by setting pPropertyBuilder to NULL), coreMQTT will add a property to the connect packet to limit the maximum packet size that the broker can send to be equal to the application provided buffer to the MQTT_Init API. This prevents the case when the packet is bigger than the buffer at which point, coreMQTT cannot handle the packet, neither can it drop it as MQTT protocol doesn't allow it.
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 CONNACK 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.
  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.

Functions to add optional properties to the CONNECT packet are:

Connect Properties:

Will Properties:

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 );
// 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.
}
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)
Establish an MQTT session.
Definition: core_mqtt.c:4403
MQTTStatus_t MQTTPropAdd_PayloadFormat(MQTTPropBuilder_t *pPropertyBuilder, bool payloadFormat, const uint8_t *pOptionalMqttPacketType)
Adds Payload Format Indicator property to the MQTT property builder.
Definition: core_mqtt_prop_serializer.c:987
MQTTStatus_t MQTTPropertyBuilder_Init(MQTTPropBuilder_t *pPropertyBuilder, uint8_t *buffer, size_t length)
Initialize the property builder.
Definition: core_mqtt_serializer.c:5012
MQTTStatus_t MQTTPropAdd_MaxPacketSize(MQTTPropBuilder_t *pPropertyBuilder, uint32_t maxPacketSize, const uint8_t *pOptionalMqttPacketType)
Adds Maximum Packet Size property to the MQTT property builder.
Definition: core_mqtt_prop_serializer.c:842
#define MQTT_PACKET_TYPE_CONNECT
CONNECT (client-to-server).
Definition: core_mqtt_serializer.h:53
MQTTStatus_t
Return codes from MQTT functions.
Definition: core_mqtt_serializer.h:239
@ MQTTQoS0
Definition: core_mqtt_serializer.h:271
MQTT CONNECT packet parameters.
Definition: core_mqtt_serializer.h:294
const char * pClientIdentifier
MQTT client identifier. Must be unique per client.
Definition: core_mqtt_serializer.h:308
size_t clientIdentifierLength
Length of the client identifier.
Definition: core_mqtt_serializer.h:313
const char * pUserName
MQTT user name. Set to NULL if not used.
Definition: core_mqtt_serializer.h:318
bool cleanSession
Whether to establish a new, clean session or resume a previous session.
Definition: core_mqtt_serializer.h:298
size_t userNameLength
Length of MQTT user name. Set to 0 if not used.
Definition: core_mqtt_serializer.h:323
uint16_t keepAliveSeconds
MQTT keep alive period.
Definition: core_mqtt_serializer.h:303
const char * pPassword
MQTT password. Set to NULL if not used.
Definition: core_mqtt_serializer.h:328
size_t passwordLength
Length of MQTT password. Set to 0 if not used.
Definition: core_mqtt_serializer.h:333
MQTT PUBLISH packet parameters.
Definition: core_mqtt_serializer.h:395
MQTTQoS_t qos
Quality of Service for message.
Definition: core_mqtt_serializer.h:399
size_t payloadLength
Message payload length.
Definition: core_mqtt_serializer.h:429
size_t topicNameLength
Length of topic name.
Definition: core_mqtt_serializer.h:419
const char * pTopicName
Topic name on which the message is published.
Definition: core_mqtt_serializer.h:414
const void * pPayload
Message payload.
Definition: core_mqtt_serializer.h:424

Update the maximum number of concurrent incoming and outgoing PUBLISH records based on MQTT 5.0 Receive Maximum property :

  • For incoming publishes: Use the minimum between the client's configured receive maximum (In the MQTT_Init function) and the receive maximum value sent in CONNECT properties
  • For outgoing publishes: Use the minimum between the client's configured maximum (In the MQTT_Init function) and the server's receive maximum value received in CONNACK properties

Initialize the client's keep-alive timer using the Server Keep Alive value received in the CONNACK. This value overrides the client's original keep-alive setting, as per MQTT v5 specification.

◆ MQTT_Subscribe()

MQTTStatus_t MQTT_Subscribe ( MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  subscriptionCount,
uint16_t  packetId,
const MQTTPropBuilder_t pPropertyBuilder 
)

Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.

Parameters
[in]pContextInitialized MQTT context.
[in]pSubscriptionListArray of MQTT subscription info.
[in]subscriptionCountThe number of elements in @ pSubscriptionList array.
[in]packetIdPacket ID generated by MQTT_GetPacketId.
[in]pPropertyBuilderProperties to be sent in the outgoing packet.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTBadResponse if there is an error in property parsing;
MQTTSendFailed if transport write failed;
MQTTStatusNotConnected if the connection is not established yet
MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API
MQTTSuccess otherwise.

Functions to add optional properties to the SUBSCRIBE packet are:

Example

// 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.
}
uint16_t MQTT_GetPacketId(MQTTContext_t *pContext)
Get a packet ID that is valid according to the MQTT 5.0 spec.
Definition: core_mqtt.c:5137
MQTTStatus_t MQTT_Subscribe(MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.
Definition: core_mqtt.c:4630
MQTTStatus_t MQTTPropAdd_SubscriptionId(MQTTPropBuilder_t *pPropertyBuilder, uint32_t subscriptionId, const uint8_t *pOptionalMqttPacketType)
Adds a Subscription Identifier property to the MQTT property builder.
Definition: core_mqtt_prop_serializer.c:613
#define MQTT_PACKET_TYPE_SUBSCRIBE
SUBSCRIBE (client-to-server).
Definition: core_mqtt_serializer.h:60
MQTT SUBSCRIBE packet parameters.
Definition: core_mqtt_serializer.h:351
size_t topicFilterLength
Length of subscription topic filter - unsigned long.
Definition: core_mqtt_serializer.h:365
MQTTQoS_t qos
Quality of Service for subscription. Include protocol error of qos > 2.
Definition: core_mqtt_serializer.h:355
const char * pTopicFilter
Topic filter to subscribe to.
Definition: core_mqtt_serializer.h:360

◆ MQTT_Publish()

MQTTStatus_t MQTT_Publish ( MQTTContext_t pContext,
const MQTTPublishInfo_t pPublishInfo,
uint16_t  packetId,
const MQTTPropBuilder_t pPropertyBuilder 
)

Publishes a message to the given topic name.

Parameters
[in]pContextInitialized MQTT context.
[in]pPublishInfoMQTT PUBLISH packet parameters.
[in]packetIdpacket ID generated by MQTT_GetPacketId.
[in]pPropertyBuilderProperties to be sent in the outgoing packet.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTBadResponse if there is an error in property parsing;
MQTTSendFailed if transport write failed;
MQTTStatusNotConnected if the connection is not established yet
MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API
MQTTPublishStoreFailed if the user provided callback to copy and store the outgoing publish packet fails
MQTTSuccess otherwise.

Functions to add optional properties to the PUBLISH packet are:

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!" );
// 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.
}
MQTTStatus_t MQTT_Publish(MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
Publishes a message to the given topic name.
Definition: core_mqtt.c:4702
#define MQTT_PACKET_TYPE_PUBLISH
PUBLISH (bidirectional).
Definition: core_mqtt_serializer.h:55
@ MQTTQoS1
Definition: core_mqtt_serializer.h:272

◆ MQTT_Ping()

MQTTStatus_t MQTT_Ping ( MQTTContext_t pContext)

Sends an MQTT PINGREQ to broker.

Parameters
[in]pContextInitialized and connected MQTT context.
Returns
MQTTNoMemory if pBuffer is too small to hold the MQTT packet; MQTTBadParameter if invalid parameters are passed; MQTTSendFailed if transport write failed; MQTTStatusNotConnected if the connection is not established yet MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API MQTTSuccess otherwise.

◆ MQTT_Unsubscribe()

MQTTStatus_t MQTT_Unsubscribe ( MQTTContext_t pContext,
const MQTTSubscribeInfo_t pSubscriptionList,
size_t  subscriptionCount,
uint16_t  packetId,
const MQTTPropBuilder_t pPropertyBuilder 
)

Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.

Parameters
[in]pContextInitialized MQTT context.
[in]pSubscriptionListList of MQTT subscription info.
[in]subscriptionCountThe number of elements in pSubscriptionList.
[in]packetIdpacket ID generated by MQTT_GetPacketId.
[in]pPropertyBuilderProperties to be sent in the outgoing packet.
Returns

Functions to add optional properties to the UNSUBSCRIBE packet are:

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 );
// 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.
}
MQTTStatus_t MQTT_Unsubscribe(MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId, const MQTTPropBuilder_t *pPropertyBuilder)
Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.
Definition: core_mqtt.c:4937
MQTTStatus_t MQTTPropAdd_UserProp(MQTTPropBuilder_t *pPropertyBuilder, const MQTTUserProperty_t *userProperty, const uint8_t *pOptionalMqttPacketType)
Adds User Property to the MQTT property builder.
Definition: core_mqtt_prop_serializer.c:692
#define MQTT_PACKET_TYPE_UNSUBSCRIBE
UNSUBSCRIBE (client-to-server).
Definition: core_mqtt_serializer.h:62
Struct to hold user property.
Definition: core_mqtt_serializer.h:702
const char * pValue
value.
Definition: core_mqtt_serializer.h:714
size_t keyLength
Length of the key.
Definition: core_mqtt_serializer.h:710
const char * pKey
key.
Definition: core_mqtt_serializer.h:706
size_t valueLength
Length of the value.
Definition: core_mqtt_serializer.h:718

◆ MQTT_Disconnect()

MQTTStatus_t MQTT_Disconnect ( MQTTContext_t pContext,
const MQTTPropBuilder_t pPropertyBuilder,
const MQTTSuccessFailReasonCode_t pReasonCode 
)

Sends MQTT DISCONNECT for a given reason code.

Parameters
[in]pContextInitialized and connected MQTT context.
[in]pPropertyBuilderProperties to be sent in the outgoing packet.
[in]pReasonCodeOptional reason code to be sent in the DISCONNECT packet. If NULL, then no reason code is sent.
Returns
MQTTBadParameter if invalid parameters are passed;
MQTTBadResponse if invalid properties are parsed;
MQTTSendFailed if transport send failed;
MQTTStatusNotConnected if the connection is not established yet and a PING or an ACK is being sent.
MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API
MQTTSuccess otherwise.

Functions to add optional properties to the DISCONNECT packet are:

Example

// 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 });
status = MQTT_Disconnect( pContext, &propertyBuilder, &reason );
if( status == MQTTSuccess )
{
// The DISCONNECT packet was sent successfully. The connection is now closed.
}
MQTTStatus_t MQTT_Disconnect(MQTTContext_t *pContext, const MQTTPropBuilder_t *pPropertyBuilder, const MQTTSuccessFailReasonCode_t *pReasonCode)
Sends MQTT DISCONNECT for a given reason code.
Definition: core_mqtt.c:5004
MQTTStatus_t MQTTPropAdd_ReasonString(MQTTPropBuilder_t *pPropertyBuilder, const char *pReasonString, size_t reasonStringLength, const uint8_t *pOptionalMqttPacketType)
Adds Reason String property to the MQTT property builder.
Definition: core_mqtt_prop_serializer.c:1152
#define MQTT_PACKET_TYPE_DISCONNECT
DISCONNECT (client-to-server).
Definition: core_mqtt_serializer.h:66
@ MQTT_REASON_DISCONNECT_NORMAL_DISCONNECTION
Definition: core_mqtt_serializer.h:662

◆ MQTT_ProcessLoop()

MQTTStatus_t MQTT_ProcessLoop ( MQTTContext_t pContext)

Loop to receive packets from the transport interface. Handles keep alive.

Note
If a dummy timer function, MQTTGetCurrentTimeFunc_t, is passed to the library, then the keep-alive mechanism is not supported by the MQTT_ProcessLoop API. In that case, the MQTT_ReceiveLoop API function should be used instead.
Parameters
[in]pContextInitialized and connected MQTT context.
Note
Calling this function blocks the calling context for a time period that depends on the passed the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_TIMEOUT_MS, and the underlying transport interface implementation timeouts, unless an error occurs. The blocking period also depends on the execution time of the MQTTEventCallback_t callback supplied to the library. It is recommended that the supplied MQTTEventCallback_t callback does not contain blocking operations to prevent potential non-deterministic blocking period of the MQTT_ProcessLoop API 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_MS milliseconds; MQTTIllegalState if an incoming QoS 1/2 publish or ack causes an invalid transition for the internal state machine; MQTTNeedMoreBytes if MQTT_ProcessLoop has received incomplete data; it should be called again (probably after a delay); MQTTStatusNotConnected if the connection is not established yet and a PING or an ACK is being sent. MQTTStatusDisconnectPending if the user is expected to call MQTT_Disconnect before calling any other API MQTTSuccess on success.

Example

// Variables used in this example.
MQTTStatus_t status;
// This context is assumed to be initialized and connected.
MQTTContext_t * pContext;
while( true )
{
status = MQTT_ProcessLoop( pContext );
if( status != MQTTSuccess && status != MQTTNeedMoreBytes )
{
// Determine the error. It's possible we might need to disconnect
// the underlying transport connection.
}
else
{
// Other application functions.
}
}
MQTTStatus_t MQTT_ProcessLoop(MQTTContext_t *pContext)
Loop to receive packets from the transport interface. Handles keep alive.
Definition: core_mqtt.c:5084
@ MQTTNeedMoreBytes
Definition: core_mqtt_serializer.h:251

◆ MQTT_ReceiveLoop()

MQTTStatus_t MQTT_ReceiveLoop ( MQTTContext_t pContext)

Loop to receive packets from the transport interface. Does not handle keep alive.

Note
If a dummy MQTTGetCurrentTimeFunc_t was passed to MQTT_Init, then the MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_TIMEOUT_MS timeout configurations MUST be set to 0.
Parameters
[in]pContextInitialized and connected MQTT context.
Note
Calling this function blocks the calling context for a time period that depends on the the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_TIMEOUT_MS, and the underlying transport interface implementation timeouts, unless an error occurs. The blocking period also depends on the execution time of the MQTTEventCallback_t callback supplied to the library. It is recommended that the supplied MQTTEventCallback_t callback does not contain blocking operations to prevent potential non-deterministic blocking period of the MQTT_ReceiveLoop API 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; MQTTIllegalState if an incoming QoS 1/2 publish or ack causes an invalid transition for the internal state machine; MQTTNeedMoreBytes if MQTT_ReceiveLoop has received incomplete data; it should be called again (probably after a delay); MQTTSuccess on success.

Example

// Variables used in this example.
MQTTStatus_t status;
uint32_t keepAliveMs = 60 * 1000;
// This context is assumed to be initialized and connected.
MQTTContext_t * pContext;
while( true )
{
status = MQTT_ReceiveLoop( pContext );
if( status != MQTTSuccess && status != MQTTNeedMoreBytes )
{
// 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
// to in order to comply with keep alive.
if( ( pContext->getTime() - pContext->lastPacketTxTime ) > keepAliveMs )
{
status = MQTT_Ping( pContext );
}
// Other application functions.
}
}
MQTTStatus_t MQTT_Ping(MQTTContext_t *pContext)
Sends an MQTT PINGREQ to broker.
Definition: core_mqtt.c:4848
MQTTStatus_t MQTT_ReceiveLoop(MQTTContext_t *pContext)
Loop to receive packets from the transport interface. Does not handle keep alive.
Definition: core_mqtt.c:5111
uint32_t lastPacketTxTime
Timestamp of the last packet sent by the library.
Definition: core_mqtt.h:364
MQTTGetCurrentTimeFunc_t getTime
Function used to get millisecond timestamps.
Definition: core_mqtt.h:354

◆ MQTT_GetPacketId()

uint16_t MQTT_GetPacketId ( MQTTContext_t pContext)

Get a packet ID that is valid according to the MQTT 5.0 spec.

Parameters
[in]pContextInitialized MQTT context.
Returns
A non-zero number.

◆ MQTT_MatchTopic()

MQTTStatus_t MQTT_MatchTopic ( const char *  pTopicName,
const size_t  topicNameLength,
const char *  pTopicFilter,
const size_t  topicFilterLength,
bool *  pIsMatch 
)

A utility function that determines whether the passed topic filter and topic name match according to the MQTT 5.0 protocol specification.

Parameters
[in]pTopicNameThe topic name to check.
[in]topicNameLengthLength of the topic name.
[in]pTopicFilterThe topic filter to check.
[in]topicFilterLengthLength of topic filter.
[out]pIsMatchIf the match is performed without any error, that is if the return value is MQTTSuccess, then and only then the value in this parameter is valid and updated. In such a case, if the topic filter and the topic name match, then this value is set to true; otherwise if there is no match then it is set to false.
Note
The API assumes that the passed topic name is valid to meet the requirements of the MQTT 5.0 specification. Invalid topic names (for example, containing wildcard characters) should not be passed to the function. Also, the API checks validity of topic filter for wildcard characters ONLY if the passed topic name and topic filter do not have an exact string match.
Returns
Returns one of the following:

Example

// Variables used in this example.
const char * pTopic = "topic/match/1";
const char * pFilter = "topic/#";
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.
}
MQTTStatus_t MQTT_MatchTopic(const char *pTopicName, const size_t topicNameLength, const char *pTopicFilter, const size_t topicFilterLength, bool *pIsMatch)
A utility function that determines whether the passed topic filter and topic name match according to ...
Definition: core_mqtt.c:5166

◆ MQTT_GetSubAckStatusCodes()

MQTTStatus_t MQTT_GetSubAckStatusCodes ( const MQTTPacketInfo_t pSubackPacket,
uint8_t **  pPayloadStart,
size_t *  pPayloadSize 
)

Parses the payload of an MQTT SUBACK packet that contains status codes corresponding to topic filter subscription requests from the original subscribe packet.

Each return code in the SUBACK packet corresponds to a topic filter in the SUBSCRIBE Packet being acknowledged. The status codes can be one of the following:

  • 0x00 - Success - Maximum QoS 0
  • 0x01 - Success - Maximum QoS 1
  • 0x02 - Success - Maximum QoS 2 These are the reason codes when the server refuses the request-
  • 0x80 - Topic Filter Refused
  • 0x83 - Implementation specific error.
  • 0x87 - Not authorized.
  • 0x8F - Invalid Topic Filter.
  • 0x91 - Packet identifier in use.
  • 0x97 - Quota exceeded.
  • 0x9E - Shared subscriptions not supported.
  • 0xA1 - Subscription identifiers not supported.
  • 0xA2 - Wildcard subscriptions not supported.

Refer to MQTTSubAckStatus_t for the status codes.

Parameters
[in]pSubackPacketThe SUBACK packet whose payload is to be parsed.
[out]pPayloadStartThis is populated with the starting address of the payload (or return codes for topic filters) in the SUBACK packet.
[out]pPayloadSizeThis 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:

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.
bool eventCallback(
MQTTContext_t * pContext,
MQTTPacketInfo_t * pPacketInfo,
MQTTDeserializedInfo_t * pDeserializedInfo
MQTTPropBuilder_t * pSendPropsBuffer,
MQTTPropBuilder_t * pGetPropsBuffer
)
{
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 ] )
{
"Requested QoS %u, but granted QoS %u for %s",
pSubscribes[ i ].qos, pCodes[ i ], pSubscribes[ i ].pTopicFilter
) );
}
}
}
}
// Handle other packet types.
}
MQTTStatus_t MQTT_GetSubAckStatusCodes(const MQTTPacketInfo_t *pSubackPacket, uint8_t **pPayloadStart, size_t *pPayloadSize)
Parses the payload of an MQTT SUBACK packet that contains status codes corresponding to topic filter ...
Definition: core_mqtt.c:5245
#define LogWarn(message)
Macro that is called in the MQTT library for logging "Warning" level messages.
Definition: core_mqtt_config_defaults.h:235
#define MQTT_PACKET_TYPE_SUBACK
SUBACK (server-to-client).
Definition: core_mqtt_serializer.h:61
@ MQTTSubAckFailure
Failure.
Definition: core_mqtt.h:286
uint8_t type
Type of incoming MQTT packet.
Definition: core_mqtt_serializer.h:447

◆ MQTT_Status_strerror()

const char * MQTT_Status_strerror ( MQTTStatus_t  status)

Error code to string conversion for MQTT statuses.

Parameters
[in]statusThe status to convert to a string.
Returns
The string representation of the status.

◆ MQTT_GetBytesInMQTTVec()

MQTTStatus_t MQTT_GetBytesInMQTTVec ( const MQTTVec_t *  pVec,
size_t *  pOutput 
)

Get the bytes in a MQTTVec pointer which can store the whole array as a an MQTT packet when calling MQTT_SerializeMQTTVec( void * pAllocatedMem, MQTTVec_t *pVec ) function.

Parameters
[in]pVecThe MQTTVec pointer given as input to the user defined MQTTStorePacketForRetransmit callback function. Must not be NULL.
[out]pOutputThe number of bytes in the vector. This value is invalid if the status is not MQTTSuccess.
Returns
MQTTSuccess when the calculation is successful. The provided MQTTVec array can then be used to set aside memory to be used with MQTT_SerializeMQTTVec( void * pAllocatedMem, MQTTVec_t *pVec ) function. MQTTBadParameter on failure.

◆ MQTT_SerializeMQTTVec()

void MQTT_SerializeMQTTVec ( uint8_t *  pAllocatedMem,
const MQTTVec_t *  pVec 
)

Serialize the bytes in an array of MQTTVec in the provided pAllocatedMem.

Parameters
[in]pAllocatedMemMemory in which to serialize the data in the MQTTVec array. It must be of size provided by MQTT_GetBytesInMQTTVec( const MQTTVec_t * pVec, size_t * pOutput ). Must not be NULL.
[in]pVecThe MQTTVec pointer given as input to the user defined MQTTStorePacketForRetransmit callback function. Must not be NULL.

◆ MQTT_GetPacketTypeString()

const char * MQTT_GetPacketTypeString ( uint8_t  packetType)

Get a human-readable string representation of an MQTT packet type.

This function converts an MQTT packet type byte into a corresponding string representation for debugging and logging purposes.

Parameters
[in]packetTypeThe MQTT packet type byte to convert.
Returns
A pointer to a constant string containing the packet type name. Returns "UNKNOWN" if the packet type is not recognized.
Note
The returned string is statically allocated and should not be freed.
For PUBLISH packets, the function masks the lower 4 bits (flags) and returns "PUBLISH" regardless of the QoS, DUP, or RETAIN flag values.

Example

uint8_t packetType = MQTT_PACKET_TYPE_PUBLISH;
const char * packetName = MQTT_GetPacketTypeString( packetType );
printf( "Received packet: %s\n", packetName ); // Prints "Received packet: PUBLISH"
const char * MQTT_GetPacketTypeString(uint8_t packetType)
Get a human-readable string representation of an MQTT packet type.
Definition: core_mqtt.c:5469