Skip to contentSkip to navigationSkip to topbar
On this page

MQTT Functions


(warning)

Microvisor Public Beta

Microvisor is in a pre-release phase and the information contained in this document is subject to change. Some features referenced below may not be fully available until Microvisor's General Availability (GA) release.

Microvisor system calls currently include the following functions to manage MQTT communications over the Internet.


MQTT

mqtt page anchor

This document assumes you are familiar with the MQTT specification(link takes you to an external page) and how the protocol operates.


Request-response correlation

request-response-correlation page anchor

A number of the following system calls consume or return 'correlation IDs'. These are 32-bit unsigned integer values you supply to help your code match responses to source requests. This is helpful because requests may be fulfilled in a non-deterministic order. Format values in a way that's appropriate to your application.


Return values and errors

return-values-and-errors page anchor

All of the functions described below return a 32-bit integer that is one of the values from the standard Microvisor enumeration MvStatus. All possible error values for a given system call are provided with each function's description.

Success is always signaled by a return value of zero (MV_STATUS_OKAY).

(warning)

Warning

The MQTT functions for managing requests and the responses they generate operate through Microvisor network channels. To learn how to establish network connections, and open channels through them, please see Microvisor network functions.


mvMqttGetNextReadableDataType()

mvmqttgetnextreadabledatatype page anchor

Determine what type of MQTT data a channel last received

Declaration

1
extern enum MvStatus mvMqttGetNextReadableDataType(MvChannelHandle handle,
2
enum MvMqttReadableDataType *type);

Parameters

ParameterDescription
handleThe handle of the channel over which to obtain the data type. This must be a channel of type MV_CHANNELTYPE_MQTT
typeA pointer to memory into which Microvisor will write the data type value

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTtype does not reference memory accessible to the application
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed

Description

Issued MQTT requests (listed below) will eventually cause a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE to be posted to the host channel's notification center. On receipt of this notification, call mvMqttGetNextReadableDataType() to determine the type of data received and use this information to select the appropriate system call to retrieve the data.

The integer written to the memory referenced by type will be one of the following values:

ConstantDescription
MV_MQTTREADABLEDATATYPE_NONENo unconsumed data is available at this time
MV_MQTTREADABLEDATATYPE_MESSAGERECEIVEDA message is ready for consumption
MV_MQTTREADABLEDATATYPE_MESSAGELOSTA message was lost; details are available
MV_MQTTREADABLEDATATYPE_CONNECTRESPONSEA response to a connect request is available
MV_MQTTREADABLEDATATYPE_SUBSCRIBERESPONSEA response to a subscribe request is available
MV_MQTTREADABLEDATATYPE_UNSUBSCRIBERESPONSEA response to an unsubscribe request is available
MV_MQTTREADABLEDATATYPE_PUBLISHRESPONSEA response to a publish request is available
MV_MQTTREADABLEDATATYPE_DISCONNECTRESPONSEA response to a disconnect request is available

Example

This function, taken from our MQTT demo code(link takes you to an external page), shows how you might use mvMqttGetNextReadableDataType() to check for the type of data received and to branch to the correct data-access function.

1
void mqtt_handle_readable_event() {
2
3
enum MvMqttReadableDataType readableDataType;
4
if (mvMqttGetNextReadableDataType(mqtt_channel, &readableDataType) != MV_STATUS_OKAY) return;
5
server_log("MQTT Event: data received of type %02X", readableDataType);
6
7
switch (readableDataType) {
8
case MV_MQTTREADABLEDATATYPE_CONNECTRESPONSE:
9
// A response to a connect request is available.
10
pushMessage(OnMQTTEventConnectResponse);
11
break;
12
case MV_MQTTREADABLEDATATYPE_MESSAGERECEIVED:
13
// A message is ready for consumption.
14
pushMessage(OnMQTTEventMessageReceived);
15
break;
16
case MV_MQTTREADABLEDATATYPE_MESSAGELOST:
17
// A message was lost, details are available.
18
pushMessage(OnMQTTEventMessageLost);
19
break;
20
case MV_MQTTREADABLEDATATYPE_SUBSCRIBERESPONSE:
21
// A response to a subscribe request is available.
22
pushMessage(OnMQTTEventSubscribeResponse);
23
break;
24
case MV_MQTTREADABLEDATATYPE_UNSUBSCRIBERESPONSE:
25
// A response to an unsubscribe request is available.
26
pushMessage(OnMQTTEventUnsubscribeResponse);
27
break;
28
case MV_MQTTREADABLEDATATYPE_PUBLISHRESPONSE:
29
// A response to a publish request is available.
30
pushMessage(OnMQTTEventPublishResponse);
31
break;
32
case MV_MQTTREADABLEDATATYPE_DISCONNECTRESPONSE:
33
// A response to a disconnect operation is available.
34
pushMessage(OnMQTTEventDisconnectResponse);
35
break;
36
default:
37
break;
38
}
39
}

