class TplinkSmarthomeApi

Constants

VERSION

Attributes

ip_address[RW]
verbose[RW]

Public Class Methods

dependencies_met?() click to toggle source
# File lib/tplink_smarthome_api.rb, line 39
def self.dependencies_met?
  self.smarthome_cli_available?
end
new(ip_address, verbose: false) click to toggle source
# File lib/tplink_smarthome_api.rb, line 7
def initialize(ip_address, verbose: false)
  raise RuntimeError unless self.class.dependencies_met?
  @ip_address = ip_address
  @verbose = verbose
end

Private Class Methods

smarthome_cli_available?() click to toggle source
# File lib/tplink_smarthome_api.rb, line 50
def self.smarthome_cli_available?
  `which tplink-smarthome-api`
  return true if $?.exitstatus == 0

  puts "[#{Time.now}] tplink-smarthome-api could not be found."
  puts "[#{Time.now}] To install it, run: `npm install -g tplink-smarthome-api`"
  false
end

Public Instance Methods

power_off(delay: 0) click to toggle source
# File lib/tplink_smarthome_api.rb, line 18
def power_off(delay: 0)
  switch_power false, delay: delay
  self
end
power_on(delay: 0) click to toggle source
# File lib/tplink_smarthome_api.rb, line 13
def power_on(delay: 0)
  switch_power true, delay: delay
  self
end
reboot(delay: 1) click to toggle source
# File lib/tplink_smarthome_api.rb, line 33
def reboot(delay: 1)
  payload = { system: {
              reboot: { delay: delay } } }.to_json
  send_command payload
end
switch_power(value, delay: 0) click to toggle source
# File lib/tplink_smarthome_api.rb, line 23
def switch_power(value, delay: 0)
  sleep(delay)
  log("[#{Time.now}] Switching power #{value ? 'on' : 'off'} for #{ip_address}...")
  payload = { system: {
              set_relay_state: { state: value ? 1 : 0 }
            } }.to_json
  send_command payload
  self
end

Private Instance Methods

log(payload) click to toggle source
# File lib/tplink_smarthome_api.rb, line 59
def log(payload)
  puts payload if verbose
end
send_command(payload) click to toggle source
# File lib/tplink_smarthome_api.rb, line 45
def send_command(payload)
  `tplink-smarthome-api sendCommand #{ip_address} '#{payload}'`
  self
end