MQTT Component
Properties Methods Events Configuration Settings Errors
A lightweight, fully-featured MQTT client implementation.
Syntax
TiotMQTT
Remarks
The MQTT component provides a lightweight, fully-featured MQTT client implementation with support for versions 3.1.1 and 5.0. The component 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 component sends the following information:
- The values of the ClientId, CleanSession, and KeepAliveInterval properties.
- The value of the User property (if non-empty).
- The value of the Password property (if non-empty).
- The values of the WillTopic and WillMessage properties and the WillQOS and WillRetain configuration settings.
- MQTT 5 specific values from ClientTopicAliasMax, SessionExpInterval, ConnectProperties and WillProperties.
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:
- The Clean Session flag functionality is divided into two properties to allow for finer control over session state data: the Clean Start flag (see CleanSession) and the new SessionExpInterval.
- All response packets (CONNACK, PUBACK, PUBREC, PUBREL, PUBCOMP, SUBACK, UNSUBACK, DISCONNECT) now contain a reason code describing why operations succeeded or failed. See MessageAck, Subscribed, Unsubscribed, and DisconnectReasonCode for details.
- The Request / Response pattern is formalized by the addition of the ResponseTopic. Additional properties such as correlation data and be specified via OutgoingMessageProperties and ConnectProperties.
- New subscription features: Shared Subscriptions, Subscription Options, and SubscriptionIdentifier (see Subscribe for details).
- Topic Aliases can be sent by both client and server to refer to topic filters by shorter numerical identifiers in order to save bandwidth (see TopicAlias, ServerTopicAliasMax and ClientTopicAliasMax).
- Servers can communicate what features it supports in ConnAckProperties.
- More: message expiration (OutgoingMessageProperties), Receive Maximums and Maximum Packet Sizes (ConnectProperties and ConnAckProperties), and a Will Delay interval (WillProperties) are all supported.
Property List
The following is the full list of the properties of the component with short descriptions. Click on the links for further details.
CleanSession | Determines whether a clean session is used once connected. |
ClientId | A string that uniquely identifies this instance of the component to the server. |
Connected | Triggers a connection or disconnection. |
Firewall | A set of properties related to firewall access. |
IncomingMessages | Collection of incoming messages with QoS > 0 that have not been fully acknowledged. |
KeepAliveInterval | The maximum period of inactivity the component will allow before sending a keep-alive packet. |
LocalHost | The name of the local host or user-assigned IP interface through which connections are initiated or accepted. |
LocalPort | The TCP port in the local host where the component binds. |
OutgoingMessages | Collection of outgoing messages with QoS > 0 that have not been fully acknowledged. |
Password | A password if authentication is to be used. |
ReadyToSend | Indicates whether the component is ready to send data. |
RemoteHost | The address of the remote host. Domain names are resolved to IP addresses. |
RemotePort | The port of the MQTT server (default is 1883). The default port for SSL is 8883. |
SSLAcceptServerCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertEncoded | The certificate (PEM/base64 encoded). |
SSLCertStore | The name of the certificate store for the client certificate. |
SSLCertStorePassword | If 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. |
SSLCertStoreType | The type of certificate store for this certificate. |
SSLCertSubject | The subject of the certificate used for client authentication. |
SSLEnabled | Whether TLS/SSL is enabled. |
SSLServerCertEncoded | The certificate (PEM/base64 encoded). |
Timeout | A timeout for the component. |
User | A username if authentication is to be used. |
Version | The MQTT protocol version that the component will conform to. |
WillMessage | The message that the server should publish in the event of an ungraceful disconnection. |
WillTopic | The 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 component with short descriptions. Click on the links for further details.
Config | Sets or retrieves a configuration setting. |
Connect | Connects to the remote host. |
Disconnect | Disconnects from the remote host. |
DoEvents | Processes events from the internal message queue. |
Interrupt | Interrupt the current action and disconnects from the remote host. |
PublishData | Publishes a message with a raw data payload. |
PublishMessage | Publishes a message with a string payload. |
Reset | Reset the component. |
RestoreSession | Restores session state data. |
SaveSession | Saves session state data. |
Subscribe | Subscribes the component to one or more topic filters. |
Unsubscribe | Unsubscribes the component from one or more topic filters. |
Event List
The following is the full list of the events fired by the component with short descriptions. Click on the links for further details.
Connected | Fired immediately after a connection completes (or fails). |
ConnectionStatus | Fired to indicate changes in connection state. |
Disconnected | Fired when a connection is closed. |
Error | Information about errors during data delivery. |
Log | Fires once for each log message. |
MessageAck | Fired when an incoming or outgoing message has completed all acknowledgment steps. |
MessageIn | Fired when an incoming message has been received and/or fully acknowledged. |
MessageOut | Fired when an outgoing message has been sent and/or fully acknowledged. |
ReadyToSend | Fired when the component is ready to send data. |
SSLServerAuthentication | Fired after the server presents its certificate to the client. |
SSLStatus | Shows the progress of the secure connection. |
Subscribed | Fires for each topic filter subscription the server acknowledges. |
Unsubscribed | Fires when the server has acknowledged an unsubscribe request. |
Configuration Settings
The following is a list of configuration settings for the component with short descriptions. Click on the links for further details.
AutoReconnect | Whether to automatically attempt to reconnect in the event of a connection error. |
ClientTopicAliasMax | The maximum value the client will accept for a topic alias sent by the server. |
ConnAckProperties | JSON string containing the properties returned in the CONNACK packet. |
ConnectionTimeout | How long to wait for a connection attempt to succeed. |
ConnectProperties | JSON string specifying properties to be included in the CONNECT packet. |
DisconnectProperties | JSON string containing DISCONNECT packet properties. |
DisconnectReasonCode | Code describing the reason the client or server closed the connection. |
Duplicate | Whether to set the Duplicate flag when publishing a message. |
IncomingUserPropCount | The 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. |
LogLevel | The level of detail that is logged. |
OutgoingMessageProperties | JSON string specifying properties to be included in the PUBLISH packet. |
OutgoingPacketId | The packet Id of the last message published. |
OutgoingUserPropCount | Controls 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. |
RepublishInterval | How many seconds to wait before republishing unacknowledged messages. |
ResponseTopic | Topic name for a response message. |
Retain | Whether to set the Retain flag when publishing a message. |
SendCustomPacket | Sends a packet constructed using the supplied hex byte string. |
ServerTopicAliasMax | The highest value that the Server will accept as a Topic Alias sent by the Client. |
SessionExpInterval | The length of time in seconds the client and server should store session state data after the connection is closed. |
SessionPresent | When connecting with CleanSession disabled, indicates whether the server actually had any previous session data stored. |
SessionStateFile | File to use for saving and restoring session data. |
SubscriptionIdentifier | A numeric subscription identifier included in SUBSCRIBE packet which will be returned with messages delivered for that subscription. |
TopicAlias | Value that is used to identify the Topic instead of using the Topic Name in order to reduce packet size. |
TopicDelimiter | The string to use as a delimiter in a topic filter list string. |
TopicNLArray | List of No Local option flags for subscription topic filters. |
TopicQOSArray | Comma-separated list of topic filter QoS values to use when subscribing. |
TopicRAPArray | List of Retain As Published option flags for subscription topic filters. |
TopicRHArray | List of Retain Handling option values for subscription topic filters. |
WillProperties | JSON string specifying will properties to be included in the CONNECT packet. |
WillQOS | The QoS value to use for the Will message. |
WillRetain | Whether the server should retain the Will message after publishing it. |
CloseStreamAfterTransfer | If true, the component will close the upload or download stream after the transfer. |
ConnectionTimeout | Sets a separate timeout value for establishing a connection. |
FirewallAutoDetect | Tells the component whether or not to automatically detect and use firewall system settings, if available. |
FirewallHost | Name or IP address of firewall (optional). |
FirewallPassword | Password to be used if authentication is to be used when connecting through the firewall. |
FirewallPort | The TCP port for the FirewallHost;. |
FirewallType | Determines the type of firewall to connect through. |
FirewallUser | A user name if authentication is to be used connecting through a firewall. |
KeepAliveInterval | The retry interval, in milliseconds, to be used when a TCP keep-alive packet is sent and no response is received. |
KeepAliveTime | The inactivity time in milliseconds before a TCP keep-alive packet is sent. |
Linger | When set to True, connections are terminated gracefully. |
LingerTime | Time in seconds to have the connection linger. |
LocalHost | The name of the local host through which connections are initiated or accepted. |
LocalPort | The port in the local host where the component binds. |
MaxLineLength | The maximum amount of data to accumulate when no EOL is found. |
MaxTransferRate | The transfer rate limit in bytes per second. |
ProxyExceptionsList | A semicolon separated list of hosts and IPs to bypass when using a proxy. |
TCPKeepAlive | Determines whether or not the keep alive socket option is enabled. |
TcpNoDelay | Whether or not to delay when sending packets. |
UseIPv6 | Whether to use IPv6. |
LogSSLPackets | Controls whether SSL packets are logged when using the internal security API. |
OpenSSLCADir | The path to a directory containing CA certificates. |
OpenSSLCAFile | Name of the file containing the list of CA's trusted by your application. |
OpenSSLCipherList | A string that controls the ciphers to be used by SSL. |
OpenSSLPrngSeedData | The data to seed the pseudo random number generator (PRNG). |
ReuseSSLSession | Determines if the SSL session is reused. |
SSLCACerts | A newline separated list of CA certificate to use during SSL client authentication. |
SSLCheckCRL | Whether to check the Certificate Revocation List for the server certificate. |
SSLCipherStrength | The minimum cipher strength used for bulk encryption. |
SSLEnabledCipherSuites | The cipher suite to be used in an SSL negotiation. |
SSLEnabledProtocols | Used to enable/disable the supported security protocols. |
SSLEnableRenegotiation | Whether the renegotiation_info SSL extension is supported. |
SSLIncludeCertChain | Whether the entire certificate chain is included in the SSLServerAuthentication event. |
SSLNegotiatedCipher | Returns the negotiated ciphersuite. |
SSLNegotiatedCipherStrength | Returns the negotiated ciphersuite strength. |
SSLNegotiatedCipherSuite | Returns the negotiated ciphersuite. |
SSLNegotiatedKeyExchange | Returns the negotiated key exchange algorithm. |
SSLNegotiatedKeyExchangeStrength | Returns the negotiated key exchange algorithm strength. |
SSLNegotiatedVersion | Returns the negotiated protocol version. |
SSLProvider | The name of the security provider to use. |
SSLSecurityFlags | Flags that control certificate verification. |
SSLServerCACerts | A newline separated list of CA certificate to use during SSL server certificate validation. |
TLS12SignatureAlgorithms | Defines the allowed TLS 1.2 signature algorithms when UseInternalSecurityAPI is True. |
TLS12SupportedGroups | The supported groups for ECC. |
TLS13KeyShareGroups | The groups for which to pregenerate key shares. |
TLS13SignatureAlgorithms | The allowed certificate signature algorithms. |
TLS13SupportedGroups | The supported groups for (EC)DHE key exchange. |
AbsoluteTimeout | Determines whether timeouts are inactivity timeouts or absolute timeouts. |
FirewallData | Used to send extra data to the firewall. |
InBufferSize | The size in bytes of the incoming queue of the socket. |
OutBufferSize | The size in bytes of the outgoing queue of the socket. |
BuildInfo | Information about the product's build. |
CodePage | The system code page used for Unicode to Multibyte translations. |
LicenseInfo | Information about the current license. |
UseInternalSecurityAPI | Tells the component whether or not to use the system security libraries or an internal implementation. |