mvMqttRequestConnect()

mvmqttrequestconnect page anchor

Initiate a connection to an MQTT broker

Declaration

1
extern enum MvStatus mvMqttRequestConnect(MvChannelHandle handle,
2
struct MvMqttConnectRequest *request);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
requestA pointer to an MvMqttConnectRequest structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTrequest does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within request are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDCERTIFICATIONMultiple credential types were supplied
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_REQUESTALREADYSENTThe request has already been sent, either successfully or not
MV_STATUS_TOOMANYELEMENTSMore than eight certificates were included in either the CA or device certificate chains
MV_STATUS_REQUIREDELEMENTMISSINGA mandatory request configuration element has not been included

Notifications

This call, if successful, may subsequently yield any of the following notifications.

Notification Event TypeDescription
MV_EVENTTYPE_CHANNELDATAREADABLEIssued to the host channel's notification center when data has been received through the channel. Call mvMqttReadConnectResponse() to the ultimate outcome of the request

Description

Only one connect is permitted per channel life cycle. To connect again, create a new channel.

For each channel, only one request can be issued. If Microvisor returns MV_STATUS_PARAMETERFAULT, MV_STATUS_INVALIDHANDLE, MV_STATUS_INVALIDBUFFERSIZE, MV_STATUS_INVALIDCERTIFICATION, MV_STATUS_TOOMANYELEMENTS, MV_STATUS_REQUIREDELEMENTMISSING or MV_STATUS_CHANNELCLOSED, then the request will not have been issued, and you can reconfigure the request and try again. Any other value indicates that the request has been sent, and any attempt to issue it again, or to use the channel for a fresh request, will result in MV_STATUS_REQUESTALREADYSENT being returned. Instead, send any subsequent MQTT request through a new channel. You can re-use the channel definition structure and buffers if you wish. Be sure to close the channel used for a given MQTT request once you have received the response or a failure notification.

The call's request parameter takes a pointer to an MvMqttConnectRequest structure:

1
struct MvMqttConnectRequest {
2
enum MvMqttProtocolVersion protocol_version,
3
struct mvSizedString host,
4
uint16_t port,
5
struct mvSizedString clientid,
6
struct MvMqttAuthentication *authentication,
7
struct MvTlsCredentials *tls_credentials,
8
uint32_t keepalive,
9
uint8_t clean_start,
10
struct MvMqttWill *will
11
}

This structure's properties are:

  • protocol_version — The MQTT protocol version used by the broker. Supported versions are 3.1.1 and 5, chosen using the constants MV_MQTTPROTOCOLVERSION_V3_1_1 and MV_MQTTPROTOCOLVERSION_V5 respectively.
  • host — A data structure comprising the broker's URL as bytes, which need not be nul-terminated, and the number of bytes.
  • port — The broker's port number.
  • clientid — A data structure comprising a client ID as bytes, which need not be nul-terminated, and the number of bytes. The client ID must be unique to the broker. MQTT 3.1.1 allows you to send a zero-byte client ID, if you don't need a state to be held by the broker. In this case, the clean_start flag must be set to a non-zero value, or the broker will reject the connection.
  • authentication — A pointer to an MvMqttAuthentication structure, see below.
  • tls_credentials — A pointer to an MvMqttTlsCredentials structure, see below.
  • keepalive — The keepalive interval in seconds.
  • clean_start — A flag which can be set to inform the broker you do not wish to establish a persistent session, i.e., the broker should completely forget about the client when the connection closes. Pass zero for a persistent session: the broker will retain any subscriptions for the client plus all missed messages for the client that were subscribed with an MQTT quality of service (QoS) level 1 or 2.
  • will — An optional MQTT will for the connection, see below.

Authentication

The connection request's authentication property takes a pointer to an MvMqttAuthentication structure:

