Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby wrapper for public Nest API
require 'excon'
require 'json'
require 'uri'
module NestAPI
VERSION = '0.0.1'
class Default
def initialize(token)
@token = token
end
def url
URI.parse('https://developer-api.nest.com')
end
def query
{
auth: @token
}
end
def headers
{
'User-Agent' => "NestAPI LIFX v#{VERSION}",
'Accept' => 'application/json'
}
end
def middlewares
Excon.defaults[:middlewares] + [Excon::Middleware::RedirectFollower]
end
end
class Error < StandardError
end
class Session
def initialize(token)
@default = Default.new(token)
end
def structures
(tree['structures'] ||= {}).keys.map do |id|
Structure.new(id, @default, tree)
end
end
private
def tree
return @tree if @tree
expected = 200
response = Excon.get(@default.url.to_s, {
query: URI.encode_www_form(@default.query),
headers: @default.headers,
middlewares: @default.middlewares
})
if response.status == expected
@tree = JSON.parse(response.body)
else
raise Error, "Nest failed to retrieve data. Expected #{expected}, got #{response.status}. Response: #{response.body}"
end
end
end
class Structure
def initialize(id, default, tree)
@id = id
@default = default
@tree = tree
end
def id
@id
end
def away
ref['away']
end
def away=(new_value)
expected = 200
response = Excon.put("#{@default.url.to_s}/structures/#{@id}", {
body: JSON.dump(away: new_value),
query: URI.encode_www_form(@default.query),
headers: @default.headers,
middlewares: @default.middlewares
})
if response.status == expected
ref['away'] = new_value
else
raise Error, "Nest failed to update structure. Expected #{expected}, got #{response.status}. Response: #{response.body}"
end
end
private
def ref
@tree['structures'][@id]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.