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:

$ gem install mqtt

After that you can require the library in your script:

require 'mqtt'

Get started by running the following code:

require 'rubygems'
require 'mqtt'

MQTT::Client.connect('mqtt://public:public@public.cloud.shiftr.io', client_id: 'ruby') do |client|
  client.subscribe 'hello'

  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 public instance 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:

require 'rubygems'
require 'mqtt'

Now, you can connect to shiftr.io:

MQTT::Client.connect('mqtt://public:public@public.cloud.shiftr.io', client_id: 'ruby') do |client|
  # ...
end
  • The first argument is the MQTT URI which you can get from your instance on shiftr.io.
  • The second argument is a hash with the client_id 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:

client.subscribe 'hello'
  • The first argument is the name of the topic to subscribe.

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

client.unsubscribe 'hello'
  • The first argument is the name of the topic to unsubscribe.

Most importantly, publish messages to shiftr.io:

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:

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!