Define format method for HSBType (#3165)

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>
This commit is contained in:
lolodomo 2022-11-26 16:00:54 +01:00 committed by GitHub
parent f0875a46f2
commit 27b847f40c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 0 deletions

View File

@ -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;
@ -243,6 +246,21 @@ public class HSBType extends PercentType implements ComplexType, State, Command
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();

View File

@ -41,6 +41,15 @@ public class HSBTypeTest {
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