Skip to content

Instantly share code, notes, and snippets.

@krtschmr
Created September 12, 2017 09:57
Show Gist options
  • Save krtschmr/1157f32bee124e69901bc4a45cfb37cf to your computer and use it in GitHub Desktop.
Save krtschmr/1157f32bee124e69901bc4a45cfb37cf to your computer and use it in GitHub Desktop.
controll a sonoff-tasmota device via ruby
# Free to use. if you modify it, pls let me know, i might need your code aswell :-)
# github: krtschmr
# tim@krtschmr.de
# USAGE
# Straightforward
# Sonoff.on!("192.168.1.53")
# Sonoff.off!("192.168.1.53")
# Sonoff.restart!("192.168.1.53") # turns off, waits 3 seconds and turns on
#
# or control via instance
#
# s = Sonoff.new(192.168.1.53)
# s.state # returns current state
# s.read_state # updates the state
# s.on! # turns on
# s.off! # turns off
# s.restart! # turns off, waits 3 seconds and turns on
class Sonoff
def self.on!(ip)
new(ip, skip_init: true).on!
end
def self.off!(ip)
new(ip, skip_init: true).off!
end
def self.restart!(ip)
new(ip, skip_init: true).restart!
end
@@ip = nil
attr_accessor :state
def initialize(ip, args={})
@@ip = ip
self.state = "unknown"
read_state unless args[:skip_init]
end
def read_state
status = eval(send_cmd("status"))
begin
if status[:Status][:Power] == 1
self.state = "on"
else
self.state = "off"
end
rescue
self.state = "unknown"
end
end
def on!
send_cmd "Power%20On"
self.state = "on"
end
def off!
send_cmd "Power%20Off"
self.state = "off"
end
def restart!
off!; sleep(3); on!;
end
def ip
@@ip
end
private
def send_cmd(cmd)
@@agent ||= Mechanize.new
url = "http://#{@@ip}/cm?cmnd=#{cmd}"
page = @@agent.get(url).body
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment