Class: Lightwavez::Client

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

Constant Summary collapse

COMMANDS =
{ :on => 'F1', :off => 'F0', :all_off => 'Fa', :last_dim => 'Fo', :dim => 'Fd', :mood => 'Fm'}

Instance Method Summary collapse

Constructor Details

#initialize(address = nil, port = 9760) ⇒ Client

Returns a new instance of Client.



9
10
11
12
# File 'lib/client.rb', line 9

def initialize(address = nil, port = 9760)
  @address = address || discover
  @port = port
end

Instance Method Details

#discoverObject

this will register the first time and get the IP address for the link afte that



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/client.rb', line 47

def discover
  sock = UDPSocket.new
  sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, true)

  result = ""
  server_thread = Thread.start do
    server = UDPSocket.open
    server.bind('0.0.0.0', 9761)
    result = server.recvfrom(64)
    server.close
  end

  sock.send("100,!F*p\r", 0, '255.255.255.255', 9760)
  server_thread.join(2)
  sock.close

  if !result.is_a? Array || result.length < 1 || result[1].length < 2
    raise 'invalid response'
  end

  return result[1][2]
end

#get_command(room, device, operation, params = nil) ⇒ Object

generates a command for a room and a device. Only supports on/off/dimm commands for now accepted operations are: :on, :off, :all_off, :last_dim, :dim (needs param to be 1-32), :mood (needs mood id) device is not needed for :all_off and :mood  rooms, devices and moods (params for :mood) and be either a number or name if mapping is loaded



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/client.rb', line 18

def get_command(room, device, operation, params = nil)
  raise 'invalid command' unless COMMANDS.has_key? operation
  raise 'missing dim level (1-32)' if params.nil? && operation == :dim
  raise 'missing mood id' if params.nil? && operation == :mood

  cmd = ""
  if operation != :all_off && operation != :mood
    cmd = "R#{room}D#{device}#{COMMANDS[operation]}"
    if operation == :dim
      raise 'invalid dim level (1-32)' if params < 1 || params > 32
      cmd = cmd + "P#{params}"
    end
  else
    cmd = "R#{room}#{COMMANDS[operation]}"
    if operation == :mood
      cmd = cmd + "P#{params}"
    end
  end

  return cmd
end

#send(command) ⇒ Object

consructs and sends a command over to the link without waiting for the answer



41
42
43
44
# File 'lib/client.rb', line 41

def send(command)
  sequence = Random.rand(100)
  send_raw("#{sequence},!#{command}\r")
end