Class: MaxCube::Network::UDP::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/maxcube/network/udp/client.rb

Overview

Class that provides yet only basic UDP communication with Cube devices.

Instance Method Summary collapse

Constructor Details

#initialize(port = PORT) ⇒ Client

Returns a new instance of Client.



9
10
11
12
13
14
15
16
# File 'lib/maxcube/network/udp/client.rb', line 9

def initialize(port = PORT)
  @socket = UDPSocket.new
  @socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)
  @port = port

  @parser = Messages::UDP::Parser.new
  @serializer = Messages::UDP::Serializer.new
end

Instance Method Details

#closeObject



47
48
49
50
# File 'lib/maxcube/network/udp/client.rb', line 47

def close
  puts "\nClosing client ..."
  @socket.close
end

#discoveryObject



42
43
44
45
# File 'lib/maxcube/network/udp/client.rb', line 42

def discovery
  puts "Starting discovery ...\n\n"
  send_recv_hash(type: 'I')
end

#recv_msgObject



22
23
24
25
26
27
28
29
# File 'lib/maxcube/network/udp/client.rb', line 22

def recv_msg
  msg, addr = @socket.recvfrom(1024)
  port = addr[1]
  ipaddr = addr[3]
  [msg, ipaddr, port]
rescue Interrupt
  puts 'Aborted'
end

#send_msg(msg, addr = BROADCAST) ⇒ Object



18
19
20
# File 'lib/maxcube/network/udp/client.rb', line 18

def send_msg(msg, addr = BROADCAST)
  @socket.send(msg, 0, addr, @port)
end

#send_recv_hash(hash, addr = BROADCAST) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/maxcube/network/udp/client.rb', line 31

def send_recv_hash(hash, addr = BROADCAST)
  msg = @serializer.serialize_udp_hash(hash)
  send_msg(msg, addr)
  msg, addr, port = recv_msg
  return nil unless msg
  hash = @parser.parse_udp_msg(msg)
  puts "'#{hash[:type]}' response from #{addr}:#{port}:\n" \
       "#{hash.to_yaml}\n"
  hash
end