Class: LifxDash::LifxHTTPApi
- Inherits:
-
Object
- Object
- LifxDash::LifxHTTPApi
- Defined in:
- lib/lifx_dash/lifx_http_api.rb
Constant Summary collapse
- BASE_URI =
"api.lifx.com/v1"
Instance Attribute Summary collapse
-
#logger ⇒ Object
readonly
Returns the value of attribute logger.
-
#token ⇒ Object
readonly
Returns the value of attribute token.
Instance Method Summary collapse
-
#initialize(api_token, logger = LOGGER) ⇒ LifxHTTPApi
constructor
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.
-
#toggle(selector = "all") ⇒ Object
Call the toggle-power endpoint on the LIFX HTTP API.
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))
18 19 20 21 |
# File 'lib/lifx_dash/lifx_http_api.rb', line 18 def initialize(api_token, logger = LOGGER) @token = api_token @logger = logger end |
Instance Attribute Details
#logger ⇒ Object (readonly)
Returns the value of attribute logger.
10 11 12 |
# File 'lib/lifx_dash/lifx_http_api.rb', line 10 def logger @logger end |
#token ⇒ Object (readonly)
Returns the value of attribute token.
10 11 12 |
# File 'lib/lifx_dash/lifx_http_api.rb', line 10 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"}]}
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/lifx_dash/lifx_http_api.rb', line 33 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.}" raise e end |