class TPLink::API

Talk to TPLink's API. This class is use internally. You should not need to call it. @!visibility private

Constants

DEFAULT_HEADERS

@!visibility private

DEFAULT_PARAMS

@!visibility private

@!visibility private

Public Class Methods

new(opts = {}) click to toggle source

@!visibility private

# File lib/tp_link/api.rb, line 46
def initialize(opts = {})
  @config = Config.new(opts)
  @token = nil
  @device_list = []
end

Public Instance Methods

device_list() click to toggle source
# File lib/tp_link/api.rb, line 61
def device_list
  @device_list if @device_list
  response = TPLINK_API.post do |req|
    req.params['token'] = token
    req.body = { method: 'getDeviceList' }.to_json
  end
  @device_list = parse_response(response)['deviceList']
end
send_data(device, data) click to toggle source
# File lib/tp_link/api.rb, line 70
def send_data(device, data)
  conn = data_connection(device)
  res = conn.post do |req|
    req.body = { method: 'passthrough',
                 params: { deviceId: device.id,
                           requestData: data.to_json } }.to_json
  end
  parse_response(res)
end
token(regen = false) click to toggle source
# File lib/tp_link/api.rb, line 52
def token(regen = false)
  return @token if @token && regen == false
  response = TPLINK_API.post do |req|
    req.body = { method: 'login', url: 'https://wap.tplinkcloud.com',
                 params: @config.to_hash }.to_json
  end
  @token = parse_response(response)['token']
end

Private Instance Methods

data_connection(device) click to toggle source
# File lib/tp_link/api.rb, line 82
def data_connection(device)
  Faraday.new(device.url) do |c|
    c.request :json
    c.response :json, content_type: /\bjson$/i
    c.adapter Faraday.default_adapter
    c.params['token'] = token
    c.headers.merge!(DEFAULT_HEADERS)
  end
end
parse_response(res) click to toggle source
# File lib/tp_link/api.rb, line 92
def parse_response(res)
  raise TPLink::TPLinkCloudError, 'Generic TPLinkCloud Error' unless res.success?
  response = res.body
  raise TPLink::DeviceOffline if response['error_code'].to_i == -20_571
  raise TPLink::TPLinkCloudError, 'TPLinkCloud API Error' \
    unless response['error_code'].to_i.zero?
  raise TPLink::TPLinkCloudError, 'No respone data' \
    unless res.body['result']
  if response['result'].key?('responseData') && \
     response['result']['responseData'].class == String
    response['result']['responseData'] = \
      JSON.parse(response['result']['responseData'])
  end
  response['result']
end