Class: Discovery::UDP

Inherits:
Object
  • Object
show all
Defined in:
lib/discovery/udp.rb

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.discoverablesObject (readonly)

Returns the value of attribute discoverables.



57
58
59
# File 'lib/discovery/udp.rb', line 57

def discoverables
  @discoverables
end

.groupObject

Returns the value of attribute group.



12
13
14
# File 'lib/discovery/udp.rb', line 12

def group
  @group
end

.portObject

Returns the value of attribute port.



11
12
13
# File 'lib/discovery/udp.rb', line 11

def port
  @port
end

.threadObject (readonly)

Returns the value of attribute thread.



13
14
15
# File 'lib/discovery/udp.rb', line 13

def thread
  @thread
end

Class Method Details

.beacon_to_hash(beacon) ⇒ Object

Convert the incoming beacon to a Hash containing all necessary info Implement to something nontrivial in the inherited module



49
50
51
# File 'lib/discovery/udp.rb', line 49

def self.beacon_to_hash beacon
  {beacon:beacon}
end

.haltObject

Halt the discovery thread started by listen, but do not unregister the callback



38
# File 'lib/discovery/udp.rb', line 38

def self.halt; @thread.kill; end

.listen(&block) ⇒ Object

Register a callback to be used in the event of a recognized beacon. Each non-nil response object for each UDP beacon will be yielded to it.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/discovery/udp.rb', line 20

def self.listen &block
  @blocks ||= []
  (@blocks << block).uniq!
  
  @thread ||= Thread.new do
    loop do
      @discoverables.values.each_with_object(next_beacon) do |blk,beacon|
        obj = blk.call beacon
        @blocks.each do |callback|
          callback.call(obj)
        end unless obj.nil?
      end
    end
  end
end

.newObject



16
# File 'lib/discovery/udp.rb', line 16

def self.new; raise NotImplementedError nil end

.next_beacon(timeout: nil) ⇒ Object

Return the info hash of the next DDDP beacon detected - blocking Optional :timeout keyword argument specifies maximum time to block



42
43
44
45
# File 'lib/discovery/udp.rb', line 42

def self.next_beacon timeout:nil
  @udp_rx ||= Util::UDP::RX.new(@group, @port)
  beacon_to_hash(Timeout.timeout(timeout) { @udp_rx.gets })
end

.register(cls, &block) ⇒ Object



58
59
60
61
# File 'lib/discovery/udp.rb', line 58

def self.register cls, &block
  @discoverables ||= {}
  @discoverables[cls] = block
end