Skip to content

Instantly share code, notes, and snippets.

@OkayDave
Last active May 26, 2024 15:57
Show Gist options
  • Save OkayDave/dbc531a5c55c60e5c14c7d96b006a9c1 to your computer and use it in GitHub Desktop.
Save OkayDave/dbc531a5c55c60e5c14c7d96b006a9c1 to your computer and use it in GitHub Desktop.
DIY Philips Hue Sync for Linux
#!/bin/env ruby
# frozen_string_literal: true
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'hue', '~> 0.2'
gem 'color', '~> 1.8'
end
IMPORT = `which import`.chomp
MONITOR_X_OFFSET = 2560
MONITOR_Y_OFFSET = 0
REFRESH_RATE = 2.0
def import_command(x_offset, y_offset)
[
IMPORT,
'-silent',
'-window root',
"-crop 1x1+#{x_offset.to_i}+#{y_offset.to_i}",
'-depth 8',
'txt:-'
].join(' ')
end
def pixel_colour(x_offset, y_offset)
m = `#{import_command(x_offset, y_offset)}`.match(/\((\d+),(\d+),(\d+)\)/)
return @pixel_colour = { r: m[1].to_i, g: m[2].to_i, b: m[3].to_i } if m
return @pixel_colour unless @pixel_colour.nil?
raise 'No initial pixel data'
end
client = Hue::Client.new
play_lights = []
target_pixels = []
screen_res = `xrandr | head -n 1`.match(/current (\d+) x (\d+)/)
raise 'No screen resolution data' unless screen_res
client.lights.each do |light|
play_lights << light if light.name =~ /play/i
light.on!
end
target_pixels[0] = [
(
(screen_res[1].to_i - MONITOR_X_OFFSET) / 3
) + MONITOR_X_OFFSET,
(
(screen_res[2].to_i - MONITOR_Y_OFFSET) / 2
) + MONITOR_Y_OFFSET
]
target_pixels[1] = [
(
(screen_res[1].to_i - MONITOR_X_OFFSET) * (2 / 3.0)
).to_i + MONITOR_X_OFFSET,
target_pixels[0][1]
]
begin
loop do
play_lights.each_with_index do |light, index|
rgb = pixel_colour(target_pixels[index][0], target_pixels[index][1])
xyz = Color::RGB.new(rgb[:r], rgb[:g], rgb[:b]).to_xyz
x = xyz[:x] / (xyz[:x] + xyz[:y] + xyz[:z])
y = xyz[:y] / (xyz[:x] + xyz[:y] + xyz[:z])
light.set_state({ xy: [x, y] }, 400)
sleep REFRESH_RATE
end
end
rescue SystemExit, Interrupt, StandardError => e
puts e.message
play_lights.each(&:off!)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment