Class: ADAM6050::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/adam6050/server.rb

Overview

The server listens to a speciefied UDP port and delegates incomming messages to the different handlers.

Constant Summary collapse

DEFAULT_PORT =

Returns the dafault port of the UDP server.

Returns:

  • (Integer)

    the dafault port of the UDP server.

1025

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(password: nil, logger: Logger.new(STDOUT)) ⇒ Server

Returns a new instance of Server.

Parameters:

  • password (String) (defaults to: nil)

    the plain text password to use when validating new clients.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/adam6050/server.rb', line 15

def initialize(password: nil, logger: Logger.new(STDOUT))
  @session  = Session.new
  @handlers = [
    Handler::Login.new(password),
    Handler::Status.new,
    Handler::Read.new,
    Handler::Write.new
  ]
  @state = State.initial
  @state_lock = Mutex.new
  @logger = logger
end

Instance Attribute Details

#loggerLogger (readonly)

Returns the logger used by the server.

Returns:

  • (Logger)

    the logger used by the server.



11
12
13
# File 'lib/adam6050/server.rb', line 11

def logger
  @logger
end

Instance Method Details

#run(host: nil, port: DEFAULT_PORT, &block) ⇒ Object

Parameters:

  • host (String) (defaults to: nil)

    the host to listen on.

  • port (Integer) (defaults to: DEFAULT_PORT)

    the UDP port to listen on.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/adam6050/server.rb', line 30

def run(host: nil, port: DEFAULT_PORT, &block)
  logger.info "Listening on port #{port}"

  Socket.udp_server_loop host, port do |msg, sender|
    logger.debug { "#{sender.remote_address.inspect} -> '#{msg.inspect}'" }
    handler = @handlers.find { |h| h.handles? msg } || next
    @state_lock.synchronize do
      handle(handler, msg, sender, &block)
    end
  end
end

#updateObject

Updates the state atomicly.



43
44
45
46
47
# File 'lib/adam6050/server.rb', line 43

def update
  @state_lock.synchronize do
    @state = yield @state
  end
end