1
struct MvMqttAuthentication {
2
enum MvMqttAuthenticationMethod method,
3
struct MvMqttUsernamePassword *username_password
4
}

The value of method is MV_MQTTAUTHENTICATIONMETHOD_NONE or MV_MQTTAUTHENTICATIONMETHOD_USERNAMEPASSWORD. If you are using the former, there is no need to include the username_password property.

To add a username and password to the MvMqttAuthentication structure, complete and pass in the following data:

1
struct MvMqttUsernamePassword {
2
struct mvSizedString username,
3
struct mvSizedString password
4
}

Provide each credential as a data structure that comprises the name of the requested item and its length.

TLS credentials

To provide TLS credentials to allow your application's access to a named broker to be authenticated, include a pointer to the following structure as the value of your MvMqttConnectRequest's tls_credentials property:

1
struct MvTlsCredentials {
2
struct MvTlsCertificateChain cacert,
3
struct MvOwnTlsCertificateChain clientcert
4
}

This structure's properties are themselves structures:

1
struct MvTlsCertificateChain {
2
uint32_t num_certs,
3
struct MvSizedString *certs
4
}
1
struct MvOwnTlsCertificateChain {
2
struct TlsCertificateChain chain,
3
struct MvSizedString key
4
}

Each MvTlsCertificateChain structure comprises an array of certificates in binary form and the number of certificates in the array. Each MvOwnTlsCertificateChain contains both a chain of certificates and an encryption key (RSA only).

Provide the certificate as a data structure incorporating a pointer to the bytes and the number of bytes.

Certificates and keys must be provided as DER (Distinguished Encoding Rules) binary data(link takes you to an external page). Keys must be provided in PKCS#8 format(link takes you to an external page). Convert to these format from commonplace .pem files as follows:

openssl x509 -in cert.pem -inform pem -out cert.der -outform der

For keys:

openssl pkcs8 -topk8 -in key.pem -inform pem -out key.der -outform der -nocrypt

Wills

An MQTT client may specify a will message when it connects to a broker. A will is a normal MQTT message which the broker stores. If the broker subsequently detects that the client has disconnected unexpectedly, it sends the will to all other clients that have subscribed to its will messages topic (see your broker's documentation for this topic's name). If the client disconnects gracefully, the broker discards the will.

You specify your will when you configure your connection to the broker. Include it in the MvMqttConnectRequest structure as its will property. The data is provided as an MvMqttWill structure:

1
struct MvMqttWill {
2
struct MvSizedString topic,
3
struct MvSizedString payload,
4
uint32_t qos,
5
uint8_t retain
6
}

This structure's properties are:

  • topic — A data structure comprising the topic name as bytes, which need not be nul-terminated, and the number of bytes.
  • payload — A data structure comprising the message bytes, which need not be nul-terminated, and the number of bytes.
  • qos — The required MQTT Quality of Service setting: 0 (at most once) or 1 (at least once). Microvisor does not support QoS level 2.
  • retain — The message retention flag. Set to a non-zero value to instruct the broker to set the message as its topic's retained message. Each topic can have a single retained message, which will be automatically sent to every new subscriber.

mvMqttReadConnectResponse()

mvmqttreadconnectresponse page anchor

Read the MQTT connection attempt response

Declaration

1
extern enum MvStatus mvMqttReadConnectResponse(MvChannelHandle handle,
2
struct MvMqttConnectResponse *response);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
responseA pointer to memory into which Microvisor will write an MvMqttConnectResponse structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTresponse does not reference memory accessible to the application
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. The returned data type will MV_MQTTREADABLEDATATYPE_CONNECTRESPONSE if the data is the response to an attempt to connect to an MQTT broker. In this case, call mvMqttReadConnectResponse(). Microvisor will write an MvMqttConnectResponse record which your code can then parse:

1
struct MvMqttConnectResponse {
2
enum MvMqttConnectStatus status,
3
uint32_t reason_code
4
}

Request states

The 32-bit integer in status will be one of the following values:

ConstantConnection OnlyDescription
MV_MQTTREQUESTSTATE_REQUESTCOMPLETEDNoThe request was completed successfully
MV_MQTTREQUESTSTATE_INVALIDPARAMETERSNoInvalid connection parameters were specified
MV_MQTTREQUESTSTATE_ALREADYCONNECTEDNoAn MQTT connection has already been attempted on this channel
MV_MQTTREQUESTSTATE_NOTCONNECTEDNoThe MQTT connection was not established or failed at the point the request was made
MV_MQTTREQUESTSTATE_NXDOMAINYesDNS resolution of the broker URL failed
MV_MQTTREQUESTSTATE_UNKNOWNCAYesAn unknown certificate authority was specified
MV_MQTTREQUESTSTATE_CERTIFICATEEXPIREDYesA certificate is out of date
MV_MQTTREQUESTSTATE_SOCKETERRORYesA socket error was encountered on connect
MV_MQTTREQUESTSTATE_CONNECTIONCIRCUITBREAKERNoThe Microvisor cloud dropped the connection because incoming messages were rate limited

The value of reason_code is supplied by the broker and will be a standard MQTT value. Zero indicates no error.

Example

1
void mqtt_handle_connect_response_event() {
2
3
struct MvMqttConnectResponse response = {};
4
5
enum MvStatus status = mvMqttReadConnectResponse(mqtt_channel, &response);
6
if (status != MV_STATUS_OKAY) {
7
server_error("mvMqttReadConnectResponse returned 0x%02x\n", (int) status);
8
pushMessage(OnBrokerConnectFailed);
9
return;
10
}
11
12
server_log("Connect response status is 0x%02X", response.status);
13
if (response.status != MV_MQTTCONNECTSTATUS_CONNACKRECEIVED) {
14
// Not the status we expect
15
pushMessage(OnBrokerConnectFailed);
16
return;
17
}
18
19
server_log("Connect response reason_code is 0x%02X", (int)response.reason_code);
20
if (response.reason_code != 0x00) {
21
// Not the reason code we expect
22
pushMessage(OnBrokerConnectFailed);
23
return;
24
}
25
26
server_log("MQTT broker connection established");
27
pushMessage(OnBrokerConnected);
28
}

mvMqttRequestSubscribe()

mvmqttrequestsubscribe page anchor

Subscribe to one or more MQTT topics

Declaration

1
extern enum MvStatus mvMqttRequestSubscribe(MvChannelHandle handle,
2
struct MvMqttSubscribeRequest *request);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
subscriptionsA pointer to an MvMqttSubscribeRequest structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTrequest does not reference memory accessible to the application
MV_STATUS_LATEFAULTA pointer within request is illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_RATELIMITEDThere are too many MQTT requests currently in flight
MV_STATUS_TOOMANYELEMENTSThere are too many (>8) topics specified in the request

Notifications

This call, if successful, may subsequently yield any of the following notifications.

Notification Event TypeDescription
MV_EVENTTYPE_CHANNELDATAREADABLEIssued to the host channel's notification center when data has been received through the channel. Call mvMqttReadSubscribeResponse() to the ultimate outcome of the request

Description

Only one subscription request will be serviced at a time. Subscribe to multiple topics with a single subscription request. However, you can current subscribe to no more than eight topics with one call.

1
struct MvMqttSubscribeRequest {
2
uint32_t correlation_id,
3
struct MvMqttSubscription *subscriptions,
4
uint32_t num_subscriptions
5
}

The value of correlation_id is an application-defined ID that will be included in the response to enable you to match the response to the source request. Requests may be fulfilled in a non-deterministic order.

The subscriptions property takes a pointer to an array of MvMqttSubscription structures. Set the number of array elements as the num_subscriptions property. Each element is a structure:

1
struct MvMqttSubscription {
2
struct MvSizedString topic,
3
uint32_t desired_qos,
4
uint32_t nl,
5
uint32_t rap,
6
uint32_t rh
7
}

This structure's properties are:

  • topic — A data structure comprising the topic name as bytes, which need not be nul-terminated, and the number of bytes.
  • desired_qos — The MQTT quality of service (QoS) setting (0 or 1; Microvisor does not support QoS level 2) you'd like to be applied.
  • nl — Your preferred MQTT no-local flag to request. MQTT v5 only.
  • rap — Your preferred MQTT retain-as-published flag. MQTT v5 only.
  • rh — Your preferred MQTT retain setting. MQTT v5 only.

mvMqttReadSubscribeResponse()

mvmqttreadsubscriberesponse page anchor

Read the response to an MQTT subscription request

Declaration

