Sha256: 7b1d5ec31ad9f8faedf2ec6ec359521f4c42ab7dd95f63e749d7a2073274cf88

Contents?: true

Size: 1.27 KB

Versions: 1

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true

module Switchbot
  class Client
    API_ENDPOINT = 'https://api.switch-bot.com'

    def initialize(token)
      @token = token
    end

    def devices
      request(
        http_method: :get,
        endpoint: 'v1.0/devices'
      )
    end

    def status(device_id:)
      request(
        http_method: :get,
        endpoint: "/v1.0/devices/#{device_id}/status"
      )
    end

    def commands(device_id:, command:, parameter: 'default', command_type: 'command')
      request(
        http_method: :post,
        endpoint: "/v1.0/devices/#{device_id}/commands",
        params: {
          command: command,
          parameter: parameter,
          commandType: command_type
        }
      )
    end

    private

    def headers
      {
        'User-Agent' => "Switchbot v#{Switchbot::VERSION} (https://github.com/ytkg/switchbot)",
        'Authorization' => @token
      }
    end

    def connection
      @connection ||= Faraday.new(url: API_ENDPOINT, headers: headers) do |conn|
        conn.request :json
      end
    end

    def request(http_method:, endpoint:, params: {})
      response = connection.public_send(http_method, endpoint, params)
      JSON.parse(response.body).deep_transform_keys(&:underscore).deep_symbolize_keys
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
switchbot-0.1.0 lib/switchbot/client.rb