class Orchestrator::Device::UdpConnection

Public Class Methods

new(manager, processor) click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 4
def initialize(manager, processor)
    @manager = manager
    @loop = manager.thread
    @processor = processor

    settings = manager.settings
    @ip = settings.ip
    @port = settings.port
    @on_read = method(:on_read)

    # One per loop unless port specified
    @udp_server = @loop.udp_service

    if IPAddress.valid? @ip
        @attached_ip = @ip
        @udp_server.attach(@attached_ip, @port, @on_read)
        @loop.next_tick do
            # Call connected (we only need to do this once)
            @processor.connected
        end
    else
        variation = 1 + rand(60000 * 5)  # 5min
        @checker = @manager.get_scheduler.in(60000 * 5 + variation) do
            find_ip(@ip)
        end
        find_ip(@ip)
    end
end

Public Instance Methods

disconnect() click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 58
def disconnect; end
on_read(data) click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 38
def on_read(data)
    # We schedule as UDP server may be on a different thread
    @loop.schedule do
        @processor.buffer(data)
    end
end
terminate() click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 45
def terminate
    #@processor.disconnected   # Disconnect should never be called
    @terminated = true
    if @searching
        @searching.cancel
        @searching = nil
    else
        @udp_server.detach(@attached_ip, @port)
    end

    @checker.cancel if @checker
end
transmit(cmd) click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 33
def transmit(cmd)
    return if @terminated
    @udp_server.send(@attached_ip, @port, cmd[:data])
end

Protected Instance Methods

find_ip(hostname) click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 64
def find_ip(hostname)
    @loop.lookup(hostname).then(proc{ |result|
        update_ip(result[0][0])
    }, proc { |failure|
        variation = 1 + rand(8000)
        @searching = @manager.get_scheduler.in(8000 + variation) do
            @searching = nil
            find_ip(hostname)
        end
    })
end
update_ip(ip) click to toggle source
# File lib/orchestrator/device/transport_udp.rb, line 76
def update_ip(ip)
    if ip != @attached_ip
        if @attached_ip
            @udp_server.detach(@attached_ip, @port)
        else
            @processor.connected
        end
        @attached_ip = ip
        @udp_server.attach(@attached_ip, @port, @on_read)
    end
end