Skip to content

Commit

Permalink
Add hex to light
Browse files Browse the repository at this point in the history
  • Loading branch information
soffes committed Jan 3, 2024
1 parent 4297055 commit e35ffbd
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions hue.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Gem::Specification.new do |spec|
spec.required_ruby_version = '>= 2.1.0'
spec.add_dependency 'thor'
spec.add_dependency 'json'
spec.add_dependency 'color_conversion'
spec.add_development_dependency 'minitest', '~> 5.0'
spec.add_development_dependency 'webmock'
end
28 changes: 26 additions & 2 deletions lib/hue/light.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'color_conversion'

module Hue
class Light
include TranslateKeys
Expand All @@ -21,13 +23,13 @@ class Light
# Both 0 and 65535 are red, 25500 is green and 46920 is blue.
attr_reader :hue

# Saturation of the light. 255 is the most saturated (colored)
# Saturation of the light. 254 is the most saturated (colored)
# and 0 is the least saturated (white).
attr_reader :saturation

# Brightness of the light. This is a scale from the minimum
# brightness the light is capable of, 0, to the maximum capable
# brightness, 255. Note a brightness of 0 is not off.
# brightness, 254. Note a brightness of 0 is not off.
attr_reader :brightness

# The x coordinate of a color in CIE color space. Between 0 and 1.
Expand Down Expand Up @@ -140,6 +142,28 @@ def refresh
unpack(json)
end

def hex
ColorConversion::Color.new(h: hue, s: saturation, b: brightness).hex
end

def hex=(hex)
hex = "##{hex}" unless hex.start_with?('#')
hsb = ColorConversion::Color.new(hex).hsb

# Map values from standard HSB to what Hue wants and update state
state = {
hue: ((hsb[:h].to_f / 360.0) * 65535.0).to_i,
saturation: ((hsb[:s].to_f / 100.0) * 254.0).to_i,
brightness: ((hsb[:b].to_f / 100.0) * 254.0).to_i
}

set_state(state)

@hue = state[:hue]
@saturation = state[:saturation]
@brightness = state[:brightness]
end

private

KEYS_MAP = {
Expand Down

0 comments on commit e35ffbd

Please sign in to comment.