MQTT Class

Properties   Methods   Events   Configuration Settings   Errors  

A lightweight, fully-featured MQTT client implementation.

Syntax

MQTT

Remarks

The MQTT class provides a lightweight, fully-featured MQTT client implementation with support for versions 3.1.1 and 5.0. The class supports plaintext and TLS-enabled connections over both standard TCP and WebSockets.

Connecting

Connecting to an MQTT server is easy; in the simplest case, set the ClientId property and call the Connect method, passing it the server's hostname and port number.

When connecting to an MQTT server, the class sends the following information:

If CleanSession is True, check the SessionPresent configuration setting once connected to determine whether the server actually had any session state saved.

Refer to CleanSession, SaveSession, and RestoreSession for more information about MQTT sessions and session state persistence; refer to WillTopic, WillMessage, WillQOS, and WillRetain for more information about MQTT Wills.

Basic Connection Example

mqtt1.ClientId = "testClient";
mqtt1.CleanSession = true;
mqtt1.KeepAliveInterval = 30;
mqtt1.WillTopic = "wills/" + mqtt1.ClientId;
mqtt1.WillMessage = mqtt1.ClientId + " was disconnected ungracefully!";
mqtt1.Connect("mqtt.test-server.com", 1883);

Topic Subscriptions

The Subscribe and Unsubscribe methods are used to subscribe to and unsubscribe from topics.

When subscribing, pass one or more topic filters and QoS levels to indicate the topics to subscribe to and the desired QoS level(s). Topic filters may contain wildcards in order to match multiple topics on the server.

Subscribe Examples

// Subscribed event handler.
mqtt1.OnSubscribed += (s, e) => {
  if (e.ResponseCode <= 2)
    Console.WriteLine("Subscribed to " + e.TopicFilter + " at QoS " + e.QOS + ".");
  else
    Console.WriteLine("Failed to subscribe to " + e.TopicFilter + ".");
};

// Basic, subscribe to some topic filters, all at the same QoS level.
mqtt1.Subscribe("home,home/floor1/+/temperature,home/floor2/#", 2);

// A bit more advanced, subscribe to the same topic filters, but at different QoS levels.
mqtt1.Config("TopicQOSArray=1,2,2");
// The 0 is ignored here since we've specified individual QoS values explicitly.
mqtt1.Subscribe("home,home/floor1/+/temperature,home/floor2/#", 0);

After subscribing to topics, any messages received will cause the MessageIn, and potentially also the MessageAck, events to fire. Refer to those events for more information about processing steps for inbound messages.

When unsubscribing, pass the exact same topic filter that was used to subscribe.

Unsubscribe Example

// Unsubscribe from topic filters; have to use the exact same strings as before. If this
// was to be called after calling the code example shown for the Subscribe() method, we
// would still be subscribed to the "home" topic filter.
mqtt1.Unsubscribe("home/floor1/+/temperature,home/floor2/#");

Refer to Subscribe and Unsubscribe for more information about subscriptions and topic filters.

Publishing Messages

To publish messages to topics, use the PublishMessage and PublishData methods.

PublishMessage is used to publish a message with a string payload, while PublishData is used to publish a message with a raw data payload. Both also accept the name of a topic to publish to, and a QoS level at which to publish.

Publish Examples

// Publish a simple string-based message.
mqtt1.PublishMessage("/home/floor1/security/camera2", 1, "Cat detected!");

// Publish a raw data message.
byte[] catPicture = ...;
mqtt1.PublishData("/home/floor1/security/camera2", 1, catPicture);

Refer to PublishData and PublishMessage for more information about message publishing and processing steps for outbound messages, as well as topic naming.

MQTT 5 Notes

MQTT 5 is similar to v3.1.1, with a few changes and several new features. Major differences include:

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

CleanSessionDetermines whether a clean session is used once connected.
ClientIdA string that uniquely identifies this instance of the class to the server.
ConnectedTriggers a connection or disconnection.
FirewallAutoDetectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallTypeThis property determines the type of firewall to connect through.
FirewallHostThis property contains the name or IP address of firewall (optional).
FirewallPasswordThis property contains a password if authentication is to be used when connecting through the firewall.
FirewallPortThis property contains the TCP port for the firewall Host .
FirewallUserThis property contains a user name if authentication is to be used connecting through a firewall.
IncomingMessageCountThe number of records in the IncomingMessage arrays.
IncomingMessageContentTypeString describing the content of the message.
IncomingMessageCorrelationDataUsed by the sender of the request message to identify which request the response message is for when it is received.
IncomingMessageDuplicateWhether or not this message's Duplicate flag is set.
IncomingMessageMessageThis message's raw data payload.
IncomingMessageMessageExpIntervalThe lifetime of the message in seconds specified by the sender.
IncomingMessagePacketIdThis message's packet Id.
IncomingMessagePayloadFormatIndicatorIndicates whether the payload is unspecified bytes or UTF-8 Encoded character data.
IncomingMessageQoSThis message's QoS level.
IncomingMessageResponseTopicString used as the topic name for a response message.
IncomingMessageRetainedWhether or not this message's Retain flag is set.
IncomingMessageStateThis message's current state.
IncomingMessageSubscriptionIdentifiersA comma separated list of any SubscriptionIdentifiers associated with any client subscription(s) that caused this message to be delivered.
IncomingMessageTopicThis message's topic.
IncomingMessageTopicAliasAn integer used to identify the topic instead of the full topic filter in order to reduce the size of the publish packet.
KeepAliveIntervalThe maximum period of inactivity the class will allow before sending a keep-alive packet.
LocalHostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
LocalPortThe TCP port in the local host where the class binds.
OutgoingMessageCountThe number of records in the OutgoingMessage arrays.
OutgoingMessageContentTypeString describing the content of the message.
OutgoingMessageCorrelationDataUsed by the sender of the request message to identify which request the response message is for when it is received.
OutgoingMessageDuplicateWhether or not this message's Duplicate flag is set.
OutgoingMessageMessageThis message's raw data payload.
OutgoingMessageMessageExpIntervalThe lifetime of the message in seconds specified by the sender.
OutgoingMessagePacketIdThis message's packet Id.
OutgoingMessagePayloadFormatIndicatorIndicates whether the payload is unspecified bytes or UTF-8 Encoded character data.
OutgoingMessageQoSThis message's QoS level.
OutgoingMessageResponseTopicString used as the topic name for a response message.
OutgoingMessageRetainedWhether or not this message's Retain flag is set.
OutgoingMessageStateThis message's current state.
OutgoingMessageSubscriptionIdentifiersA comma separated list of any SubscriptionIdentifiers associated with any client subscription(s) that caused this message to be delivered.
OutgoingMessageTopicThis message's topic.
OutgoingMessageTopicAliasAn integer used to identify the topic instead of the full topic filter in order to reduce the size of the publish packet.
PasswordA password if authentication is to be used.
ReadyToSendIndicates whether the class is ready to send data.
RemoteHostThe address of the remote host. Domain names are resolved to IP addresses.
RemotePortThe port of the MQTT server (default is 1883). The default port for SSL is 8883.
SSLAcceptServerCertEncodedThe certificate (PEM/base64 encoded).
SSLCertEncodedThe certificate (PEM/base64 encoded).
SSLCertStoreThe name of the certificate store for the client certificate.
SSLCertStorePasswordIf the certificate store is of a type that requires a password, this property is used to specify that password in order to open the certificate store.
SSLCertStoreTypeThe type of certificate store for this certificate.
SSLCertSubjectThe subject of the certificate used for client authentication.
SSLEnabledWhether TLS/SSL is enabled.
SSLServerCertEncodedThe certificate (PEM/base64 encoded).
TimeoutA timeout for the class.
UserA username if authentication is to be used.
VersionThe MQTT protocol version that the class will conform to.
WillMessageThe message that the server should publish in the event of an ungraceful disconnection.
WillTopicThe topic that the server should publish the WillMessage to in the event of an ungraceful disconnection.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

ConfigSets or retrieves a configuration setting.
ConnectConnects to the remote host.
DisconnectDisconnects from the remote host.
DoEventsProcesses events from the internal message queue.
InterruptInterrupt the current action and disconnects from the remote host.
PublishDataPublishes a message with a raw data payload.
PublishMessagePublishes a message with a string payload.
ResetReset the class.
RestoreSessionRestores session state data.
SaveSessionSaves session state data.
SubscribeSubscribes the class to one or more topic filters.
UnsubscribeUnsubscribes the class from one or more topic filters.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

ConnectedFired immediately after a connection completes (or fails).
ConnectionStatusFired to indicate changes in connection state.
DisconnectedFired when a connection is closed.
ErrorInformation about errors during data delivery.
LogFires once for each log message.
MessageAckFired when an incoming or outgoing message has completed all acknowledgment steps.
MessageInFired when an incoming message has been received and/or fully acknowledged.
MessageOutFired when an outgoing message has been sent and/or fully acknowledged.
ReadyToSendFired when the class is ready to send data.
SSLServerAuthenticationFired after the server presents its certificate to the client.
SSLStatusShows the progress of the secure connection.
SubscribedFires for each topic filter subscription the server acknowledges.
UnsubscribedFires when the server has acknowledged an unsubscribe request.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AutoReconnectWhether to automatically attempt to reconnect in the event of a connection error.
ClientTopicAliasMaxThe maximum value the client will accept for a topic alias sent by the server.
ConnAckPropertiesJSON string containing the properties returned in the CONNACK packet.
ConnectionTimeoutHow long to wait for a connection attempt to succeed.
ConnectPropertiesJSON string specifying properties to be included in the CONNECT packet.
DisconnectPropertiesJSON string containing DISCONNECT packet properties.
DisconnectReasonCodeCode describing the reason the client or server closed the connection.
DuplicateWhether to set the Duplicate flag when publishing a message.
IncomingUserPropCountThe size of the IncomingUserPropName and IncomingUserPropValue arrays.
IncomingUserPropName[i]The name of the user property at index i.
IncomingUserPropValue[i]The value of the user property at index i.
LogLevelThe level of detail that is logged.
OutgoingMessagePropertiesJSON string specifying properties to be included in the PUBLISH packet.
OutgoingPacketIdThe packet Id of the last message published.
OutgoingUserPropCountControls the size of the OutgoingUserPropName and OutgoingUserPropValue configuration arrays.
OutgoingUserPropName[i]The name of the User Property at index i.
OutgoingUserPropValue[i]The value of the User Property at index i.
RepublishIntervalHow many seconds to wait before republishing unacknowledged messages.
ResponseTopicTopic name for a response message.
RetainWhether to set the Retain flag when publishing a message.
SendCustomPacketSends a packet constructed using the supplied hex byte string.
ServerTopicAliasMaxThe highest value that the Server will accept as a Topic Alias sent by the Client.
SessionExpIntervalThe length of time in seconds the client and server should store session state data after the connection is closed.
SessionPresentWhen connecting with CleanSession disabled, indicates whether the server actually had any previous session data stored.
SessionStateFileFile to use for saving and restoring session data.
SubscriptionIdentifierA numeric subscription identifier included in SUBSCRIBE packet which will be returned with messages delivered for that subscription.
TopicAliasValue that is used to identify the Topic instead of using the Topic Name in order to reduce packet size.
TopicDelimiterThe string to use as a delimiter in a topic filter list string.
TopicNLArrayList of No Local option flags for subscription topic filters.
TopicQOSArrayComma-separated list of topic filter QoS values to use when subscribing.
TopicRAPArrayList of Retain As Published option flags for subscription topic filters.
TopicRHArrayList of Retain Handling option values for subscription topic filters.
WillPropertiesJSON string specifying will properties to be included in the CONNECT packet.
WillQOSThe QoS value to use for the Will message.
WillRetainWhether the server should retain the Will message after publishing it.
ConnectionTimeoutSets a separate timeout value for establishing a connection.
FirewallAutoDetectTells the class whether or not to automatically detect and use firewall system settings, if available.
FirewallHostName or IP address of firewall (optional).
FirewallPasswordPassword to be used if authentication is to be used when connecting through the firewall.
FirewallPortThe TCP port for the FirewallHost;.
FirewallTypeDetermines the type of firewall to connect through.
FirewallUserA user name if authentication is to be used connecting through a firewall.
KeepAliveIntervalThe retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received.
KeepAliveTimeThe inactivity time in milliseconds before a TCP keep-alive packet is sent.
LingerWhen set to True, connections are terminated gracefully.
LingerTimeTime in seconds to have the connection linger.
LocalHostThe name of the local host through which connections are initiated or accepted.
LocalPortThe port in the local host where the class binds.
MaxLineLengthThe maximum amount of data to accumulate when no EOL is found.
MaxTransferRateThe transfer rate limit in bytes per second.
ProxyExceptionsListA semicolon separated list of hosts and IPs to bypass when using a proxy.
TCPKeepAliveDetermines whether or not the keep alive socket option is enabled.
TcpNoDelayWhether or not to delay when sending packets.
UseIPv6Whether to use IPv6.
LogSSLPacketsControls whether SSL packets are logged when using the internal security API.
OpenSSLCADirThe path to a directory containing CA certificates.
OpenSSLCAFileName of the file containing the list of CA's trusted by your application.
OpenSSLCipherListA string that controls the ciphers to be used by SSL.
OpenSSLPrngSeedDataThe data to seed the pseudo random number generator (PRNG).
ReuseSSLSessionDetermines if the SSL session is reused.
SSLCACertsA newline separated list of CA certificate to use during SSL client authentication.
SSLCheckCRLWhether to check the Certificate Revocation List for the server certificate.
SSLCipherStrengthThe minimum cipher strength used for bulk encryption.
SSLEnabledCipherSuitesThe cipher suite to be used in an SSL negotiation.
SSLEnabledProtocolsUsed to enable/disable the supported security protocols.
SSLEnableRenegotiationWhether the renegotiation_info SSL extension is supported.
SSLIncludeCertChainWhether the entire certificate chain is included in the SSLServerAuthentication event.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
TLS12SignatureAlgorithmsDefines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True.
TLS12SupportedGroupsThe supported groups for ECC.
TLS13KeyShareGroupsThe groups for which to pregenerate key shares.
TLS13SignatureAlgorithmsThe allowed certificate signature algorithms.
TLS13SupportedGroupsThe supported groups for (EC)DHE key exchange.
AbsoluteTimeoutDetermines whether timeouts are inactivity timeouts or absolute timeouts.
FirewallDataUsed to send extra data to the firewall.
InBufferSizeThe size in bytes of the incoming queue of the socket.
OutBufferSizeThe size in bytes of the outgoing queue of the socket.

Copyright (c) 2021 /n software inc. - All rights reserved.
IPWorks MQ 2020 Qt Edition - Version 20.0 [Build 7941]