1
extern enum MvStatus mvMqttReadSubscribeResponse(MvChannelHandle handle,
2
struct MvMqttSubscribeResponse *response);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
responseA pointer to an MvMqttSubscribeResponse structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTresponse does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within response are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_INVALIDBUFFERSIZEResponse data doesn't fit into the buffer provided for response codes

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_SUBSCRIBERESPONSE, call mvMqttReadSubscribeResponse(). Pass in an MvMqttSubscribeResponse record which Microvisor will use to write back response data:

1
struct MvMqttSubscribeResponse {
2
enum MvMqttRequestState *request_state,
3
uint32_t *correlation_id,
4
uint32_t *reason_codes,
5
uint32_t reason_codes_size,
6
uint32_t *reason_codes_len
7
}

The integer written to the memory referenced by request_state will be one of the values listed above.

The value of correlation_id is a pointer to the ID specified in the subscription request, allowing you to map responses to source requests. Requests may be fulfilled in a non-deterministic order.

The value is reason_codes is a pointer to an array of 32-bit values. The maximum size of the array is placed in reason_codes_size, and must match the maximum specified in the subscription request (as num_subscriptions). This will be the same as or larger than the number of codes written, which Microvisor will is write into the memory referenced by reason_codes_len.


mvMqttRequestUnsubscribe()

mvmqttrequestunsubscribe page anchor

Unsubscribe from one or more MQTT topics

Declaration

1
extern enum MvStatus mvMqttRequestUnsubscribe(MvChannelHandle handle,
2
struct MqttUnsubscribeRequest *request);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
requestA pointer to an MqttUnsubscribeRequest structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTrequest does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within request are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_RATELIMITEDThere are too many MQTT requests currently in flight
MV_STATUS_TOOMANYELEMENTSThere are too many (>8) topics specified in the request

Notifications

This call, if successful, may subsequently yield any of the following notifications.

Notification Event TypeDescription
MV_EVENTTYPE_CHANNELDATAREADABLEIssued to the host channel's notification center when data has been received through the channel. Call mvMqttReadUnsubscribeResponse() to the ultimate outcome of the request

Description

Only one unsubscribe request will be serviced at a time. Unsubscribe to multiple topics with a single unsubscribe request. However, you can current subscribe to no more than eight topics with one call.

1
struct MvMqttUnsubscribeRequest {
2
uint32_t correlation_id,
3
struct MvSizedString *topics,
4
uint32_t num_topics
5
}

The value of correlation_id is an application-defined ID that will be included in the response to enable you to match the response to the source request. Requests may be fulfilled in a non-deterministic order.

The topics property takes a pointer to an array of data structures. Each element comprises the name of a topic as bytes and the number of bytes. The number of elements in the array should be placed in num_topics.


mvMqttReadUnsubscribeResponse()

mvmqttreadunsubscriberesponse page anchor

Read the response to an MQTT unsubscribe request

Declaration

1
extern enum MvStatus mvMqttReadUnsubscribeResponse(MvChannelHandle handle,
2
struct MvMqttUnsubscribeResponse *response);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
responseA pointer to an MvMqttUnsubscribeResponse structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTresponse does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within response are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_UNSUBSCRIBERESPONSE, call mvMqttReadUnsubscribeResponse(). Pass in an MvMqttUnsubscribeResponse record which Microvisor will use to write back the outcome(s) of the operation:

1
struct MvMqttUnsubscribeResponse {
2
enum MQTTRequestState *request_state,
3
uint32_t *correlation_id,
4
uint32_t *reason_codes,
5
uint32_t *reason_codes_len,
6
uint32_t reason_codes_size
7
}

The integer written to the memory referenced by request_state will be one of the values listed above.

The value of correlation_id is a pointer to the ID specified in the subscription request, allowing you to map responses to source requests. Requests may be fulfilled in a non-deterministic order.

The value of reason_codes is a pointer to a buffer into which Microvisor will write a 32-bit MQTT reason code for each of the topics specified in the original unsubscribe request. Specify the size of the buffer in bytes as reason_codes_size; it must match the maximum specified in the unsubscribe request (as num_topics). This will be the same as or larger than the number of codes written, which Microvisor will write to the memory referenced by reason_codes_len.


mvMqttRequestPublish()

mvmqttrequestpublish page anchor

Post a message to an MQTT topic

Declaration

1
extern enum MvStatus mvMqttRequestPublish(MvChannelHandle handle,
2
struct MvMqttPublishRequest *request);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
requestA pointer to an MvMqttPublishRequest structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTrequest does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within request are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_RATELIMITEDThere are too many MQTT requests currently in flight

