Ruby

This manual will help you to get started with Ruby and the ruby-mqtt library.

Get started

In order to use the library install the gem using rubygems:

1
$ gem install mqtt

After that you can require the library in your script:

1
require 'mqtt'

Get started by running the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
require 'rubygems'
require 'mqtt'

MQTT::Client.connect('mqtt://try:try@broker.shiftr.io', client_id: 'ruby') do |client|
  client.subscribe '/example'
  # client.unsubscribe '/example'

  loop do
    client.publish 'hello', 'world'

    while !client.queue_empty? do
      topic, message = client.get
      puts "#{topic}: #{message}"
    end

    sleep 1
  end
end

This example script will connect to the try namespace and send a hello world message every second. If you see the connected client and the messages flowing in the real-time graph, you are ready to go!

In Detail

In the following section, we will look at the above example script line by line.

A detailed description of the libraries API can also be found in repository on GitHub.

To use the library you first need to require it:

1
2
require 'rubygems'
require 'mqtt'

Now, you can connect to shiftr.io:

1
2
3
MQTT::Client.connect('mqtt://try:try@broker.shiftr.io', client_id: 'ruby') do |client|
  # ...
end
  • The first argument is the MQTT URI which you can get from your namespace on shiftr.io.
  • The second argument is a hash with the clientId property, which will be displayed as the connections name in the real-time graph.
  • The passed block will be executed when the client has connected.

Make subscriptions to receive messages from other clients:

1
client.subscribe '/example'
  • The first argument is the name of the topic to subscribe.

Of course, you can always cancel a subscription by unsubscribing it:

1
client.unsubscribe '/example'
  • The first argument is the name of the topic to unsubscribe.

Most importantly, publish messages to shiftr.io:

1
client.publish 'hello', 'world'
  • The first argument is the topic to publish the message to.
  • The second argument is the payload of the message.

And last but not least, receive messages from other clients by looping over the queue:

1
2
3
4
while !client.queue_empty? do
  topic, message = client.get
  puts "#{topic}: #{message}"
end
  • The method client.queue_empty? returns if there are any messages received.
  • The method client.get will return the first message in the queue.

Congratulations, now you are able to work with shiftr.io in your Ruby projects!