Skip to content

Instantly share code, notes, and snippets.

@syxanash
Last active June 23, 2024 17:25
Show Gist options
  • Save syxanash/b7aee45517cc8ca2f13c479c57b85b50 to your computer and use it in GitHub Desktop.
Save syxanash/b7aee45517cc8ca2f13c479c57b85b50 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'faye/websocket'
require 'net/http'
require 'eventmachine'
require 'rest-client'
SMART_BULB = {
ip: 'shelly_ip_addr',
user: 'shelly_user',
password: 'shelly_password'
}
def shelly_request(url)
RestClient::Request.new(
:method => 'get',
:url => url,
:user => SMART_BULB[:user],
:password => SMART_BULB[:password],
).execute
end
def up?(server, port)
http = Net::HTTP.start(server, port, { open_timeout: 5, read_timeout: 5 })
response = http.head('/')
response.code == '401'
rescue Timeout::Error, SocketError
false
end
def blink_on_load(current_status)
for i in 1..6 do
shelly_request("http://#{SMART_BULB[:ip]}/light/0?turn=on&brightness=#{i * 10}")
end
shelly_request("http://#{SMART_BULB[:ip]}/light/0?turn=#{current_status}&brightness=10")
end
def blink_on_disconnect(current_status)
shelly_request("http://#{SMART_BULB[:ip]}/light/0?turn=on&brightness=5")
sleep 0.1
shelly_request("http://#{SMART_BULB[:ip]}/light/0?turn=#{current_status}&brightness=10")
end
unless up?(SMART_BULB[:ip], '80')
puts '[!] Issues connecting to Shelly Light Bulb'
exit 1
end
total_users = nil
bulb_status = nil
EM.run {
ws = Faye::WebSocket::Client.new('wss://lightbulb.url')
ws.on :open do |event|
puts 'Connected to Litebulb!'
end
ws.on :message do |event|
ws_data = event.data
if ws_data.start_with?('USERS')
new_users = ws_data.match(%r{^USERS\:(.*?)$})[1]
unless total_users.nil?
if new_users > total_users
blink_on_load(bulb_status)
else
blink_on_disconnect(bulb_status)
end
end
total_users = new_users
end
if ws_data.start_with?('BULB')
parsed_status = ws_data.match(%r{^BULB\:(.*?)$})[1]
bulb_status = parsed_status == '1' ? 'on' : 'off'
shelly_request("http://#{SMART_BULB[:ip]}/light/0/?turn=#{bulb_status}")
puts "Bulb has been turned #{bulb_status}"
end
end
ws.on :close do |_event|
# p [:close, event.code, event.reason]
ws = nil
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment