Class: LifxDash::LifxHTTPApi

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

Constant Summary collapse

BASE_URI =
"api.lifx.com/v1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_token, logger = LOGGER) ⇒ LifxHTTPApi

Initialize a new api client with a an API auth token and logger If no logger is passed, the default LOGGER constant will be used e.g.

LifxDash::LifxHTTPApi.new("my-token-here", Logger.new(STDOUT))

17
18
19
20
# File 'lib/lifx_dash/lifx_http_api.rb', line 17

def initialize(api_token, logger = LOGGER)
  @token = api_token
  @logger = logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger


9
10
11
# File 'lib/lifx_dash/lifx_http_api.rb', line 9

def logger
  @logger
end

#tokenObject (readonly)

Returns the value of attribute token


9
10
11
# File 'lib/lifx_dash/lifx_http_api.rb', line 9

def token
  @token
end

Instance Method Details

#toggle(selector = "all") ⇒ Object

Call the toggle-power endpoint on the LIFX HTTP API. Pass a `selector` argument (defaults to 'all'). The API auth token is passed via HTTP Basic AUTH.

The method logs success, warning or errors to the logger. Success is determined by a 2XX response code and a valid JSON response body like so:

{"results":[{"id":"d073d500ec8e","label":"Golden Boy","status":"ok"}]}

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/lifx_dash/lifx_http_api.rb', line 32

def toggle(selector = "all")
  uri = URI("https://#{BASE_URI}/lights/#{selector}/toggle")
  logger.info "Toggling lights! (via #{BASE_URI})"

  Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
    req = Net::HTTP::Post.new(uri)
    req.add_field "Authorization", "Bearer #{token}"
    res = http.request(req)
    if res.code.to_s =~ /^2/ && success?(res.body)
      logger.info "Lights toggled successfully!"
      logger.info "API reply (#{res.code}): #{res.body}"
    else
      logger.warn "Warning: Possible issue with LIFX lights or HTTP API response"
      logger.warn "API reply (#{res.code}): #{res.body}"
    end
  end
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, URI::InvalidURIError,
         Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
  logger.error "Error: POST request to #{BASE_URI} failed: #{e.message}"
  raise e
end