How to use sango - Ruby edition

I will explain how to use sango from Ruby.

To use sango in Ruby, follow the procedure below.

  1. Installation of gem
  2. Client implementation

Confirmed environment

  • Ruby 2.0.0
  • Gem 2.0.14
  • Ruby-mqtt 0.3.0

1. Installation of gem

gem install mqtt

As a result, ruby-mqtt it will be installed.

2. Client implementation

MQTT::Client.new(Hostname, ...) ...) `` to create an instance of the MQTT client, to connect if you run connect.

After connect the get or perform Subscribe in, publish or you can go to Publish in.

Connect

The connect part is common to both Pub / Sub.

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'rubygems'
require 'mqtt'

MQTTHOST = "free.mqtt.shiguredo.jp"
USERNAME = "example@github"
PASSWORD = "<password>"

# MQTTに接続するためのクライアントを作成します
client = MQTT::Client.new(
  MQTTHOST,
  :username => USERNAME,
  :password => PASSWORD
)

Subscribe

# 接続します
client.connect do |c|
  # Subscribeします
  TOPIC = "shirou@github/#"
  c.get(TOPIC) do |topic, message|
    puts "#{topic}: #{message}"
  end
end

Publish

# 接続します
client.connect do |c|
  # Publishします
  TOPIC = "shirou@github/a/b"
  c.publish(TOPIC, "message from ruby")
end

reference

Rubydoc
http://rubydoc.info/gems/mqtt