Class: MessageChannel::Mqtt

Inherits:
Object
  • Object
show all
Defined in:
lib/message_channel/mqtt.rb

Instance Method Summary collapse

Constructor Details

#initialize(host: nil, port: nil) ⇒ Mqtt

Returns a new instance of Mqtt.



7
8
9
10
11
12
# File 'lib/message_channel/mqtt.rb', line 7

def initialize( host: nil, port: nil )
  @host  =  host  || "127.0.0.1"
  @port  =  ( port  ||  1883 ).to_i
  @mqtt  =  MQTT::Client.connect( @host, @port )
  @threads  =  {}
end

Instance Method Details

#listen(*patterns, &block) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/message_channel/mqtt.rb', line 56

def listen( *patterns, &block )
  if block.nil?
    listen_once( *patterns )
  else
    listen_each( *patterns ) do |topic, items|
      block.call( topic, items )
    end
  end
end

#listen_each(*patterns, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/message_channel/mqtt.rb', line 40

def listen_each( *patterns, &block )
  patterns.each do |pattern|
    @threads[pattern]  =  ::Thread.start( pattern ) do |pttrn|
      mqtt  =  MQTT::Client.connect( @host, @port )
      begin
        mqtt.get( pttrn ) do |topic, message|
          items  =  JSON.parse( message, symbolize_names: true )
          block.call( topic, items )
        end
      ensure
        mqtt.disconnect    rescue  nil
      end
    end
  end
end

#listen_once(*patterns) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/message_channel/mqtt.rb', line 14

def listen_once( *patterns )
  queue  =  Queue.new
  threads  =  {}
  patterns.each do |pattern|
    threads[pattern]  =  ::Thread.start( pattern ) do |pttrn|
      mqtt  =  MQTT::Client.connect( @host, @port )
      begin
        mqtt.get( pttrn ) do |topic, message|
          items  =  JSON.parse( message, symbolize_names: true )
          mqtt.disconnect    rescue  nil
          queue.push  [topic, items]
        end
      rescue => e
        nil
      end
    end
  end

  topic, items  =  queue.pop
  patterns.each do |pattern|
    threads[pattern].kill    rescue  nil
    threads.delete( pattern )    rescue  nil
  end
  [topic, items]
end

#notify(topic, **items) ⇒ Object



73
74
75
# File 'lib/message_channel/mqtt.rb', line 73

def notify( topic, **items )
  @mqtt.publish( topic, items.to_json, false )
end

#unlisten(**patterns) ⇒ Object



66
67
68
69
70
71
# File 'lib/message_channel/mqtt.rb', line 66

def unlisten( **patterns )
  patterns.each do |pattern|
    @threads[pattern].kill    rescue  nil
    @threads.delete( pattern )    rescue  nil
  end
end