coreMQTT
v1.1.2
MQTT 3.1.1 Client Library
|
|
Implements the user-facing functions in core_mqtt.h.
More...
#include <string.h>
#include <assert.h>
#include "core_mqtt.h"
#include "core_mqtt_state.h"
|
static int32_t | sendPacket (MQTTContext_t *pContext, const uint8_t *pBufferToSend, size_t bytesToSend) |
| Sends provided buffer to network using transport send. More...
|
|
static uint32_t | calculateElapsedTime (uint32_t later, uint32_t start) |
| Calculate the interval between two millisecond timestamps, including when the later value has overflowed. More...
|
|
static MQTTPubAckType_t | getAckFromPacketType (uint8_t packetType) |
| Convert a byte indicating a publish ack type to an MQTTPubAckType_t. More...
|
|
static int32_t | recvExact (const MQTTContext_t *pContext, size_t bytesToRecv) |
| Receive bytes into the network buffer. More...
|
|
static MQTTStatus_t | discardPacket (const MQTTContext_t *pContext, size_t remainingLength, uint32_t timeoutMs) |
| Discard a packet from the transport interface. More...
|
|
static MQTTStatus_t | receivePacket (const MQTTContext_t *pContext, MQTTPacketInfo_t incomingPacket, uint32_t remainingTimeMs) |
| Receive a packet from the transport interface. More...
|
|
static uint8_t | getAckTypeToSend (MQTTPublishState_t state) |
| Get the correct ack type to send. More...
|
|
static MQTTStatus_t | sendPublishAcks (MQTTContext_t *pContext, uint16_t packetId, MQTTPublishState_t publishState) |
| Send acks for received QoS 1/2 publishes. More...
|
|
static MQTTStatus_t | handleKeepAlive (MQTTContext_t *pContext) |
| Send a keep alive PINGREQ if the keep alive interval has elapsed. More...
|
|
static MQTTStatus_t | handleIncomingPublish (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket) |
| Handle received MQTT PUBLISH packet. More...
|
|
static MQTTStatus_t | handlePublishAcks (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket) |
| Handle received MQTT publish acks. More...
|
|
static MQTTStatus_t | handleIncomingAck (MQTTContext_t *pContext, MQTTPacketInfo_t *pIncomingPacket, bool manageKeepAlive) |
| Handle received MQTT ack. More...
|
|
static MQTTStatus_t | receiveSingleIteration (MQTTContext_t *pContext, uint32_t remainingTimeMs, bool manageKeepAlive) |
| Run a single iteration of the receive loop. More...
|
|
static MQTTStatus_t | validateSubscribeUnsubscribeParams (const MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId) |
| Validates parameters of MQTT_Subscribe or MQTT_Unsubscribe. More...
|
|
static MQTTStatus_t | sendPublish (MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, size_t headerSize) |
| Send serialized publish packet using transport send. More...
|
|
static MQTTStatus_t | receiveConnack (const MQTTContext_t *pContext, uint32_t timeoutMs, bool cleanSession, MQTTPacketInfo_t *pIncomingPacket, bool *pSessionPresent) |
| Receives a CONNACK MQTT packet. More...
|
|
static MQTTStatus_t | handleSessionResumption (MQTTContext_t *pContext, bool sessionPresent) |
| Resends pending acks for a re-established MQTT session, or clears existing state records for a clean session. More...
|
|
static MQTTStatus_t | serializePublish (const MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId, size_t *const pHeaderSize) |
| Serializes a PUBLISH message. More...
|
|
static MQTTStatus_t | validatePublishParams (const MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId) |
| Function to validate MQTT_Publish parameters. More...
|
|
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. More...
|
|
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. More...
|
|
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. More...
|
|
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. More...
|
|
MQTTStatus_t | MQTT_Connect (MQTTContext_t *pContext, const MQTTConnectInfo_t *pConnectInfo, const MQTTPublishInfo_t *pWillInfo, uint32_t timeoutMs, bool *pSessionPresent) |
| Establish an MQTT session. More...
|
|
MQTTStatus_t | MQTT_Subscribe (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId) |
| Sends MQTT SUBSCRIBE for the given list of topic filters to the broker. More...
|
|
MQTTStatus_t | MQTT_Publish (MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId) |
| Publishes a message to the given topic name. More...
|
|
MQTTStatus_t | MQTT_Ping (MQTTContext_t *pContext) |
| Sends an MQTT PINGREQ to broker. More...
|
|
MQTTStatus_t | MQTT_Unsubscribe (MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId) |
| Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker. More...
|
|
MQTTStatus_t | MQTT_Disconnect (MQTTContext_t *pContext) |
| Disconnect an MQTT session. More...
|
|
MQTTStatus_t | MQTT_ProcessLoop (MQTTContext_t *pContext, uint32_t timeoutMs) |
| Loop to receive packets from the transport interface. Handles keep alive. More...
|
|
MQTTStatus_t | MQTT_ReceiveLoop (MQTTContext_t *pContext, uint32_t timeoutMs) |
| Loop to receive packets from the transport interface. Does not handle keep alive. More...
|
|
uint16_t | MQTT_GetPacketId (MQTTContext_t *pContext) |
| Get a packet ID that is valid according to the MQTT 3.1.1 spec. More...
|
|
MQTTStatus_t | MQTT_MatchTopic (const char *pTopicName, const uint16_t topicNameLength, const char *pTopicFilter, const uint16_t topicFilterLength, bool *pIsMatch) |
| A utility function that determines whether the passed topic filter and topic name match according to the MQTT 3.1.1 protocol specification. More...
|
|
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. More...
|
|
const char * | MQTT_Status_strerror (MQTTStatus_t status) |
| Error code to string conversion for MQTT statuses. More...
|
|
Implements the user-facing functions in core_mqtt.h.
◆ sendPacket()
static int32_t sendPacket |
( |
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:
- The requested number of bytes bytesToSend have been sent. OR
- No byte cannot be sent over the network for the MQTT_SEND_RETRY_TIMEOUT_MS duration. OR
- There is an error in sending data over the network.
- Returns
- Total number of bytes sent, or negative value on network error.
◆ 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] | later | The later time stamp, in milliseconds. |
[in] | start | The earlier time stamp, in milliseconds. |
- Returns
- later - start.
◆ getAckFromPacketType()
Convert a byte indicating a publish ack type to an MQTTPubAckType_t.
- Parameters
-
[in] | packetType | First byte of fixed header. |
- Returns
- Type of ack.
◆ recvExact()
static int32_t recvExact |
( |
const MQTTContext_t * |
pContext, |
|
|
size_t |
bytesToRecv |
|
) |
| |
|
static |
Receive bytes into the network buffer.
- Parameters
-
[in] | pContext | Initialized MQTT Context. |
[in] | bytesToRecv | Number of bytes to receive. |
- Note
- This operation calls the transport receive function repeatedly to read bytes from the network until either:
- The requested number of bytes bytesToRecv are read. OR
- No data is received from the network for MQTT_RECV_POLLING_TIMEOUT_MS duration.
OR
- There is an error in reading from the network.
- Returns
- Number of bytes received, or negative number on network error.
◆ discardPacket()
Discard a packet from the transport interface.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | remainingLength | Remaining length of the packet to dump. |
[in] | timeoutMs | Time remaining to discard the packet. |
- Returns
- MQTTRecvFailed or MQTTNoDataAvailable.
◆ receivePacket()
Receive a packet from the transport interface.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | incomingPacket | packet struct with remaining length. |
[in] | remainingTimeMs | Time remaining to receive the packet. |
- Returns
- MQTTSuccess or MQTTRecvFailed.
◆ getAckTypeToSend()
Get the correct ack type to send.
- Parameters
-
[in] | state | Current state of publish. |
- Returns
- Packet Type byte of PUBACK, PUBREC, PUBREL, or PUBCOMP if one of those should be sent, else 0.
◆ sendPublishAcks()
Send acks for received QoS 1/2 publishes.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | packetId | packet ID of original PUBLISH. |
[in] | publishState | Current publish state in record. |
- Returns
- MQTTSuccess, MQTTIllegalState or MQTTSendFailed.
◆ handleKeepAlive()
Send a keep alive PINGREQ if the keep alive interval has elapsed.
- Parameters
-
[in] | pContext | Initialized MQTT Context. |
- Returns
- MQTTKeepAliveTimeout if a PINGRESP is not received in time, MQTTSendFailed if the PINGREQ cannot be sent, or MQTTSuccess.
◆ handleIncomingPublish()
Handle received MQTT PUBLISH packet.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | pIncomingPacket | Incoming packet. |
- Returns
- MQTTSuccess, MQTTIllegalState or deserialization error.
◆ handlePublishAcks()
Handle received MQTT publish acks.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | pIncomingPacket | Incoming packet. |
- Returns
- MQTTSuccess, MQTTIllegalState, or deserialization error.
◆ handleIncomingAck()
Handle received MQTT ack.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | pIncomingPacket | Incoming packet. |
[in] | manageKeepAlive | Flag indicating if PINGRESPs should not be given to the application |
- Returns
- MQTTSuccess, MQTTIllegalState, or deserialization error.
◆ receiveSingleIteration()
Run a single iteration of the receive loop.
- Parameters
-
[in] | pContext | MQTT Connection context. |
[in] | remainingTimeMs | Remaining time for the loop in milliseconds. |
[in] | manageKeepAlive | Flag 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()
Validates parameters of MQTT_Subscribe or MQTT_Unsubscribe.
- Parameters
-
[in] | pContext | Initialized MQTT context. |
[in] | pSubscriptionList | List of MQTT subscription info. |
[in] | subscriptionCount | The number of elements in pSubscriptionList. |
[in] | packetId | Packet identifier. |
- Returns
- MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.
◆ sendPublish()
Send serialized publish packet using transport send.
param[in] pContext Initialized MQTT context.
param[in] pPublishInfo MQTT PUBLISH packet parameters.
param[in] headerSize Header size of the PUBLISH packet.
- Returns
- MQTTSendFailed if transport write failed; MQTTSuccess otherwise.
◆ receiveConnack()
Receives a CONNACK MQTT packet.
- Parameters
-
[in] | pContext | Initialized MQTT context. |
[in] | timeoutMs | Timeout for waiting for CONNACK packet. |
[in] | cleanSession | Clean session flag set by application. |
[out] | pIncomingPacket | List of MQTT subscription info. |
[out] | pSessionPresent | Whether 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.
◆ handleSessionResumption()
Resends pending acks for a re-established MQTT session, or clears existing state records for a clean session.
- Parameters
-
[in] | pContext | Initialized MQTT context. |
[in] | sessionPresent | Session present flag received from the MQTT broker. |
- Returns
- MQTTSendFailed if transport send during resend failed; MQTTSuccess otherwise.
◆ serializePublish()
Serializes a PUBLISH message.
param[in] pContext Initialized MQTT context.
param[in] pPublishInfo MQTT PUBLISH packet parameters.
param[in] packetId Packet Id of the publish packet.
param[out] pHeaderSize Size of the serialized PUBLISH header.
- Returns
- MQTTNoMemory if pBuffer is too small to hold the MQTT packet; MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.
◆ validatePublishParams()
Function to validate MQTT_Publish parameters.
param[in] pContext Initialized MQTT context.
param[in] pPublishInfo MQTT PUBLISH packet parameters.
param[in] packetId Packet 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] | pTopicFilter | The topic filter containing the wildcard. |
[in] | topicFilterLength | Length of the topic filter being examined. |
[in] | filterIndex | Index 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] | pTopicName | The topic name to match. |
[in] | topicNameLength | Length of the topic name. |
[in] | pTopicFilter | The topic filter to match. |
[in] | topicFilterLength | Length of the topic filter. |
[in,out] | pNameIndex | Current index in the topic name being examined. It is advanced by one level for + wildcards. |
[in,out] | pFilterIndex | Current index in the topic filter being examined. It is advanced to position of '/' level separator for '+' wildcard. |
[out] | pMatch | Whether 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] | pTopicName | The topic name to check. |
[in] | topicNameLength | Length of the topic name. |
[in] | pTopicFilter | The topic filter to check. |
[in] | topicFilterLength | Length of topic filter. |
- Returns
true
if the topic name and topic filter match; false
otherwise.
◆ MQTT_Init()
Initialize an MQTT context.
This function must be called on a 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_RETRY_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] | 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
- MQTTBadParameter if invalid parameters are passed; MQTTSuccess otherwise.
Example
uint32_t getTimeStampMs();
void eventCallback(
);
int32_t networkSend(
NetworkContext_t * pContext,
const void * pBuffer,
size_t bytes );
int32_t networkRecv(
NetworkContext_t * pContext,
void * pBuffer,
size_t bytes );
uint8_t buffer[ 1024 ];
memset( (
void * ) &mqttContext, 0x00,
sizeof(
MQTTContext_t ) );
transport.
send = networkSend;
transport.
recv = networkRecv;
status =
MQTT_Init( &mqttContext, &transport, getTimeStampMs, eventCallback, &fixedBuffer );
{
}
◆ MQTT_Connect()
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:
- If
timeoutMs
is greater than 0: MQTTContext_t.getTime is used to ensure that the function does not wait more than timeoutMs
for CONNACK.
- 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_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
- MQTTNoMemory if the MQTTContext_t.networkBuffer is too small to hold the MQTT packet; 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; MQTTSuccess otherwise.
- Note
- This API may spend more time than provided in the timeoutMS parameters in certain conditions as listed below:
- 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.
- 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
bool sessionPresent;
status =
MQTT_Connect( pContext, &connectInfo, &willInfo, 100, &sessionPresent );
{
assert( sessionPresent == false );
}
◆ MQTT_Subscribe()
Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.
- 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 by MQTT_GetPacketId. |
- Returns
- MQTTNoMemory if the MQTTContext_t.networkBuffer is too small to hold the MQTT packet; MQTTBadParameter if invalid parameters are passed; MQTTSendFailed if transport write failed; MQTTSuccess otherwise.
Example
uint16_t packetId;
const char * filters[ NUMBER_OF_SUBSCRIPTIONS ];
for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ )
{
}
status =
MQTT_Subscribe( pContext, &subscriptionList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId );
{
}
◆ MQTT_Publish()
Publishes a message to the given topic name.
- Parameters
-
[in] | pContext | Initialized MQTT context. |
[in] | pPublishInfo | MQTT PUBLISH packet parameters. |
[in] | packetId | packet ID generated by MQTT_GetPacketId. |
- Returns
- MQTTNoMemory if pBuffer is too small to hold the MQTT packet; MQTTBadParameter if invalid parameters are passed; MQTTSendFailed if transport write failed; MQTTSuccess otherwise.
Example
◆ MQTT_Ping()
Sends an MQTT PINGREQ to broker.
- Parameters
-
[in] | pContext | Initialized 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; MQTTSuccess otherwise.
◆ MQTT_Unsubscribe()
Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.
- 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 by MQTT_GetPacketId. |
- Returns
- MQTTNoMemory if the MQTTContext_t.networkBuffer is too small to hold the MQTT packet; MQTTBadParameter if invalid parameters are passed; MQTTSendFailed if transport write failed; MQTTSuccess otherwise.
Example
uint16_t packetId;
const char * filters[ NUMBER_OF_SUBSCRIPTIONS ];
for( int i = 0; i < NUMBER_OF_SUBSCRIPTIONS; i++ )
{
}
status =
MQTT_Unsubscribe( pContext, &unsubscribeList[ 0 ], NUMBER_OF_SUBSCRIPTIONS, packetId );
{
}
◆ MQTT_Disconnect()
◆ MQTT_ProcessLoop()
Loop to receive packets from the transport interface. Handles keep alive.
- 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 mechanism is not supported by the MQTT_ProcessLoop API. In that case, the MQTT_ReceiveLoop API 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 passed
timeoutMs
, the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_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 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; MQTTSuccess on success.
Example
uint32_t timeoutMs = 100;
while( true )
{
{
}
else
{
}
}
◆ MQTT_ReceiveLoop()
Loop to receive packets from the transport interface. Does not handle keep alive.
- Note
- Passing a timeout value of 0 will run the loop for a single iteration. If a dummy MQTTGetCurrentTimeFunc_t was passed to MQTT_Init, then the timeout value passed to the API MUST be 0, and the MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_SEND_RETRY_TIMEOUT_MS timeout 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 passed
timeoutMs
, the configuration macros, MQTT_RECV_POLLING_TIMEOUT_MS and MQTT_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 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; MQTTSuccess on success.
Example
uint32_t timeoutMs = 100;
uint32_t keepAliveMs = 60 * 1000;
while( true )
{
{
}
else
{
{
}
}
}
◆ MQTT_GetPacketId()
Get a packet ID that is valid according to the MQTT 3.1.1 spec.
- Parameters
-
[in] | pContext | Initialized MQTT context. |
- Returns
- A non-zero number.
◆ MQTT_MatchTopic()
MQTTStatus_t MQTT_MatchTopic |
( |
const char * |
pTopicName, |
|
|
const uint16_t |
topicNameLength, |
|
|
const char * |
pTopicFilter, |
|
|
const uint16_t |
topicFilterLength, |
|
|
bool * |
pIsMatch |
|
) |
| |
A utility function that determines whether the passed topic filter and topic name match according to the MQTT 3.1.1 protocol specification.
- Parameters
-
[in] | pTopicName | The topic name to check. |
[in] | topicNameLength | Length of the topic name. |
[in] | pTopicFilter | The topic filter to check. |
[in] | topicFilterLength | Length of topic filter. |
[out] | pIsMatch | This is filled with the whether there exists a match or not. |
- Note
- The API assumes that the passed topic name is valid to meet the requirements of the MQTT 3.1.1 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
const char * pTopic = "topic/match/1";
const char * pFilter = "topic/#";
bool match = false;
status =
MQTT_MatchTopic( pTopic, strlen( pTopic ), pFilter, strlen( pFilter ), &match );
if( match )
{
}
◆ 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.
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
- 0x80 - Failure Refer to MQTTSubAckStatus_t for 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:
Example
void eventCallback(
)
{
uint8_t * pCodes;
size_t numCodes;
{
assert( numCodes == NUMBER_OF_SUBSCRIPTIONS );
for( int i = 0; i < numCodes; i++ )
{
{
}
else
{
if( pSubscribes[ i ].qos != pCodes[ i ] )
{
"Requested QoS %u, but granted QoS %u for %s",
pSubscribes[ i ].qos, pCodes[ i ], pSubscribes[ i ].pTopicFilter
) );
}
}
}
}
}
◆ MQTT_Status_strerror()
Error code to string conversion for MQTT statuses.
- Parameters
-
[in] | status | The status to convert to a string. |
- Returns
- The string representation of the status.
MQTT SUBSCRIBE packet parameters.
Definition: core_mqtt_serializer.h:187
uint16_t topicNameLength
Length of topic name.
Definition: core_mqtt_serializer.h:233
MQTT CONNECT packet parameters.
Definition: core_mqtt_serializer.h:140
MQTTStatus_t MQTT_Subscribe(MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId)
Sends MQTT SUBSCRIBE for the given list of topic filters to the broker.
Definition: core_mqtt.c:1849
uint8_t * pBuffer
Pointer to buffer.
Definition: core_mqtt_serializer.h:131
MQTTStatus_t MQTT_ProcessLoop(MQTTContext_t *pContext, uint32_t timeoutMs)
Loop to receive packets from the transport interface. Handles keep alive.
Definition: core_mqtt.c:2160
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:2366
MQTT incoming packet parameters.
Definition: core_mqtt_serializer.h:251
MQTTStatus_t MQTT_Connect(MQTTContext_t *pContext, const MQTTConnectInfo_t *pConnectInfo, const MQTTPublishInfo_t *pWillInfo, uint32_t timeoutMs, bool *pSessionPresent)
Establish an MQTT session.
Definition: core_mqtt.c:1752
const char * pTopicFilter
Topic filter to subscribe to.
Definition: core_mqtt_serializer.h:196
struct NetworkContext NetworkContext_t
The NetworkContext is an incomplete type. An implementation of this interface must define struct Netw...
Definition: transport_interface.h:189
Buffer passed to MQTT library.
Definition: core_mqtt_serializer.h:130
MQTTStatus_t MQTT_Ping(MQTTContext_t *pContext)
Sends an MQTT PINGREQ to broker.
Definition: core_mqtt.c:1983
uint16_t MQTT_GetPacketId(MQTTContext_t *pContext)
Get a packet ID that is valid according to the MQTT 3.1.1 spec.
Definition: core_mqtt.c:2272
const void * pPayload
Message payload.
Definition: core_mqtt_serializer.h:238
size_t size
Size of buffer.
Definition: core_mqtt_serializer.h:132
uint32_t lastPacketTime
Timestamp of the last packet sent by the library.
Definition: core_mqtt.h:213
#define LogWarn(message)
Macro that is called in the MQTT library for logging "Warning" level messages.
Definition: core_mqtt_config_defaults.h:213
TransportSend_t send
Definition: transport_interface.h:254
const char * pClientIdentifier
MQTT client identifier. Must be unique per client.
Definition: core_mqtt_serializer.h:154
MQTTStatus_t
Return codes from MQTT functions.
Definition: core_mqtt_serializer.h:97
uint16_t keepAliveSeconds
MQTT keep alive period.
Definition: core_mqtt_serializer.h:149
const char * pPassword
MQTT password. Set to NULL if not used.
Definition: core_mqtt_serializer.h:174
MQTTStatus_t MQTT_MatchTopic(const char *pTopicName, const uint16_t topicNameLength, const char *pTopicFilter, const uint16_t topicFilterLength, bool *pIsMatch)
A utility function that determines whether the passed topic filter and topic name match according to ...
Definition: core_mqtt.c:2297
MQTTStatus_t MQTT_Unsubscribe(MQTTContext_t *pContext, const MQTTSubscribeInfo_t *pSubscriptionList, size_t subscriptionCount, uint16_t packetId)
Sends MQTT UNSUBSCRIBE for the given list of topic filters to the broker.
Definition: core_mqtt.c:2044
uint16_t passwordLength
Length of MQTT password. Set to 0 if not used.
Definition: core_mqtt_serializer.h:179
MQTTStatus_t MQTT_ReceiveLoop(MQTTContext_t *pContext, uint32_t timeoutMs)
Loop to receive packets from the transport interface. Does not handle keep alive.
Definition: core_mqtt.c:2217
const char * pTopicName
Topic name on which the message is published.
Definition: core_mqtt_serializer.h:228
MQTTGetCurrentTimeFunc_t getTime
Function used to get millisecond timestamps.
Definition: core_mqtt.h:203
MQTTStatus_t MQTT_Publish(MQTTContext_t *pContext, const MQTTPublishInfo_t *pPublishInfo, uint16_t packetId)
Publishes a message to the given topic name.
Definition: core_mqtt.c:1909
A struct representing an MQTT connection.
Definition: core_mqtt.h:169
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:1693
bool cleanSession
Whether to establish a new, clean session or resume a previous session.
Definition: core_mqtt_serializer.h:144
uint16_t topicFilterLength
Length of subscription topic filter.
Definition: core_mqtt_serializer.h:201
MQTTQoS_t qos
Quality of Service for subscription.
Definition: core_mqtt_serializer.h:191
uint16_t clientIdentifierLength
Length of the client identifier.
Definition: core_mqtt_serializer.h:159
@ MQTTQoS1
Definition: core_mqtt_serializer.h:118
uint8_t type
Type of incoming MQTT packet.
Definition: core_mqtt_serializer.h:255
MQTTQoS_t qos
Quality of Service for message.
Definition: core_mqtt_serializer.h:213
@ MQTTSuccess
Definition: core_mqtt_serializer.h:98
MQTT PUBLISH packet parameters.
Definition: core_mqtt_serializer.h:209
NetworkContext_t * pNetworkContext
Definition: transport_interface.h:255
#define MQTT_PACKET_TYPE_SUBACK
SUBACK (server-to-client).
Definition: core_mqtt_serializer.h:71
uint16_t userNameLength
Length of MQTT user name. Set to 0 if not used.
Definition: core_mqtt_serializer.h:169
size_t payloadLength
Message payload length.
Definition: core_mqtt_serializer.h:243
TransportRecv_t recv
Definition: transport_interface.h:253
@ MQTTSubAckFailure
Failure.
Definition: core_mqtt.h:150
@ MQTTQoS0
Definition: core_mqtt_serializer.h:117
Struct to hold deserialized packet information for an MQTTEventCallback_t callback.
Definition: core_mqtt.h:233
const char * pUserName
MQTT user name. Set to NULL if not used.
Definition: core_mqtt_serializer.h:164
The transport layer interface.
Definition: transport_interface.h:252