Sha256: f8be79f7d030353630694ed12d55de5bd74aa0beed052ece7939265b9a260be1

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

require "tplink_smarthome_api/version"
require 'json'

class TplinkSmarthomeApi
  attr_accessor :ip_address, :verbose

  def initialize(ip_address, verbose: false)
    raise RuntimeError unless self.class.dependencies_met?
    @ip_address = ip_address
    @verbose = verbose
  end

  def power_on(delay: 0)
    switch_power true, delay: delay
    self
  end

  def power_off(delay: 0)
    switch_power false, delay: delay
    self
  end

  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

  def reboot(delay: 1)
    payload = { system: {
                reboot: { delay: delay } } }.to_json
    send_command payload
  end

  def self.dependencies_met?
    self.smarthome_cli_available?
  end

  private

  def send_command(payload)
    `tplink-smarthome-api sendCommand #{ip_address} '#{payload}'`
    self
  end

  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

  def log(payload)
    puts payload if verbose
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tplink_smarthome_api-0.3.1 lib/tplink_smarthome_api.rb