Class: MQTT::Homie::Client

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

Overview

Constant Summary collapse

DEFAULT_ROOT_TOPIC =
"homie"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mqtt/homie/client.rb', line 11

def initialize(options = {})
  @device = options[:device]
  @host = options[:host]
  @root_topic = options[:root_topic] || DEFAULT_ROOT_TOPIC

  raise "device required" unless @device

  # next version of homie doesn't use stats or firmware details
  @use_stats = true
  if options[:develop]
    @device.use_stats = false
    @device.use_fw = false
    @use_stats = false
  end

  # observe all node properties so we can publish values when they change
  @device.nodes.each do |node|
    node.properties.each do |property|
      property.add_observer(self)
    end
  end
end

Instance Attribute Details

#deviceObject (readonly)

Returns the value of attribute device.



9
10
11
# File 'lib/mqtt/homie/client.rb', line 9

def device
  @device
end

#hostObject

Returns the value of attribute host.



8
9
10
# File 'lib/mqtt/homie/client.rb', line 8

def host
  @host
end

#root_topicObject

Returns the value of attribute root_topic.



8
9
10
# File 'lib/mqtt/homie/client.rb', line 8

def root_topic
  @root_topic
end

Instance Method Details

#connectObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/mqtt/homie/client.rb', line 34

def connect
  return if connected?

  @device.state = :init
  @client = create_mqtt_client
  @client.connect

  publish(@device, topic)
  publish_statistics if @use_stats

  @threads = []

  # run a thread to publish statistics
  @threads << Thread.new { run_statistics } if @use_stats

  # run a thread to listen for settings
  @threads << Thread.new { run_set_listener }

  @device.state = :ready
  publish_state
end

#connected?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/mqtt/homie/client.rb', line 71

def connected?
  @device.state == :ready
end

#disconnectObject



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

def disconnect
  @device.state = :disconnected
  publish_state

  @client.disconnect
  @client = nil

  @threads.each { |i| i[:done] = true }
  @threads = []
end

#topicObject



67
68
69
# File 'lib/mqtt/homie/client.rb', line 67

def topic
  @root_topic + "/" + @device.id
end

#update(time, object) ⇒ Object



75
76
77
78
79
# File 'lib/mqtt/homie/client.rb', line 75

def update(time, object)
  if object.kind_of?(MQTT::Homie::Property)
    publish_property_value(object)
  end
end