class Libmagellan::MQTT

Constants

AUTH_BASE_URL
COLOURS
DEFAULT_LOG_LEVEL
LOG_LEVELS
MQTT_METHOD
OPTIONS
PROTOCOL

Attributes

client[R]
client_version[RW]
consumer_key[RW]
consumer_secret[RW]
host[RW]
port[RW]
token[RW]

Public Class Methods

new(args={}) click to toggle source

MQTT Client @param [Hash] args MQTT Arguments @option args [String] :host MQTT server host address @option args [Integer] :port MQTT server port @option args [String] :project Project name @option args [String] :consumer_key MQTT authorization consumer-key @option args [String] :consumer_key MQTT authorization consumer-secret

# File lib/libmagellan/mqtt.rb, line 57
def initialize(args={})
  args, errors = validate_args(args)
  show_errors(errors, initialize_usage()) if errors.present?

  @host = args.delete(:host)
  @port = args.delete(:port)
  @project = args.delete(:project)
  @consumer_key = args.delete(:consumer_key) || @project
  @consumer_secret = args.delete(:consumer_secret)
  @client_version = args.delete(:client_version)
  @secure = args.delete(:secure) || false
  @skip_verify = args[:skip_verify] || false

  @token = nil
  @client = nil
end

Public Instance Methods

disconnect() click to toggle source

MQTT Disconnect

# File lib/libmagellan/mqtt.rb, line 144
def disconnect
  connection.disconnect if connected?
end
get(topic=nil) { |topic_, payload_| ... } click to toggle source

Get message to me @param [String] topic Topic name @return [Array] topic and payload

# File lib/libmagellan/mqtt.rb, line 113
def get(topic=nil)
  with_connection do |c|
    if block_given?
      c.get(topic) do |topic_, payload_|
        yield(topic_, payload_)
      end
    else
      # return topic, payload
      c.get(topic)
    end
  end
end
get_packet(topic=nil) { |packet| ... } click to toggle source

Get message to me @param [String] topic Topic name @return [Mqtt::Packet] MQTT packet object

# File lib/libmagellan/mqtt.rb, line 129
def get_packet(topic=nil)
  with_connection do |c|
    if block_given?
      c.get_packet(topic) do |packet|
        yield(packet)
      end
    else
      # return topic, payload
      c.get_packet(topic)
    end
  end
end
logger() click to toggle source

@return [Logger]

# File lib/libmagellan/mqtt.rb, line 158
def logger
  @logger_
end
logger=(logger_) click to toggle source
# File lib/libmagellan/mqtt.rb, line 162
def logger=(logger_)
  @logger_ = logger_
end
pub(topic, payload, retain=false, qos=0)
Alias for: publish
publish(topic, payload, retain=false, qos=0) click to toggle source

Publish message to MQTT server. @param [String] topic Topic name @param [String] payload Payload

# File lib/libmagellan/mqtt.rb, line 78
def publish(topic, payload, retain=false, qos=0)
  payload = payload.to_json unless payload.is_a?(::String)
  with_connection do |c|
    c.publish(topic, payload, retain, qos)
    log("[PUBLISH] #{topic}: #{payload}", Logger::DEBUG)
  end
end
Also aliased as: pub
set_will(topic, payload, retain=false, qos=0) click to toggle source

MQTT Will

# File lib/libmagellan/mqtt.rb, line 149
def set_will(topic, payload, retain=false, qos=0)
  @will_topic = topic
  @will_payload = payload
  @will_qos = qos
  @will_retain = retain
  @with_will = true
end
sub(*topics, &block)
Alias for: subscribe
subscribe(*topics, &block) click to toggle source

Subscribe topic(s) @param [String|Array|Hash] topics Subscribe topics

# File lib/libmagellan/mqtt.rb, line 89
def subscribe(*topics, &block)
  with_connection do |c|
    c.subscribe(*topics)
    topics.each {|t| log("[SUBSCRIBE] #{t}", Logger::DEBUG) }
  end
  if block_given?
    get(nil, &block)
  end
end
Also aliased as: sub
unsub(*topics)
Alias for: unsubscribe
unsubscribe(*topics) click to toggle source

Unsubscribe topic(s) @param [String|Array|Hash] topics Subscribe topics

# File lib/libmagellan/mqtt.rb, line 102
def unsubscribe(*topics)
  with_connection do |c|
    c.unsubscribe(*topics)
    topics.each {|t| log("[UNSUBSCRIBE] #{t}", Logger::DEBUG) }
  end
end
Also aliased as: unsub

Private Instance Methods

connect(username, password) click to toggle source

Connect to MQTT Server @param [String] username Username @param [String] password Password @return [MQTT::Client] MQTT Client

# File lib/libmagellan/mqtt.rb, line 202
def connect(username, password)
  mqtt_host = "#{@host}:#{@port.to_s}"
  uri = "#{PROTOCOL}://#{username}:#{password}@#{mqtt_host}"
  @client = ::MQTT::Client.new(uri)
  if @with_will
    @client.set_will(@will_topic, @will_payload, @will_retain, @will_qos)
  end
  if @secure
    @client.ssl = true
    @client.ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE if @skip_verify
  end
  @client.connect
  log("[CONNECTED] #{host}:#{port}", Logger::DEBUG)
  return @client
end
connected?() click to toggle source

Check has connection. @return [Boolean]

# File lib/libmagellan/mqtt.rb, line 221
def connected?
  @client.present? and @client.connected?
end
connection() click to toggle source

Connect MQTT server @return [MQTT::Client] MQTT Client

# File lib/libmagellan/mqtt.rb, line 179
def connection
  username = @project || @consumer_key
  if connected?
    return @client
  else
    if @token.present?
      # トークンによる認証
      connect(username, @token)
    else
      # OAuthによる認証
      auth = generate_oauth_header(AUTH_BASE_URL, @consumer_key, @consumer_secret)
      headers = "Authorization: #{auth}"
      headers << ";Client-Version: #{@client_version}" if @client_version.present?
      password = Base64.urlsafe_encode64(headers)
      connect(username, password)
    end
  end
end
generate_oauth_header(uri, consumer_key, consumer_secret, options={}) { |client, options| ... } click to toggle source

Generate OAuth header @param [String] uri Auth URI @param [String] consumer_key Auth consumer-key @param [String] consumer_secret Auth consumer-secret @param [Hash] options Auth options

# File lib/libmagellan/mqtt.rb, line 230
def generate_oauth_header(uri, consumer_key, consumer_secret, options={})
  init_opt = {client_credential_key: consumer_key, client_credential_secret: consumer_secret}
  options[:uri] = uri if options[:uri].nil? or options[:uri].empty?
  options[:method] = MQTT_METHOD
  client = ::Signet::OAuth1::Client.new(init_opt)
  client.two_legged = true
  client, options = yield(client, options) if block_given?
  req = client.generate_authenticated_request(options)
  req["Authorization"]
end
initialize_usage() click to toggle source
# File lib/libmagellan/mqtt.rb, line 282
    def initialize_usage
      <<__USAGE__

usage:

c = Libmagellan::MQTT.new(host: "127.0.0.1", host: 1883, consumer_key: "groovenauts.app1", consumer_secret: "test", client_version: "0.0.1", log_level: :debug, commandline: true)

__USAGE__
    end
log(message="", lv=DEFAULT_LOG_LEVEL, colour=nil) click to toggle source

Logging @param [String] message Logging message @param [Symbol|String] type Logging type @param [Symbol] colour Message color

# File lib/libmagellan/mqtt.rb, line 262
def log(message="", lv=DEFAULT_LOG_LEVEL, colour=nil)
  color = COLOURS[colour.to_s.downcase.to_sym]
  m = ""
  m << "#{color}" if color.present?
  m << "#{message}"
  m << "\e[0m" if color.present?
  logger.log(lv, m) if logger
end
show_errors(errors, message="") click to toggle source

Show errors and exit(0) @param [Array] errors Error messages @param [String] message Extra message

# File lib/libmagellan/mqtt.rb, line 275
def show_errors(errors, message="")
  errors.each do |e|
    log("#{e[:field]}: #{e[:message]}", Logger::ERROR, :red)
  end
  log(message, Logger::INFO, :white) if message.present?
end
validate_args(args) click to toggle source

Validate arguments. @see initialize

# File lib/libmagellan/mqtt.rb, line 244
def validate_args(args)
  errors = []
  args = args.symbolize_keys
  OPTIONS.each do |key, val|
    if val[:required]
      errors << {field: key, message: "required param"} if args[key].blank?
    end
    if val[:default] and not args.key?(key)
      args[key] = val[:default]
    end
  end
  return args, errors
end
with_connection() { |connection()| ... } click to toggle source

Send command to MQTT server. Connect MQTT server if it is not has connection.

# File lib/libmagellan/mqtt.rb, line 173
def with_connection
  yield(connection()) if block_given?
end