Class: ITACH::Detect

Inherits:
Object
  • Object
show all
Defined in:
lib/itach/detect.rb

Class Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Detect

Returns a new instance of Detect.



18
19
20
21
22
# File 'lib/itach/detect.rb', line 18

def initialize options={}
  @address  = ENV['ITACH_ADDRESS'] || '239.255.250.250'
  @port     = ENV['ITACH_PORT']    || 9131
  @timeout  = options[:timeout]    || 20
end

Class Attribute Details

.ipObject (readonly)

Returns the value of attribute ip.



6
7
8
# File 'lib/itach/detect.rb', line 6

def ip
  @ip
end

Instance Method Details

#find_deviceObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/itach/detect.rb', line 39

def find_device
  begin
    Timeout::timeout(@timeout) do
      begin
        socket.bind(Socket::INADDR_ANY, @port)
        loop do
          msg, info = @socket.recvfrom(1024)
          if info
            @@ip = info[2]
            return "iTach found at #{info[2]}."
          end
        end
      ensure
        @socket.close
      end
    end
  rescue Timeout::Error
    puts "An iTach device was not fount within #{@timeout} seconds."
  end
end

#ipObject



24
25
26
# File 'lib/itach/detect.rb', line 24

def ip
  @ip ||= IPAddr.new(@address).hton + IPAddr.new("0.0.0.0").hton
end

#socketObject



28
29
30
31
32
33
34
35
36
37
# File 'lib/itach/detect.rb', line 28

def socket
  begin
    @socket = UDPSocket.new
    @socket.setsockopt(Socket::IPPROTO_IP, Socket::IP_ADD_MEMBERSHIP, ip)
    @socket
  rescue Errno::EADDRINUSE
    @socket.close
    socket
  end
end