Skip to content

Instantly share code, notes, and snippets.

@henrik

henrik/sureflap.rb

Last active Dec 16, 2019
Embed
What would you like to do?
SureFlap API Ruby example.
# SureFlap API code example.
#
# By Henrik Nyh <https://henrik.nyh.se> 2019-12-16 under the MIT license.
# Heavily based on the https://github.com/alextoft/sureflap PHP code by Alex Toft.
#
# Has no dependencies outside the Ruby standard library (uses Net::HTTP directly and painfully).
require "net/http"
require "json"
require "pp"
EMAIL = "foo@example.com"
PASSWORD = "my-secret-password"
ENDPOINT = "https://app.api.surehub.io"
auth_data = { email_address: EMAIL, password: PASSWORD, device_id: "0" }
post = ->(path, data) {
uri = URI.join(ENDPOINT, path)
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
req.body = data.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
hash = JSON.parse(res.body)
raise "HTTP error!\n#{res.code} #{res.message}\n#{hash.pretty_inspect}" unless res.code == "200"
hash
}
get = ->(path, token:) {
uri = URI.join(ENDPOINT, path)
req = Net::HTTP::Get.new(uri,
"Content-Type" => "application/json",
"Authorization" => "Bearer #{token}",
)
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
hash = JSON.parse(res.body)
raise "HTTP error!\n#{res.code} #{res.message}\n#{hash.pretty_inspect}" unless res.code == "200"
hash
}
token = post.("/api/auth/login", auth_data).dig("data", "token")
household_id = get.("/api/household", token: token).dig("data", 0, "id")
get.("/api/household/#{household_id}/pet", token: token).fetch("data").each do |pet_data|
id = pet_data.fetch("id")
position_data = get.("/api/pet/#{id}/position", token: token).fetch("data")
name = pet_data.fetch("name")
is_inside = (position_data.fetch("where") == 1)
since = position_data.fetch("since")
puts "#{name} is #{is_inside ? "inside" : "outside"} since #{since}."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment