-
- All Implemented Interfaces:
-
org.eclipse.paho.client.mqttv3.IMqttAsyncClient
public class MqttAsyncClient implements IMqttAsyncClient
Lightweight client for talking to an MQTT server using non-blocking methods that allow an operation to run in the background.
This class implements the non-blocking IMqttAsyncClient client interface allowing applications to initiate MQTT actions and then carry on working while the MQTT action completes on a background thread. This implementation is compatible with all Java SE runtimes from 1.4.2 and up.
An application can connect to an MQTT server using:
- A plain TCP socket
- A secure SSL/TLS socket
To enable messages to be delivered even across network and client restarts messages need to be safely stored until the message has been delivered at the requested quality of service. A pluggable persistence mechanism is provided to store the messages.
By default MqttDefaultFilePersistence is used to store messages to a file. If persistence is set to null then messages are stored in memory and hence can be lost if the client, Java runtime or device shuts down.
If connecting with setCleanSession set to true it is safe to use memory persistence as all state is cleared when a client disconnects. If connecting with cleanSession set to false in order to provide reliable message delivery then a persistent message store such as the default one should be used.
The message store interface is pluggable. Different stores can be used by implementing the MqttClientPersistence interface and passing it to the clients constructor.
-
-
Constructor Summary
Constructors Constructor Description MqttAsyncClient(String serverURI, String clientId, String mqttVersion)Create an MqttAsyncClient that is used to communicate with an MQTT server. MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, MqttPingSender mqttPingSender, ILogger logger)MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, int maxInflightMsgs, MqttPingSender pingSender, ILogger logger, IPahoEvents pahoEvents, IExperimentsConfig experimentsConfig)MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, int maxInflightMsgs, MqttPingSender pingSender, ILogger logger, IPahoEvents pahoEvents, IExperimentsConfig experimentsConfig, List<MqttInterceptor> mqttInterceptorList)Create an MqttAsyncClient that is used to communicate with an MQTT server.
-
Method Summary
Modifier and Type Method Description StringgetClientId()Returns the client ID used by this client. voidsetClientId(String clientId)StringgetMqttVersion()Returns the mqtt version used by this client. StringgetServerURI()Returns the address of the server used by this client. voidsetServerURI(String serverURI)IMqttTokenconnect(Object userContext, IMqttActionListener callback)Connects to an MQTT server using the default options. IMqttTokenconnect()Connects to an MQTT server using the default options. IMqttTokenconnect(MqttConnectOptions options)Connects to an MQTT server using the provided connect options. IMqttTokenconnect(MqttConnectOptions options, Object userContext, IMqttActionListener callback)Connects to an MQTT server using the specified options. IMqttTokendisconnect(Object userContext, IMqttActionListener callback)Disconnects from the server. IMqttTokendisconnect()Disconnects from the server. IMqttTokendisconnect(long quiesceTimeout)Disconnects from the server. IMqttTokendisconnect(long quiesceTimeout, Object userContext, IMqttActionListener callback)Disconnects from the server. voiddisconnectForcibly()Disconnects from the server forcibly to reset all the states. voiddisconnectForcibly(long disconnectTimeout)Disconnects from the server forcibly to reset all the states. voiddisconnectForcibly(long quiesceTimeout, long disconnectTimeout)Disconnects from the server forcibly to reset all the states. booleanisConnected()Determines if this client is currently connected to the server. booleanisConnecting()booleanisDisconnecting()booleanisDisconnected()IMqttTokencheckPing(Object userContext, IMqttActionListener callback)voidcheckActivity()IMqttTokensubscribe(String topicFilter, int qos, Object userContext, IMqttActionListener callback)Subscribe to a topic, which may include wildcards. IMqttTokensubscribe(String topicFilter, int qos)Subscribe to a topic, which may include wildcards. IMqttTokensubscribe(Array<String> topicFilters, Array<int> qos)Subscribe to multiple topics, each of which may include wildcards. IMqttTokensubscribe(Array<String> topicFilters, Array<int> qos, Object userContext, IMqttActionListener callback)Subscribes to multiple topics, each of which may include wildcards. IMqttTokenunsubscribe(String topicFilter, Object userContext, IMqttActionListener callback)Requests the server unsubscribe the client from a topics. IMqttTokenunsubscribe(String topicFilter)Requests the server unsubscribe the client from a topic. IMqttTokenunsubscribe(Array<String> topicFilters)Requests the server unsubscribe the client from one or more topics. IMqttTokenunsubscribe(Array<String> topicFilters, Object userContext, IMqttActionListener callback)Requests the server unsubscribe the client from one or more topics. voidsetCallback(MqttCallback callback)Sets a callback listener to use for events that happen asynchronously. static StringgenerateClientId()Returns a randomly generated client identifier based on the the fixed prefix (paho-) and the system time. Array<IMqttDeliveryToken>getPendingDeliveryTokens()Returns the delivery tokens for any outstanding publish operations. IMqttDeliveryTokenpublish(String topic, Array<byte> payload, int qos, boolean retained, Object userContext, IMqttActionListener callback)Publishes a message to a topic on the server. IMqttDeliveryTokenpublish(String topic, Array<byte> payload, int qos, boolean retained)Publishes a message to a topic on the server. IMqttDeliveryTokenpublish(String topic, MqttMessage message)Publishes a message to a topic on the server. IMqttDeliveryTokenpublish(String topic, MqttMessage message, Object userContext, IMqttActionListener callback)Publishes a message to a topic on the server. voidclose()Close the client Releases all resource associated with the client. intgetInflightMessages()intgetMaxflightMessages()voidpingReq(IMqttActionListener listener)longgetFastReconnectCheckStartTime()longgetLastOutboundActivity()longgetLastInboundActivity()voidsetBufferOpts(DisconnectedBufferOptions bufferOpts)Sets the DisconnectedBufferOptions for this client intgetBufferedMessageCount()Returns the number of messages in the Disconnected Message Buffer MqttMessagegetBufferedMessage(int bufferIndex)Returns a message from the Disconnected Message Buffer voiddeleteBufferedMessage(int bufferIndex)Deletes a message from the Disconnected Message Buffer -
-
Constructor Detail
-
MqttAsyncClient
MqttAsyncClient(String serverURI, String clientId, String mqttVersion)
Create an MqttAsyncClient that is used to communicate with an MQTT server.- Parameters:
serverURI- the address of the server to connect to, specified as a URI.clientId- a client identifier that is unique on the server being connected to
-
MqttAsyncClient
MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, MqttPingSender mqttPingSender, ILogger logger)
-
MqttAsyncClient
MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, int maxInflightMsgs, MqttPingSender pingSender, ILogger logger, IPahoEvents pahoEvents, IExperimentsConfig experimentsConfig)
-
MqttAsyncClient
MqttAsyncClient(String serverURI, String clientId, String mqttVersion, MqttClientPersistence persistence, int maxInflightMsgs, MqttPingSender pingSender, ILogger logger, IPahoEvents pahoEvents, IExperimentsConfig experimentsConfig, List<MqttInterceptor> mqttInterceptorList)
Create an MqttAsyncClient that is used to communicate with an MQTT server.- Parameters:
serverURI- the address of the server to connect to, specified as a URI.clientId- a client identifier that is unique on the server being connected topersistence- the persistence class to use to store in-flight message.
-
-
Method Detail
-
getClientId
String getClientId()
Returns the client ID used by this client.
All clients connected to the same server or server farm must have a unique ID.
-
setClientId
void setClientId(String clientId)
-
getMqttVersion
String getMqttVersion()
Returns the mqtt version used by this client.
-
getServerURI
String getServerURI()
Returns the address of the server used by this client.
The format of the returned String is the same as that used on the constructor.
-
setServerURI
void setServerURI(String serverURI)
-
connect
IMqttToken connect(Object userContext, IMqttActionListener callback)
Connects to an MQTT server using the default options.
The default options are specified in MqttConnectOptions class.
- Parameters:
userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when the connect completes.
-
connect
IMqttToken connect()
Connects to an MQTT server using the default options.
The default options are specified in MqttConnectOptions class.
-
connect
IMqttToken connect(MqttConnectOptions options)
Connects to an MQTT server using the provided connect options.
The connection will be established using the options specified in the MqttConnectOptions parameter.
- Parameters:
options- a set of connection parameters that override the defaults.
-
connect
IMqttToken connect(MqttConnectOptions options, Object userContext, IMqttActionListener callback)
Connects to an MQTT server using the specified options.
The server to connect to is specified on the constructor. It is recommended to call setCallback prior to connecting in order that messages destined for the client can be accepted as soon as the client is connected.
The method returns control before the connect completes. Completion can be tracked by:
- Waiting on the returned token waitForCompletion or
- Passing in a callback IMqttActionListener
- Parameters:
options- a set of connection parameters that override the defaults.userContext- optional object for used to pass context to the callback.callback- optional listener that will be notified when the connect completes.
-
disconnect
IMqttToken disconnect(Object userContext, IMqttActionListener callback)
Disconnects from the server.
An attempt is made to quiesce the client allowing outstanding work to complete before disconnecting. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting. This method must not be called from inside MqttCallback methods.
- Parameters:
userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when the disconnect completes.
-
disconnect
IMqttToken disconnect()
Disconnects from the server.
An attempt is made to quiesce the client allowing outstanding work to complete before disconnecting. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting. This method must not be called from inside MqttCallback methods.
-
disconnect
IMqttToken disconnect(long quiesceTimeout)
Disconnects from the server.
An attempt is made to quiesce the client allowing outstanding work to complete before disconnecting. It will wait for a maximum of the specified quiesce time for work to complete before disconnecting. This method must not be called from inside MqttCallback methods.
- Parameters:
quiesceTimeout- the amount of time in milliseconds to allow for existing work to finish before disconnecting.
-
disconnect
IMqttToken disconnect(long quiesceTimeout, Object userContext, IMqttActionListener callback)
Disconnects from the server.
The client will wait for MqttCallback methods to complete. It will then wait for up to the quiesce timeout to allow for work which has already been initiated to complete. For instance when a QoS 2 message has started flowing to the server but the QoS 2 flow has not completed.It prevents new messages being accepted and does not send any messages that have been accepted but not yet started delivery across the network to the server. When work has completed or after the quiesce timeout, the client will disconnect from the server. If the cleanSession flag was set to false and is set to false the next time a connection is made QoS 1 and 2 messages that were not previously delivered will be delivered.
This method must not be called from inside MqttCallback methods.
The method returns control before the disconnect completes. Completion can be tracked by:
- Waiting on the returned token waitForCompletion or
- Passing in a callback IMqttActionListener
- Parameters:
quiesceTimeout- the amount of time in milliseconds to allow for existing work to finish before disconnecting.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when the disconnect completes.
-
disconnectForcibly
void disconnectForcibly()
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting and wait for a maximum of 10 seconds for sending the disconnect packet to server.
-
disconnectForcibly
void disconnectForcibly(long disconnectTimeout)
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet. It will wait for a maximum of 30 seconds for work to quiesce before disconnecting.
- Parameters:
disconnectTimeout- the amount of time in milliseconds to allow send disconnect packet to server.
-
disconnectForcibly
void disconnectForcibly(long quiesceTimeout, long disconnectTimeout)
Disconnects from the server forcibly to reset all the states. Could be useful when disconnect attempt failed.
Because the client is able to establish the TCP/IP connection to a none MQTT server and it will certainly fail to send the disconnect packet.
- Parameters:
quiesceTimeout- the amount of time in milliseconds to allow for existing work to finish before disconnecting.disconnectTimeout- the amount of time in milliseconds to allow send disconnect packet to server.
-
isConnected
boolean isConnected()
Determines if this client is currently connected to the server.
-
isConnecting
boolean isConnecting()
-
isDisconnecting
boolean isDisconnecting()
-
isDisconnected
boolean isDisconnected()
-
checkPing
IMqttToken checkPing(Object userContext, IMqttActionListener callback)
-
checkActivity
void checkActivity()
-
subscribe
IMqttToken subscribe(String topicFilter, int qos, Object userContext, IMqttActionListener callback)
Subscribe to a topic, which may include wildcards.
- Parameters:
topicFilter- the topic to subscribe to, which can include wildcards.qos- the maximum quality of service at which to subscribe.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when subscribe has completed
-
subscribe
IMqttToken subscribe(String topicFilter, int qos)
Subscribe to a topic, which may include wildcards.
- Parameters:
topicFilter- the topic to subscribe to, which can include wildcards.qos- the maximum quality of service at which to subscribe.
-
subscribe
IMqttToken subscribe(Array<String> topicFilters, Array<int> qos)
Subscribe to multiple topics, each of which may include wildcards.
Provides an optimized way to subscribe to multiple topics compared to subscribing to each one individually.
- Parameters:
topicFilters- one or more topics to subscribe to, which can include wildcardsqos- the maximum quality of service at which to subscribe.
-
subscribe
IMqttToken subscribe(Array<String> topicFilters, Array<int> qos, Object userContext, IMqttActionListener callback)
Subscribes to multiple topics, each of which may include wildcards.
Provides an optimized way to subscribe to multiple topics compared to subscribing to each one individually.
The setCallback method should be called before this method, otherwise any received messages will be discarded.
If (@link MqttConnectOptions#setCleanSession(boolean)} was set to true when when connecting to the server then the subscription remains in place until either:
- The client disconnects
- An unsubscribe method is called to un-subscribe the topic
If (@link MqttConnectOptions#setCleanSession(boolean)} was set to false when connecting to the server then the subscription remains in place until either:
The "topic filter" string used when subscribing may contain special characters, which allow you to subscribe to multiple topics at once.
The topic level separator is used to introduce structure into the topic, and can therefore be specified within the topic for that purpose. The multi-level wildcard and single-level wildcard can be used for subscriptions, but they cannot be used within a topic by the publisher of a message.
The method returns control before the subscribe completes. Completion can be tracked by:
- Parameters:
topicFilters- one or more topics to subscribe to, which can include wildcardsqos- the maximum quality of service to subscribe each topic at.Messages published at a lower quality of service will be received at the published QoS.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when subscribe has completed
-
unsubscribe
IMqttToken unsubscribe(String topicFilter, Object userContext, IMqttActionListener callback)
Requests the server unsubscribe the client from a topics.
- Parameters:
topicFilter- the topic to unsubscribe from.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when unsubscribe has completed
-
unsubscribe
IMqttToken unsubscribe(String topicFilter)
Requests the server unsubscribe the client from a topic.
- Parameters:
topicFilter- the topic to unsubscribe from.
-
unsubscribe
IMqttToken unsubscribe(Array<String> topicFilters)
Requests the server unsubscribe the client from one or more topics.
- Parameters:
topicFilters- one or more topics to unsubscribe from.
-
unsubscribe
IMqttToken unsubscribe(Array<String> topicFilters, Object userContext, IMqttActionListener callback)
Requests the server unsubscribe the client from one or more topics.
Unsubcribing is the opposite of subscribing. When the server receives the unsubscribe request it looks to see if it can find a matching subscription for the client and then removes it. After this point the server will send no more messages to the client for this subscription.
The topic(s) specified on the unsubscribe must match the topic(s) specified in the original subscribe request for the unsubscribe to succeed
The method returns control before the unsubscribe completes. Completion can be tracked by:
- Waiting on the returned token waitForCompletion or
- Passing in a callback IMqttActionListener to this method
- Parameters:
topicFilters- one or more topics to unsubscribe from.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when unsubscribe has completed
-
setCallback
void setCallback(MqttCallback callback)
Sets a callback listener to use for events that happen asynchronously.
There are a number of events that the listener will be notified about. These include:
- A new message has arrived and is ready to be processed
- The connection to the server has been lost
- Delivery of a message to the server has completed
Other events that track the progress of an individual operation such as connect and subscribe can be tracked using the MqttToken returned from each non-blocking method or using setting a IMqttActionListener on the non-blocking method.
- Parameters:
callback- which will be invoked for certain asynchronous events
-
generateClientId
static String generateClientId()
Returns a randomly generated client identifier based on the the fixed prefix (paho-) and the system time.
When cleanSession is set to false, an application must ensure it uses the same client identifier when it reconnects to the server to resume state and maintain assured message delivery.
-
getPendingDeliveryTokens
Array<IMqttDeliveryToken> getPendingDeliveryTokens()
Returns the delivery tokens for any outstanding publish operations.
If a client has been restarted and there are messages that were in the process of being delivered when the client stopped this method returns a token for each in-flight message enabling the delivery to be tracked Alternately the deliveryComplete callback can be used to track the delivery of outstanding messages.
If a client connects with cleanSession true then there will be no delivery tokens as the cleanSession option deletes all earlier state. For state to be remembered the client must connect with cleanSession set to false
-
publish
IMqttDeliveryToken publish(String topic, Array<byte> payload, int qos, boolean retained, Object userContext, IMqttActionListener callback)
Publishes a message to a topic on the server.
A convenience method, which will create a new MqttMessage object with a byte array payload and the specified QoS, and then publish it.
- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".payload- the byte array to use as the payloadqos- the Quality of Service to deliver the message at.retained- whether or not this message should be retained by the server.userContext- optional object used to pass context to the callback.callback- optional listener that will be notified when message delivery hsa completed to the requested quality of service
-
publish
IMqttDeliveryToken publish(String topic, Array<byte> payload, int qos, boolean retained)
Publishes a message to a topic on the server.
A convenience method, which will create a new MqttMessage object with a byte array payload and the specified QoS, and then publish it.
- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".payload- the byte array to use as the payloadqos- the Quality of Service to deliver the message at.retained- whether or not this message should be retained by the server.
-
publish
IMqttDeliveryToken publish(String topic, MqttMessage message)
Publishes a message to a topic on the server. Takes an MqttMessage message and delivers it to the server at the requested quality of service.
- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".message- to deliver to the server
-
publish
IMqttDeliveryToken publish(String topic, MqttMessage message, Object userContext, IMqttActionListener callback)
Publishes a message to a topic on the server.
Once this method has returned cleanly, the message has been accepted for publication by the client and will be delivered on a background thread. In the event the connection fails or the client stops. Messages will be delivered to the requested quality of service once the connection is re-established to the server on condition that:
- The connection is re-established with the same clientID
- The original connection was made with (@link MqttConnectOptions#setCleanSession(boolean)} set to false
- The connection is re-established with (@link MqttConnectOptions#setCleanSession(boolean)} set to false
- Depending when the failure occurs QoS 0 messages may not be delivered.
When building an application, the design of the topic tree should take into account the following principles of topic name syntax and semantics:
- A topic must be at least one character long.
- Topic names are case sensitive. For example, ACCOUNTS and Accounts are two different topics.
- Topic names can include the space character. For example, Accounts payable is a valid topic.
- A leading "/" creates a distinct topic. For example, /finance is different from finance. /finance matches "+/+" and "/+", but not "+".
- Do not include the null character (Unicode \x0000) in any topic.
The following principles apply to the construction and content of a topic tree:
- The length is limited to 64k but within that there are no limits to the number of levels in a topic tree.
- There can be any number of root nodes; that is, there can be any number of topic trees.
The method returns control before the publish completes. Completion can be tracked by:
- Setting an setCallback where the deliveryComplete method will be called.
- Waiting on the returned token waitForCompletion or
- Passing in a callback IMqttActionListener to this method
- Parameters:
topic- to deliver the message to, for example "finance/stock/ibm".message- to deliver to the serveruserContext- optional object used to pass context to the callback.callback- optional listener that will be notified when message delivery has completed to the requested quality of service
-
close
void close()
Close the client Releases all resource associated with the client. After the client has been closed it cannot be reused. For instance attempts to connect will fail.
-
getInflightMessages
int getInflightMessages()
-
getMaxflightMessages
int getMaxflightMessages()
-
pingReq
void pingReq(IMqttActionListener listener)
-
getFastReconnectCheckStartTime
long getFastReconnectCheckStartTime()
-
getLastOutboundActivity
long getLastOutboundActivity()
-
getLastInboundActivity
long getLastInboundActivity()
-
setBufferOpts
void setBufferOpts(DisconnectedBufferOptions bufferOpts)
Sets the DisconnectedBufferOptions for this client
- Parameters:
bufferOpts- the DisconnectedBufferOptions
-
getBufferedMessageCount
int getBufferedMessageCount()
Returns the number of messages in the Disconnected Message Buffer
-
getBufferedMessage
MqttMessage getBufferedMessage(int bufferIndex)
Returns a message from the Disconnected Message Buffer
- Parameters:
bufferIndex- the index of the message to be retrieved.
-
deleteBufferedMessage
void deleteBufferedMessage(int bufferIndex)
Deletes a message from the Disconnected Message Buffer
- Parameters:
bufferIndex- the index of the message to be deleted.
-
-
-
-