-
-
Save juliancheal/34afbc830bebf58a794df8cd6c3c81ae to your computer and use it in GitHub Desktop.
controll a sonoff-tasmota device via ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Free to use. if you modify it, pls let me know, i might need your code aswell :-) | |
# github: krtschmr | |
# [email protected] | |
# 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