class Milight::V6::Command

see github.com/Fantasmos/LimitlessLED-DevAPI

Attributes

wait[RW]

Public Class Methods

new(socket, wait:) click to toggle source
# File lib/milight/v6/command.rb, line 12
def initialize(socket, wait:)
  @socket = socket
  @wait = wait
  @last_time = 0
end

Public Instance Methods

execute(zone_id, command) click to toggle source
# File lib/milight/v6/command.rb, line 18
def execute(zone_id, command)
  raise ArgumentError, "Please supply a zone ID between 1-4." if zone_id.negative? || zone_id > 4

  bridge_session

  # UDP Hex Send Format: 80 00 00 00 11 {WifiBridgeSessionID1} {WifiBridgeSessionID2} 00 {SequenceNumber} 00 {COMMAND} {ZONE NUMBER} 00 {Checksum}
  request = [0x80, 0x00, 0x00, 0x00, 0x11, @session_id1, @session_id2, 0x00, next_sequence_number, 0x00]

  request += command

  request << zone_id
  request << 0x00
  request << calculate_checksum(request)

  send_delayed(request)
end

Private Instance Methods

bridge_session() click to toggle source
# File lib/milight/v6/command.rb, line 37
def bridge_session
  return if !@session_id1.nil? || !@session_id2.nil?

  # UDP.SEND hex bytes: 20 00 00 00 16 02 62 3A D5 ED A3 01 AE 08 2D 46 61 41 A7 F6 DC AF (D3 E6) 00 00 1E <-- Send this to the ip address of the wifi bridge v6
  request = [0x20, 0x00, 0x00, 0x00, 0x16, 0x02, 0x62, 0x3A, 0xD5,
             0xED, 0xA3, 0x01, 0xAE, 0x08, 0x2D, 0x46, 0x61, 0x41,
             0xA7, 0xF6, 0xDC, 0xAF, 0xD3, 0xE6, 0x00, 0x00, 0x1E]

  @socket.send_bytes(request)
  response, _address = @socket.receive_bytes

  raise Exception, "Could not establish session with Wifi bridge." if response.nil?

  record_last_time

  @session_id1 = response[19]
  @session_id2 = response[20]
end
calculate_checksum(bytes) click to toggle source
# File lib/milight/v6/command.rb, line 63
def calculate_checksum(bytes)
  checksum = 0

  for i in 10..19 do
    checksum += bytes[i]
  end

  checksum & 0xFF
end
current_time() click to toggle source
# File lib/milight/v6/command.rb, line 96
def current_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
delay_command() click to toggle source
# File lib/milight/v6/command.rb, line 83
def delay_command
  return unless @wait

  interval = current_time - @last_time
  sleep(@wait - interval) if interval < @wait
end
next_sequence_number() click to toggle source
# File lib/milight/v6/command.rb, line 56
def next_sequence_number
  @sequence_number = 0 if @sequence_number.nil? || @sequence_number >= 255
  @sequence_number += 1

  @sequence_number
end
record_last_time() click to toggle source
# File lib/milight/v6/command.rb, line 90
def record_last_time
  return unless @wait

  @last_time = current_time
end
send_delayed(request) click to toggle source

Delay execution of commands to prevent commands being dropped by the controller.

# File lib/milight/v6/command.rb, line 74
def send_delayed(request)
  delay_command

  @socket.send_bytes(request)
  @socket.receive_bytes

  record_last_time
end