= Vert.x MQTT

== Using Vert.x MQTT

This component had officially released in the Vert.x stack, just following dependency to the _dependencies_ section
of your build descriptor:

* Maven (in your `pom.xml`):

[source,xml,subs="+attributes"]
----
<dependency>
   <groupId>io.vertx</groupId>
   <artifactId>vertx-mqtt</artifactId>
   <version>3.9.14</version>
</dependency>
----

* Gradle (in your `build.gradle` file):

[source,groovy,subs="+attributes"]
----
compile io.vertx:vertx-mqtt:3.9.14
----

= Vert.x MQTT server

This component provides a server which is able to handle connections, communication and messages exchange with remote
link:http://mqtt.org/[MQTT] clients. Its API provides a bunch of events related to raw protocol messages received by
clients and exposes some features in order to send messages to them.

It's not a fully featured MQTT broker but can be used for building something like that or for protocol translation.

WARNING: this module has the tech preview status, this means the API can change between versions.

== Getting Started

=== Handling client connection/disconnection

This example shows how it's possible to handle the connection request from a remote MQTT client. First, an
`link:../../yardoc/VertxMqtt/MqttServer.html[MqttServer]` instance is created and the `link:../../yardoc/VertxMqtt/MqttServer.html#endpoint_handler-instance_method[endpointHandler]` method is used to specify the handler called
when a remote client sends a CONNECT message for connecting to the server itself. The `link:../../yardoc/VertxMqtt/MqttEndpoint.html[MqttEndpoint]`
instance, provided as parameter to the handler, brings all main information related to the CONNECT message like client identifier,
username/password, "will" information, clean session flag, protocol version and the "keep alive" timeout.
Inside that handler, the _endpoint_ instance provides the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#accept-instance_method[accept]` method
for replying to the remote client with the corresponding CONNACK message : in this way, the connection is established.
Finally, the server is started using the `link:../../yardoc/VertxMqtt/MqttServer.html#listen-instance_method[listen]` method with
the default behavior (on localhost and default MQTT port 1883). The same method allows to specify an handler in order
to check if the server is started properly or not.

[source,ruby]
----
require 'vertx-mqtt/mqtt_server'

mqttServer = VertxMqtt::MqttServer.create(vertx)
mqttServer.endpoint_handler() { |endpoint|

  # shows main connect info
  puts "MQTT client [#{endpoint.client_identifier()}] request to connect, clean session = #{endpoint.clean_session?()}"

  if (endpoint.auth() != nil)
    puts "[username = #{endpoint.auth()['username']}, password = #{endpoint.auth()['password']}]"
  end
  if (endpoint.will() != nil)
    puts "[will topic = #{endpoint.will()['willTopic']} msg = #{Java::JavaLang::String.new(endpoint.will()['willMessageBytes'])} QoS = #{endpoint.will()['willQos']} isRetain = #{endpoint.will()['illRetain']}]"
  end

  puts "[keep alive timeout = #{endpoint.keep_alive_time_seconds()}]"

  # accept connection from the remote client
  endpoint.accept(false)

}.listen() { |ar_err,ar|

  if (ar_err == nil)

    puts "MQTT server is listening on port #{ar.actual_port()}"
  else

    puts "Error on starting the server"
    ar_err.print_stack_trace()
  end
}

----

The same _endpoint_ instance provides the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#disconnect_handler-instance_method[disconnectHandler]`
for specifying the handler called when the remote client sends a DISCONNECT message in order to disconnect from the server;
this handler takes no parameters.

[source,ruby]
----

# handling disconnect message
endpoint.disconnect_handler() { |v|

  puts "Received disconnect from client"
}

----

=== Handling client connection/disconnection with SSL/TLS support

The server has the support for accepting connection requests through the SSL/TLS protocol for authentication and encryption.
In order to do that, the `link:../dataobjects.html#MqttServerOptions[MqttServerOptions]` class provides the `link:../dataobjects.html#MqttServerOptions#set_ssl-instance_method[ssl]` method
for setting the usage of SSL/TLS (passing 'true' as value) and some other useful methods for providing server certificate and
related private key (as Java key store reference, PEM or PFX format). In the following example, the
`link:../dataobjects.html#MqttServerOptions#set_key_cert_options-instance_method[keyCertOptions]` method is used in order to
pass the certificates in PEM format. This method requires an instance of the possible implementations of the
`link:unavailable[KeyCertOptions]` interface and in this case the `link:../dataobjects.html#PemKeyCertOptions[PemKeyCertOptions]` class
is used in order to provide the path for the server certificate and the private key with the correspondent
`link:../dataobjects.html#PemKeyCertOptions#set_cert_path-instance_method[certPath]` and
`link:../dataobjects.html#PemKeyCertOptions#set_key_path-instance_method[keyPath]` methods.
The MQTT server is started passing the Vert.x instance as usual and the above MQTT options instance to the creation method.

[source,ruby]
----
require 'vertx-mqtt/mqtt_server'

options = {
  'port' => 8883,
  'keyCertOptions' => {
    'keyPath' => "./src/test/resources/tls/server-key.pem",
    'certPath' => "./src/test/resources/tls/server-cert.pem"
  },
  'ssl' => true
}

mqttServer = VertxMqtt::MqttServer.create(vertx, options)
mqttServer.endpoint_handler() { |endpoint|

  # shows main connect info
  puts "MQTT client [#{endpoint.client_identifier()}] request to connect, clean session = #{endpoint.clean_session?()}"

  if (endpoint.auth() != nil)
    puts "[username = #{endpoint.auth()['username']}, password = #{endpoint.auth()['password']}]"
  end
  if (endpoint.will() != nil)
    puts "[will topic = #{endpoint.will()['willTopic']} msg = #{Java::JavaLang::String.new(endpoint.will()['willMessageBytes'])} QoS = #{endpoint.will()['willQos']} isRetain = #{endpoint.will()['illRetain']}]"
  end

  puts "[keep alive timeout = #{endpoint.keep_alive_time_seconds()}]"

  # accept connection from the remote client
  endpoint.accept(false)

}.listen() { |ar_err,ar|

  if (ar_err == nil)

    puts "MQTT server is listening on port #{ar.actual_port()}"
  else

    puts "Error on starting the server"
    ar_err.print_stack_trace()
  end
}

----

All the other stuff related to handle endpoint connection and related disconnection is managed in the same way without SSL/TLS support.

=== Handling client subscription/unsubscription request

After a connection is established between client and server, the client can send a subscription request for a topic
using the SUBSCRIBE message. The `link:../../yardoc/VertxMqtt/MqttEndpoint.html[MqttEndpoint]` interface allows to specify an handler for the
incoming subscription request using the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#subscribe_handler-instance_method[subscribeHandler]` method.
Such handler receives an instance of the `link:../../yardoc/VertxMqtt/MqttSubscribeMessage.html[MqttSubscribeMessage]` interface which brings
the list of topics with related QoS levels as desired by the client.
Finally, the endpoint instance provides the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#subscribe_acknowledge-instance_method[subscribeAcknowledge]` method
for replying to the client with the related SUBACK message containing the granted QoS levels.

[source,ruby]
----

# handling requests for subscriptions
endpoint.subscribe_handler() { |subscribe|

  grantedQosLevels = Array.new
  subscribe.topic_subscriptions().each do |s|
    puts "Subscription for #{s.topic_name()} with QoS #{s.quality_of_service()}"
    grantedQosLevels.push(s.quality_of_service())
  end
  # ack the subscriptions request
  endpoint.subscribe_acknowledge(subscribe.message_id(), grantedQosLevels)

}

----

In the same way, it's possible to use the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#unsubscribe_handler-instance_method[unsubscribeHandler]` method
on the endpoint in order to specify the handler called when the client sends an UNSUBSCRIBE message. This handler receives
an instance of the `link:../../yardoc/VertxMqtt/MqttUnsubscribeMessage.html[MqttUnsubscribeMessage]` interface as parameter with the list of topics to unsubscribe.
Finally, the endpoint instance provides the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#unsubscribe_acknowledge-instance_method[unsubscribeAcknowledge]` method
for replying to the client with the related UNSUBACK message.

[source,ruby]
----

# handling requests for unsubscriptions
endpoint.unsubscribe_handler() { |unsubscribe|

  unsubscribe.topics().each do |t|
    puts "Unsubscription for #{t}"
  end
  # ack the subscriptions request
  endpoint.unsubscribe_acknowledge(unsubscribe.message_id())
}

----

=== Handling client published message

In order to handle incoming messages published by the remote client, the `link:../../yardoc/VertxMqtt/MqttEndpoint.html[MqttEndpoint]` interface provides
the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_handler-instance_method[publishHandler]` method for specifying the handler called
when the client sends a PUBLISH message. This handler receives an instance of the `link:../../yardoc/VertxMqtt/MqttPublishMessage.html[MqttPublishMessage]`
interface as parameter with the payload, the QoS level, the duplicate and retain flags.

If the QoS level is 0 (AT_MOST_ONCE), there is no need from the endpoint to reply the client.

If the QoS level is 1 (AT_LEAST_ONCE), the endpoind needs to reply with a PUBACK message using the
available `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_acknowledge-instance_method[publishAcknowledge]` method.

If the QoS level is 2 (EXACTLY_ONCE), the endpoint needs to reply with a PUBREC message using the
available `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_received-instance_method[publishReceived]` method; in this case the same endpoint should handle
the PUBREL message received from the client as well (the remote client sends it after receiving the PUBREC from the endpoint)
and it can do that specifying the handler through the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_release_handler-instance_method[publishReleaseHandler]` method.
In order to close the QoS level 2 delivery, the endpoint can use the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_complete-instance_method[publishComplete]` method
for sending the PUBCOMP message to the client.

[source,ruby]
----

# handling incoming published messages
endpoint.publish_handler() { |message|

  puts "Just received message [#{message.payload().to_string(Java::JavaNioCharset::Charset.default_charset())}] with QoS [#{message.qos_level()}]"

  if (message.qos_level() == :AT_LEAST_ONCE)
    endpoint.publish_acknowledge(message.message_id())
  elsif (message.qos_level() == :EXACTLY_ONCE)
    endpoint.publish_received(message.message_id())
  end

}.publish_release_handler() { |messageId|

  endpoint.publish_complete(messageId)
}

----

=== Publish message to the client

The endpoint can publish a message to the remote client (sending a PUBLISH message) using the
`link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish-instance_method[publish]` method
which takes the following input parameters : the topic to publish, the payload, the QoS level, the duplicate and retain flags.

If the QoS level is 0 (AT_MOST_ONCE), the endpoint won't receiving any feedback from the client.

If the QoS level is 1 (AT_LEAST_ONCE), the endpoint needs to handle the PUBACK message received from the client
in order to receive final acknowledge of delivery. It's possible using the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_acknowledge_handler-instance_method[publishAcknowledgeHandler]` method
specifying such an handler.

If the QoS level is 2 (EXACTLY_ONCE), the endpoint needs to handle the PUBREC message received from the client.
The `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_received_handler-instance_method[publishReceivedHandler]` method allows to specify
the handler for that. Inside that handler, the endpoint can use the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_release-instance_method[publishRelease]` method
for replying to the client with the PUBREL message. The last step is to handle the PUBCOMP message received from the client
as final acknowledge for the published message; it's possible using the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#publish_completion_handler-instance_method[publishCompletionHandler]`
for specifying the handler called when the final PUBCOMP message is received.

[source,ruby]
----
require 'vertx/buffer'

# just as example, publish a message with QoS level 2
endpoint.publish("my_topic", Vertx::Buffer.buffer("Hello from the Vert.x MQTT server"), :EXACTLY_ONCE, false, false)

# specifing handlers for handling QoS 1 and 2
endpoint.publish_acknowledge_handler() { |messageId|

  puts "Received ack for message = #{messageId}"

}.publish_received_handler() { |messageId|

  endpoint.publish_release(messageId)

}.publish_completion_handler() { |messageId|

  puts "Received ack for message = #{messageId}"
}

----

=== Be notified by client keep alive

The underlying MQTT keep alive mechanism is handled by the server internally. When the CONNECT message is received,
the server takes care of the keep alive timeout specified inside that message in order to check if the client doesn't
send messages in such timeout. At same time, for every PINGREQ received, the server replies with the related PINGRESP.

Even if there is no need for the high level application to handle that, the `link:../../yardoc/VertxMqtt/MqttEndpoint.html[MqttEndpoint]` interface
provides the `link:../../yardoc/VertxMqtt/MqttEndpoint.html#ping_handler-instance_method[pingHandler]` method for specifying an handler
called when a PINGREQ message is received from the client. It's just a notification to the application that the client
isn't sending meaningful messages but only pings for keeping alive; in any case the PINGRESP is automatically sent
by the server internally as described above.

[source,ruby]
----

# handling ping from client
endpoint.ping_handler() { |v|

  puts "Ping received from client"
}

----

=== Closing the server

The `link:../../yardoc/VertxMqtt/MqttServer.html[MqttServer]` interface provides the `link:../../yardoc/VertxMqtt/MqttServer.html#close-instance_method[close]` method
that can be used for closing the server; it stops to listen for incoming connections and closes all the active connections
with remote clients. This method is asynchronous and one overload provides the possibility to specify a complention handler
that will be called when the server is really closed.

[source,ruby]
----

mqttServer.close() { |v_err,v|

  puts "MQTT server closed"
}

----

=== Automatic clean-up in verticles

If you’re creating MQTT servers from inside verticles, those servers will be automatically closed when the verticle is undeployed.

=== Scaling : sharing MQTT servers

The handlers related to the MQTT server are always executed in the same event loop thread. It means that on a system with
more cores, only one instance is deployed so only one core is used. In order to use more cores, it's possible to deploy
more instances of the MQTT server.

It's possible to do that programmatically:

[source,ruby]
----
require 'vertx-mqtt/mqtt_server'

(0...10).each do |i|

  mqttServer = VertxMqtt::MqttServer.create(vertx)
  mqttServer.endpoint_handler() { |endpoint|
    # handling endpoint
  }.listen() { |ar_err,ar|

    # handling start listening
  }

end

----

or using a verticle specifying the number of instances:

[source,ruby]
----

options = {
  'instances' => 10
}
vertx.deploy_verticle("com.mycompany.MyVerticle", options)

----

What's really happen is that even only MQTT server is deployed but as incoming connections arrive, Vert.x distributes
them in a round-robin fashion to any of the connect handlers executed on different cores.

= Vert.x MQTT client

This component provides an link:http://mqtt.org/[MQTT] client which is compliant with the 3.1.1 spec. Its API provides a bunch of methods
for connecting/disconnecting to a broker, publishing messages (with all three different levels of QoS) and subscribing to topics.

WARNING: this module has the tech preview status, this means the API can change between versions.

== Getting started

=== Connect/Disconnect
The client gives you opportunity to connect to a server and disconnect from it.
Also, you could specify things like the host and port of a server you would like
to connect to passing instance of `link:../dataobjects.html#MqttClientOptions[MqttClientOptions]` as a param through constructor.

This example shows how you could connect to a server and disconnect from it using Vert.x MQTT client
and calling `link:../../yardoc/VertxMqtt/MqttClient.html#connect-instance_method[connect]` and `link:../../yardoc/VertxMqtt/MqttClient.html#disconnect-instance_method[disconnect]` methods.
[source,ruby]
----
require 'vertx-mqtt/mqtt_client'
client = VertxMqtt::MqttClient.create(vertx)

client.connect(1883, "mqtt.eclipse.org") { |s_err,s|
  client.disconnect()
}

----
NOTE: default address of server provided by `link:../dataobjects.html#MqttClientOptions[MqttClientOptions]` is localhost:1883 and localhost:8883 if you are using SSL/TSL.

=== Subscribe to a topic

Now, lest go deeper and take look at this example:

[source,ruby]
----
client.publish_handler() { |s|
  puts "There are new message in topic: #{s.topic_name()}"
  puts "Content(as string) of the message: #{s.payload().to_string()}"
  puts "QoS: #{s.qos_level()}"
}.subscribe("rpi2/temp", 2)

----

Here we have the example of usage of `link:../../yardoc/VertxMqtt/MqttClient.html#subscribe-instance_method[subscribe]` method. In order to receive messages from rpi2/temp topic we call `link:../../yardoc/VertxMqtt/MqttClient.html#subscribe-instance_method[subscribe]` method.
Although, to handle received messages from server you need to provide a handler, which will be called each time you have a new messages in the topics you subscribe on.
As this example shows, handler could be provided via `link:../../yardoc/VertxMqtt/MqttClient.html#publish_handler-instance_method[publishHandler]` method.

=== Publishing message to a topic

If you would like to publish some message into topic then `link:../../yardoc/VertxMqtt/MqttClient.html#publish-instance_method[publish]` should be called.
Let's take a look at the example:
[source,ruby]
----
require 'vertx/buffer'
client.publish("temperature", Vertx::Buffer.buffer("hello"), :AT_LEAST_ONCE, false, false)

----
In the example we send message to topic with name "temperature".

=== Keep connection with server alive
In order to keep connection with server you should time to time send something to server otherwise server will close the connection.
The right way to keep connection alive is a `link:../../yardoc/VertxMqtt/MqttClient.html#ping-instance_method[ping]` method.

IMPORTANT: by default you client keep connections with server automatically. That means that you don't need to call `link:../../yardoc/VertxMqtt/MqttClient.html#ping-instance_method[ping]` in order to keep connections with server.
The `link:../../yardoc/VertxMqtt/MqttClient.html[MqttClient]` will do it for you.

If you want to disable this feature then you should call `link:../dataobjects.html#MqttClientOptions#set_auto_keep_alive-instance_method[autoKeepAlive]` with `false` as argument:
[source,ruby]
----
options['autoKeepAlive'] = false

----

=== Be notified when
* publish is completed
+
You could provide handler by calling `link:../../yardoc/VertxMqtt/MqttClient.html#publish_completion_handler-instance_method[publishCompletionHandler]`. The handler will be called each time publish is completed.
This one is pretty useful because you could see the packetId of just received PUBACK or PUBCOMP packet.
[source,ruby]
----
require 'vertx/buffer'
client.publish_completion_handler() { |id|
  puts "Id of just received PUBACK or PUBCOMP packet is #{id}"
}.publish("hello", Vertx::Buffer.buffer("hello"), :EXACTLY_ONCE, false, false).publish("hello", Vertx::Buffer.buffer("hello"), :AT_LEAST_ONCE, false, false).publish("hello", Vertx::Buffer.buffer("hello"), :AT_LEAST_ONCE, false, false)


----
WARNING: The handler WILL NOT BE CALLED if sent publish packet with QoS=0.

* subscribe completed
+
[source,ruby]
----
client.subscribe_completion_handler() { |mqttSubAckMessage|
  puts "Id of just received SUBACK packet is #{mqttSubAckMessage.message_id()}"
  mqttSubAckMessage.granted_qo_s_levels().each do |s|
    if (s == 128)
      puts "Failure"
    else
      puts "Success. Maximum QoS is #{s}"
    end
  end
}.subscribe("temp", 1).subscribe("temp2", 2)

----

* unsubscribe completed
+
[source,ruby]
----
client.unsubscribe_completion_handler() { |id|
  puts "Id of just received UNSUBACK packet is #{id}"
}.subscribe("temp", 1).unsubscribe("temp")

----
* unsubscribe sent
+
[source,ruby]
----
Code not translatable
----

* PINGRESP received
+
[source,ruby]
----
client.ping_response_handler() { |s|
  #The handler will be called time to time by default
  puts "We have just received PINGRESP packet"
}

----