# Ruby MQTT with RabbitMQ and LavinMQ

We recommend [ruby-mqtt](https://github.com/njh/ruby-mqtt), a synchronous MQTT 3.1.1 client.

```bash
gem install mqtt
```

## Publish and subscribe

Set `MQTT_HOST`, `MQTT_PORT`, `MQTT_USERNAME` and `MQTT_PASSWORD` to the MQTT details on your instance’s details page in the CloudAMQP console. Port 8883 uses TLS. Without them, the examples connect to a local broker.

Save the publisher as `publisher.rb`:

```ruby
require "mqtt"

port = Integer(ENV.fetch("MQTT_PORT", "1883"))
client = MQTT::Client.new(
  host: ENV.fetch("MQTT_HOST", "localhost"),
  port: port,
  ssl: port == 8883,
  username: ENV.fetch("MQTT_USERNAME", "guest"),
  password: ENV.fetch("MQTT_PASSWORD", "guest")
)
# ruby-mqtt only checks the certificate's hostname, not who signed it
client.ssl_context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
client.connect

# QoS 1 waits for the broker's PUBACK
client.publish("hello", "Hello world!", false, 1)
puts " [x] Sent 'Hello world!'"
client.disconnect
```

Save the subscriber as `worker.rb`:

```ruby
require "mqtt"

port = Integer(ENV.fetch("MQTT_PORT", "1883"))
client = MQTT::Client.new(
  host: ENV.fetch("MQTT_HOST", "localhost"),
  port: port,
  ssl: port == 8883,
  username: ENV.fetch("MQTT_USERNAME", "guest"),
  password: ENV.fetch("MQTT_PASSWORD", "guest")
)
# ruby-mqtt only checks the certificate's hostname, not who signed it
client.ssl_context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
client.connect

client.subscribe("hello" => 1)
puts " [*] Waiting for messages. To exit press CTRL+C"
# Each message is acked when the block returns
client.get do |_topic, message|
  puts " [x] Received '#{message}'"
end
```

Run `ruby worker.rb` in one terminal and `ruby publisher.rb` in another.

A runnable example is in [ruby/mqtt in cloudamqp/examples](https://github.com/cloudamqp/examples/tree/main/ruby/mqtt).

## Good to know

- **Put the vhost in the username**, as `vhost:user`. MQTT has no vhost of its own, and the console shows the username that way.
- **Verify the server certificate.** ruby-mqtt only checks the certificate’s hostname, so set `verify_mode` to `VERIFY_PEER` on its `ssl_context`, as the example does.
- **Use QoS 1**, so `publish` waits for the broker’s PUBACK, and `get` acks each message when the block returns.
- **The client is synchronous.** `get` blocks, so run it in its own thread if the process does other work.
