Skip to content

Commit

Permalink
Define format method for HSBType (openhab#3165)
Browse files Browse the repository at this point in the history
Pattern %s will match <hue>,<saturation>,<brightness>
Pattern %hsb% will match <hue>,<saturation>,<brightness>
Pattern %rgb% will match <red>,<green>,<blue>

Related to discussion in openhab/openhab-webui#427

Signed-off-by: Laurent Garnier <lg.hc@free.fr>
  • Loading branch information
lolodomo authored Nov 26, 2022
1 parent f0875a4 commit 27b847f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ public class HSBType extends PercentType implements ComplexType, State, Command
private static final float RGB2XY[][] = { { 0.4124f, 0.3576f, 0.1805f }, { 0.2126f, 0.7152f, 0.0722f },
{ 0.0193f, 0.1192f, 0.9505f } };

private static final String UNIT_HSB = "%hsb%";
private static final String UNIT_RGB = "%rgb%";

protected BigDecimal hue;
protected BigDecimal saturation;

Expand Down Expand Up @@ -243,6 +246,21 @@ public String toFullString() {
return getHue() + "," + getSaturation() + "," + getBrightness();
}

@Override
public String format(String pattern) {
String formatPattern = pattern;
String val = getHue() + "," + getSaturation() + "," + getBrightness();
if (pattern.contains(UNIT_HSB)) {
formatPattern = pattern.replace(UNIT_HSB, "%s");
} else if (pattern.contains(UNIT_RGB)) {
formatPattern = pattern.replace(UNIT_RGB, "%s");
PercentType[] rgb = toRGB();
val = convertPercentToByte(rgb[0]) + "," + convertPercentToByte(rgb[1]) + ","
+ convertPercentToByte(rgb[2]);
}
return String.format(formatPattern, val);
}

@Override
public int hashCode() {
int tmp = 10000 * getHue().hashCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ public void testEquals() {
assertTrue(hsb1.equals(hsb2));
}

@Test
public void testFormat() {
HSBType hsb = new HSBType("316,69,47");

assertEquals("color 316,69,47", hsb.format("color %hsb%"));
assertEquals("color 119,37,97", hsb.format("color %rgb%"));
assertEquals("color 316,69,47", hsb.format("color %s"));
}

@Test
public void testHsbToRgbConversion() {
compareHsbToRgbValues("0,100,100", 255, 0, 0); // red
Expand Down

0 comments on commit 27b847f

Please sign in to comment.