Skip to content

Instantly share code, notes, and snippets.

@kirel
Created July 25, 2013 06:32
Show Gist options
  • Select an option

  • Save kirel/6077354 to your computer and use it in GitHub Desktop.

Select an option

Save kirel/6077354 to your computer and use it in GitHub Desktop.
require 'bundler/setup'
require 'rmagick'
require 'awesome_print'
require 'benchmark'
require 'httparty'
require 'json'
IP = '192.168.1.144'
USER = 'hackedkirel'
class Light
include HTTParty
format :json
base_uri "#{IP}/api/#{USER}/"
#debug_output STDOUT
def initialize id
@id = id
end
def off
state on: false
self
end
def on
state on: true
self
end
def state args
self.class.put "/lights/#{@id}/state", body: args.to_json
self
end
end
IMAGE = 'capture.jpg'
class Borders
def initialize img
@img = img
@width = 20
end
def left
@img.crop 0, 0, @width, @img.rows
end
def top
@img.crop 0, 0, @img.columns, @width
end
def right
@img.crop @img.columns - @width, 0, @width, @img.rows
end
end
def avg img
img.scale(1,1).pixel_color(0,0)
end
# Hue 0-360 / 0-65535 ~> /360*65535.round
# sat 0-100 / 0-255 ~> /100*255.round
# B 0-100
def pixel_to_hue_sat pixel
h, s, l = pixel.to_hsla
{ hue: (h/360*65535).round, sat: s.round, bri: l.round }
end
left_light = Light.new(1)
right_light = Light.new(2)
center_light = Light.new(3)
loop do
b = Benchmark.measure do
`screencapture #{IMAGE} 2&>1`
img = Magick::Image.read(IMAGE).first
# b.left.scale(1, 1).write('avg.jpg')
borders = Borders.new img
# borders.left.write('left.jpg')
# borders.right.write('right.jpg')
# borders.top.write('top.jpg')
Thread.new do
begin
left_light.state pixel_to_hue_sat(avg(borders.left)).merge on: true, transitiontime: 1
rescue
puts $!
end
end
Thread.new do
begin
right_light.state pixel_to_hue_sat(avg(borders.right)).merge on: true, transitiontime: 1
rescue
puts $!
end
end
Thread.new do
begin
center_light.state pixel_to_hue_sat(avg(borders.top)).merge on: true, transitiontime: 1
rescue
puts $!
end
end
#sleep 0.02
end
puts "#{1/b.real} fps"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment