IPWorks IoT 2020 Python Edition

Questions / Feedback?

MQTT Class

Properties   Methods   Events   Configuration Settings   Errors  

A lightweight, fully-featured MQTT client implementation.

Syntax

class ipworksiot.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 client_id 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 clean_session is True, check the SessionPresent configuration setting once connected to determine whether the server actually had any session state saved.

Refer to clean_session, save_session, and restore_session for more information about MQTT sessions and session state persistence; refer to will_topic, will_message, 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 on_message_in, and potentially also the on_message_ack, 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 publish_message and publish_data methods.

publish_message is used to publish a message with a string payload, while publish_data 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 publish_data and publish_message 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.

clean_sessionDetermines whether a clean session is used once connected.
client_idA string that uniquely identifies this instance of the class to the server.
connectedTriggers a connection or disconnection.
firewall_auto_detectThis property tells the class whether or not to automatically detect and use firewall system settings, if available.
firewall_typeThis property determines the type of firewall to connect through.
firewall_hostThis property contains the name or IP address of firewall (optional).
firewall_passwordThis property contains a password if authentication is to be used when connecting through the firewall.
firewall_portThis property contains the TCP port for the firewall Host .
firewall_userThis property contains a user name if authentication is to be used connecting through a firewall.
incoming_message_countThe number of records in the IncomingMessage arrays.
incoming_message_content_typeString describing the content of the message.
incoming_message_correlation_dataUsed by the sender of the request message to identify which request the response message is for when it is received.
incoming_message_duplicateWhether or not this message's Duplicate flag is set.
incoming_message_messageThis message's raw data payload.
incoming_message_message_exp_intervalThe lifetime of the message in seconds specified by the sender.
incoming_message_packet_idThis message's packet Id.
incoming_message_payload_format_indicatorIndicates whether the payload is unspecified bytes or UTF-8 Encoded character data.
incoming_message_qosThis message's QoS level.
incoming_message_response_topicString used as the topic name for a response message.
incoming_message_retainedWhether or not this message's Retain flag is set.
incoming_message_stateThis message's current state.
incoming_message_subscription_identifiersA comma separated list of any SubscriptionIdentifiers associated with any client subscription(s) that caused this message to be delivered.
incoming_message_topicThis message's topic.
incoming_message_topic_aliasAn integer used to identify the topic instead of the full topic filter in order to reduce the size of the publish packet.
keep_alive_intervalThe maximum period of inactivity the class will allow before sending a keep-alive packet.
local_hostThe name of the local host or user-assigned IP interface through which connections are initiated or accepted.
local_portThe TCP port in the local host where the class binds.
outgoing_message_countThe number of records in the OutgoingMessage arrays.
outgoing_message_content_typeString describing the content of the message.
outgoing_message_correlation_dataUsed by the sender of the request message to identify which request the response message is for when it is received.
outgoing_message_duplicateWhether or not this message's Duplicate flag is set.
outgoing_message_messageThis message's raw data payload.
outgoing_message_message_exp_intervalThe lifetime of the message in seconds specified by the sender.
outgoing_message_packet_idThis message's packet Id.
outgoing_message_payload_format_indicatorIndicates whether the payload is unspecified bytes or UTF-8 Encoded character data.
outgoing_message_qosThis message's QoS level.
outgoing_message_response_topicString used as the topic name for a response message.
outgoing_message_retainedWhether or not this message's Retain flag is set.
outgoing_message_stateThis message's current state.
outgoing_message_subscription_identifiersA comma separated list of any SubscriptionIdentifiers associated with any client subscription(s) that caused this message to be delivered.
outgoing_message_topicThis message's topic.
outgoing_message_topic_aliasAn 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.
ready_to_sendIndicates whether the class is ready to send data.
remote_hostThe address of the remote host. Domain names are resolved to IP addresses.
remote_portThe port of the MQTT server (default is 1883). The default port for SSL is 8883.
ssl_accept_server_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_encodedThe certificate (PEM/base64 encoded).
ssl_cert_storeThe name of the certificate store for the client certificate.
ssl_cert_store_passwordIf 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.
ssl_cert_store_typeThe type of certificate store for this certificate.
ssl_cert_subjectThe subject of the certificate used for client authentication.
ssl_enabledWhether TLS/SSL is enabled.
ssl_server_cert_encodedThe 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.
will_messageThe message that the server should publish in the event of an ungraceful disconnection.
will_topicThe 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.
do_eventsProcesses events from the internal message queue.
interruptInterrupt the current action and disconnects from the remote host.
publish_dataPublishes a message with a raw data payload.
publish_messagePublishes a message with a string payload.
resetReset the class.
restore_sessionRestores session state data.
save_sessionSaves 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.

on_connectedFired immediately after a connection completes (or fails).
on_connection_statusFired to indicate changes in connection state.
on_disconnectedFired when a connection is closed.
on_errorInformation about errors during data delivery.
on_logFires once for each log message.
on_message_ackFired when an incoming or outgoing message has completed all acknowledgment steps.
on_message_inFired when an incoming message has been received and/or fully acknowledged.
on_message_outFired when an outgoing message has been sent and/or fully acknowledged.
on_ready_to_sendFired when the class is ready to send data.
on_ssl_server_authenticationFired after the server presents its certificate to the client.
on_ssl_statusShows the progress of the secure connection.
on_subscribedFires for each topic filter subscription the server acknowledges.
on_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.
SSLCACertFilePathsThe paths to CA certificate files on Unix/Linux.
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.
SSLNegotiatedCipherReturns the negotiated ciphersuite.
SSLNegotiatedCipherStrengthReturns the negotiated ciphersuite strength.
SSLNegotiatedCipherSuiteReturns the negotiated ciphersuite.
SSLNegotiatedKeyExchangeReturns the negotiated key exchange algorithm.
SSLNegotiatedKeyExchangeStrengthReturns the negotiated key exchange algorithm strength.
SSLNegotiatedVersionReturns the negotiated protocol version.
SSLProviderThe name of the security provider to use.
SSLSecurityFlagsFlags that control certificate verification.
SSLServerCACertsA newline separated list of CA certificate to use during SSL server certificate validation.
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.
BuildInfoInformation about the product's build.
CodePageThe system code page used for Unicode to Multibyte translations.
LicenseInfoInformation about the current license.
ProcessIdleEventsWhether the class uses its internal event loop to process events when the main thread is idle.
SelectWaitMillisThe length of time in milliseconds the class will wait when DoEvents is called if there are no events to process.
UseInternalSecurityAPITells the class whether or not to use the system security libraries or an internal implementation.

Copyright (c) 2022 /n software inc. - All rights reserved.
IPWorks IoT 2020 Python Edition - Version 20.0 [Build 8265]