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.

  • logger (Logger) (defaults to: Logger.new(STDOUT))

    the logger to use.



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/adam6050/server.rb', line 19

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

#stateInteger (readonly)

Returns the current state.

Returns:

  • (Integer)

    the current state.



14
15
16
# File 'lib/adam6050/server.rb', line 14

def state
  @state
end

Instance Method Details

#run(host: nil, port: DEFAULT_PORT) {|Integer| ... } ⇒ nil

Starts a new UDP server that listens on the given port. The state is updated atomically and yielded to an optional block everytime a change is made. By returning ‘false` the block can cancel the state update. This call is blocking.

Parameters:

  • host (String) (defaults to: nil)

    the host to listen on.

  • port (Integer) (defaults to: DEFAULT_PORT)

    the UDP port to listen on.

Yields:

  • (Integer)

    the updated state.

  • (Integer)

    the old state.

Returns:

  • (nil)


43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/adam6050/server.rb', line 43

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
  nil
end

#update {|Integer| ... } ⇒ Object

Updates the state atomicly. The current state will be yielded to the given block and the return value used as the next state.

Yields:

  • (Integer)

    the current state.



60
61
62
63
64
# File 'lib/adam6050/server.rb', line 60

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