Notifications

This call, if successful, may subsequently yield any of the following notifications.

Notification Event TypeDescription
MV_EVENTTYPE_CHANNELDATAREADABLEIssued to the host channel's notification center when data has been received through the channel. Call mvMqttReadPublishResponse() to the ultimate outcome of the request

Description

The call's request parameter takes a pointer to an MvMqttPublishRequest structure:

1
struct MvMqttPublishRequest {
2
uint32_t correlation_id,
3
struct MvSizedString topic,
4
struct MvSizedString payload,
5
uint32_t desired_qos,
6
uint32_t retain
7
}

This structure's properties are:

  • correlation_id — A 32-bit integer you can use to match a subsequent response to this request. Requests may be fulfilled in a non-deterministic order.
  • topic — A data structure comprising the topic name as bytes, which need not be nul-terminated, and the number of bytes.
  • payload — A data structure comprising the message bytes, which need not be nul-terminated, and the number of bytes.
  • desired_qos — The MQTT quality of service setting (0, 1 or 2) you'd like to be applied.
  • retain — The MQTT retention behavior you would like the broker to apply to the message. Set to a non-zero value to instruct the broker to set the message as its topic's retained message. Each topic can have only one retained message, which will be automatically sent to every new subscriber.

mvMqttReadPublishResponse()

mvmqttreadpublishresponse page anchor

Read an MQTT publish-to-topic response

Declaration

1
extern enum MvStatus mvMqttReadPublishResponse(MvChannelHandle handle,
2
const struct MvMqttPublishResponse *response);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
responseA pointer to an MvMqttPublishResponse structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTresponse does not reference memory accessible to the application
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_PUBLISHRESPONSE, call mvMqttReadPublishResponse(). Microvisor will use the MvMqttPublishResponse record which your code provides to write out publication outcome information:

1
struct MvMqttPublishResponse {
2
enum MQTTRequestState request_state,
3
uint32_t correlation_id,
4
uint32_t reason_code
5
}

The integer written to request_state will be one of the values listed above.

The value of correlation_id is the ID specified in the subscription request, allowing you to map responses to source requests. Requests may be fulfilled in a non-deterministic order.

The value written to reason_code is an MQTT status value.


mvMqttReceiveMessage()

mvmqttreceivemessage page anchor

Read a received MQTT message

Declaration

1
extern enum MvStatus mvMqttReceiveMessage(MvChannelHandle handle,
2
struct MvMqttMessage *message);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
messageA pointer to an MvMqttMessage structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTmessage does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within message are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_INVALIDBUFFERSIZESome response elements don't fit into the buffer provided

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_MESSAGERECEIVED, the device has received a message from the broker. Call mvMqttReceiveMessage(). Microvisor will use the MvMqttMessage record which your code supplies to write back message data:

1
struct MvMqttMessage {
2
uint32_t *correlation_id,
3
struct MvSizedStringBuffer topic,
4
struct MvSizedStringBuffer payload,
5
uint32_t *qos,
6
uint8_t *retain
7
}

This structure's properties are:

  • correlation_id — A pointer to memory where Microvisor will write a 32-bit unsigned integer which will match the ID specified in the subscription request, allowing you to map responses to source requests. Requests may be fulfilled in a non-deterministic order.
  • topic — A pointer to a buffer structure which Microvisor will use to write back the topic name.
  • payload — A pointer to a buffer structure which Microvisor will use to write back the message payload.
  • qos — A pointer to the MQTT quality of service setting applied. You should acknowledge receipt of messages with QoS values 1 or 2 by calling mvMqttAcknowledgeMessage().
  • retain — A pointer to an MQTT flag indicating whether the message has been retained, not deleted by the broker.

mvMqttReceiveLostMessageInfo()

mvmqttreceivelostmessageinfo page anchor

Read information about a lost MQTT message

Declaration

1
extern enum MvStatus mvMqttReceiveLostMessageInfo(MvChannelHandle handle,
2
struct MvMqttLostMessageInfo *info);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
infoA pointer to an MvMqttLostMessageInfo structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTinfo does not reference memory accessible to the application
MV_STATUS_LATEFAULTOne or more of the pointers within info are illegal. The channel is no longer usable and should be closed
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_INVALIDBUFFERSIZESome response elements don't fit into the buffer provided

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_MESSAGELOST, call mvMqttReceiveLostMessageInfo(). Microvisor will use the MvMqttLostMessageInfo record which your code provides to write back information about the lost message:

