Sha256: dc104319c5eeaa68a5e1b0d5627710318134b0d60a554e933b4aa69d553a9bfe

Contents?: true

Size: 1.94 KB

Versions: 2

Compression:

Stored size: 1.94 KB

Contents

require 'launchy'
require 'faraday'
require 'json'

module NatureRemo
  class Client
    # nature-remo api http client

    def initialize token = nil
      @token = token || get_token
      @client = Faraday.new :url => 'https://api.nature.global'
      @client.headers['Authorization'] = "Bearer #{@token}"
      
    end

    def users
      @client.get do |req|
        req.url '/1/users/me'
      end
    end

    def devices
      @client.get do |req|
        req.url '/1/devices'
      end
    end

    def appliances appliance = nil
      @client.get do |req|
        if appliance.nil?
          req.url '/1/appliances'
        else
          req.url "/1/appliances/#{appliance}/signals"
        end
      end
    end

    def send_signal signal
      @client.post do |req|
        req.url "/1/signals/#{signal}/send"
        req.body = { :name => "#{signal}" }
      end
    end

    def aircon_setting appliance, temp = nil, mode = nil, volume = nil
      @client.post do |req|
        req.url "/1/appliances/#{appliance}/aircon_settings"
        req.body = {
          :temperature => "#{temp}",
          :operation_mode => "#{mode}",
          :air_volume => "#{volume}"
        }
      end
    end

    def events
      JSON.parse(self.devices.body)[0]["newest_events"]
    end

    def get_temp
      self.events["te"]["val"].to_i
    end

    def get_humi
      self.events["hu"]["val"].to_i
    end

    def get_token
      return ENV['NATURE_TOKEN'] if ENV['NATURE_TOKEN']

      begin
        json = JSON(File.read(File.expand_path('~/.nature')))
        return json['token']
      rescue => e
        set_token
      end
    end

    def set_token
      Launchy.open 'https://home.nature.global'
      print 'input your token:'
      token = STDIN.gets.to_s.chomp
      raise "Invalid Token" unless token.length == 87
      puts 'your token >> ~/.nature'
      File.write(File.expand_path('~/.nature'), JSON.dump({token: token}))
      return token
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nature_remo-0.2.3 lib/nature_remo/client.rb
nature_remo-0.2.2 lib/nature_remo/client.rb