Skip to content

Commit

Permalink
Add CCT helpers for HSBType
Browse files Browse the repository at this point in the history
Signed-off-by: Cody Cutrer <cody@cutrer.us>
  • Loading branch information
ccutrer committed Oct 3, 2024
1 parent 866d28e commit 19b3708
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/openhab/core/types/hsb_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ module Types
# {HSBType} is a complex type with constituents for hue, saturation and
# brightness and can be used for color items.
class HSBType < PercentType
if OpenHAB::Core.version >= OpenHAB::Core::V4_0
java_import org.openhab.core.util.ColorUtil
private_constant :ColorUtil
end

# @!constant BLACK
# @return [HSBType]
# @!constant WHITE
Expand Down Expand Up @@ -96,6 +101,14 @@ def new(*args)

super(*args)
end

# Create HSBType from a color temperature
# @param cct [QuantityType, Number] The color temperature (assumed in Kelvin, if not a QuantityType)
# @return [HSBType]
# @since openHAB 4.3
def from_cct(cct)
from_xy(*ColorUtil.kelvin_to_xy((cct | "K").double_value))
end
end

#
Expand Down Expand Up @@ -175,6 +188,13 @@ def to_s
# @!method to_xy
# Convert to the xyY values representing this object's color in CIE XY color model
# @return [[PercentType, PercentType, PercentType]]

# @!attribute [r] cct
# @return [QuantityType] The color temperature in Kelvin
# @since openHAB 4.3
def cct
ColorUtil.xy_to_kelvin(to_xy[0..1].map { |x| x.double_value / 100 }) | "K"
end
end
end
end
Expand Down
27 changes: 27 additions & 0 deletions spec/openhab/core/types/hsb_type_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
# frozen_string_literal: true

RSpec.describe OpenHAB::Core::Types::HSBType do
describe ".from_cct", if: OpenHAB::Core.version >= OpenHAB::Core::V4_3 do
it "works with an integer" do
warm_white = HSBType.from_cct(2700)
expect(warm_white.hue.to_f).to be_within(0.01).of(38.51)
expect(warm_white.saturation.to_f).to be_within(0.01).of(53.86)
expect(warm_white.brightness).to eq 100
# slight loss in the round-trip
expect(warm_white.cct.to_i).to be 2699
end

it "works with a K quantity" do
warm_white = HSBType.from_cct(2700 | "K")
expect(warm_white.hue.to_f).to be_within(0.01).of(38.51)
expect(warm_white.saturation.to_f).to be_within(0.01).of(53.86)
expect(warm_white.brightness).to eq 100
expect(warm_white.cct.to_i).to be 2699
end

it "works with a mired quantity" do
warm_white = HSBType.from_cct(370 | "mired")
expect(warm_white.hue.to_f).to be_within(0.01).of(38.51)
expect(warm_white.saturation.to_f).to be_within(0.01).of(53.86)
expect(warm_white.brightness).to eq 100
expect(warm_white.cct.to_i).to be 2699
end
end

it "is inspectable" do
expect(HSBType.new.inspect).to eql "0 °,0%,0%"
end
Expand Down

0 comments on commit 19b3708

Please sign in to comment.