Method: NLHue::Disco.send_discovery

Defined in:
lib/nlhue/disco.rb

.send_discovery(timeout = 4, &block) ⇒ Object

Sends an SSDP discovery request, then yields an NLHue::Bridge object for each Hue hub found on the network. Responses may come for more than timeout seconds after this function is called. Reuses Bridge objects from previously discovered bridges, if any. Returns the connection used by SSDP.



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/nlhue/disco.rb', line 204

def self.send_discovery timeout=4, &block
  # Even though we put 'upnp:rootdevice' in the ST: header, the
  # Hue hub sends multiple matching and non-matching responses.
  # We'll use a hash to track which IP addresses we've seen.
  devs = {}

  con = NLHue::SSDP.discover 'upnp:rootdevice', timeout do |ssdp|
    if ssdp && ssdp['Location'].include?('description.xml') && ssdp['USN']
      serial = ssdp['USN'].gsub(/.*([0-9A-Fa-f]{12}).*/, '\1')
      unless devs.include?(ssdp.ip) && devs[ssdp.ip].serial == serial
        dev = @@bridges.include?(serial) ?
          @@bridges[serial][:bridge] :
          Bridge.new(ssdp.ip, serial)

        dev.addr = ssdp.ip unless dev.addr == ssdp.ip

        if dev.verified?
          yield dev
        else
          dev.verify do |result|
            if result && !con.closed?
              devs[ssdp.ip] = dev
              begin
                yield dev
              rescue => e
                log_e e, "Error notifying block with discovered bridge #{serial}"
              end
            end
          end
        end
      end
    end
  end

  con
end