1
struct MvMqttMessage {
2
enum MvMqttLostMessageReason *reason,
3
uint32_t *correlation_id,
4
struct MvSizedStringBuffer topic,
5
uint32_t *message_len
6
}

The integer placed into memory referenced by reason will beMV_MQTTLOSTMESSAGEREASON_DEVICERECEIVEBUFFERTOOSMALL if the buffer allocated by the application was insufficient to receive the message. Consider increasing the size of the channel's RX buffer.

This structure's other properties are:

  • correlation_id — A pointer to memory where Microvisor will write a 32-bit unsigned integer which will match the ID specified in the subscription request, allowing you to map responses to source requests. Requests may be fulfilled in a non-deterministic order.
  • topic — A pointer to a buffer structure which Microvisor will use to write back the topic name.
  • message_len — A pointer to the lost message's size in bytes.

mvMqttAcknowledgeMessage()

mvmqttacknowledgemessage page anchor

Acknowledge the receipt of an MQTT message that arrived with QoS 1 or 2.

Declaration

1
extern enum MvStatus mvMqttAcknowledgeMessage(MvChannelHandle handle,
2
uint32_t correlation_id);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
correlation_idThe ID of the message whose receipt is to be acknowledged

Possible errors

Error ValueDescription
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_RATELIMITEDThere are too many MQTT requests currently in flight

Description

The receipt of messages delivered with an MQTT quality of service (QoS) value of 1 or 2 should be manually acknowledged, and you should call mvMqttAcknowledgeMessage() to do so.


mvMqttRequestDisconnect()

mvmqttrequestdisconnect page anchor

Disconnect from the channel's current MQTT broker

Declaration

extern enum MvStatus mvMqttRequestDisconnect(MvChannelHandle handle);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT

Possible errors

Error ValueDescription
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed
MV_STATUS_RATELIMITEDThere are too many MQTT requests currently in flight

Notifications

This call, if successful, may subsequently yield any of the following notifications.

Notification Event TypeDescription
MV_EVENTTYPE_CHANNELDATAREADABLEIssued to the host channel's notification center when data has been received through the channel. Call mvMqttReadDisconnectResponse() to the ultimate outcome of the request

Description

Call mvMqttRequestDisconnect() to request disconnection from the broker you're currently connected to through the channel. This will result in the asynchronous posting of a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE to your channel notification center. On receipt of this notification, you should call mvMqttGetNextReadableDataType() and check the returned data type for MV_MQTTREADABLEDATATYPE_DISCONNECTRESPONSE. If the values match, call mvMqttReadDisconnectResponse().


mvMqttReadDisconnectResponse()

mvmqttreaddisconnectresponse page anchor

Read an MQTT disconnect response

Declaration

1
extern enum MvStatus mvMqttReadDisconnectResponse(MvChannelHandle handle,
2
struct MvMqttDisconnectResponse *response);

Parameters

ParameterDescription
handleThe handle of the channel over which to establish the connection. This must be a channel of type MV_CHANNELTYPE_MQTT
responseA pointer to an MvMqttDisconnectResponse structure

Possible errors

Error ValueDescription
MV_STATUS_PARAMETERFAULTresponse does not reference memory accessible to the application
MV_STATUS_INVALIDHANDLEhandle does not reference a valid channel of type MV_CHANNELTYPE_MQTT
MV_STATUS_CHANNELCLOSEDThe specified channel has already been closed

Description

Your application should call mvMqttGetNextReadableDataType() when the MQTT channel receives a notification of type MV_EVENTTYPE_CHANNELDATAREADABLE. If the returned data type is MV_MQTTREADABLEDATATYPE_DISCONNECTRESPONSE, call mvMqttReadDisconnectResponse(). Pass in an MvMqttDisconnectResponse record which Microvisor will use to write back response data:

1
struct MvMqttDisconnectResponse {
2
enum MQTTRequestState request_state,
3
uint32_t disconnect_code
4
}

The integer written to request_state will be one of the values listed above.

As the name of the second property indicates, the response you read may not have been initiated by a call to mvMqttRequestDisconnect(). This status will also be generated if the connection to the broker was lost unexpectedly. The value of disconnect_code is a standard MQTT disconnection status value.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.