From 6f8969c6a3722750a9cf25010922a0f8caed0905 Mon Sep 17 00:00:00 2001 From: Laurent Garnier Date: Sat, 19 Nov 2022 11:14:40 +0100 Subject: [PATCH] Define format method for HSBType Pattern %s will match ,, Pattern %hsb% will match ,, Pattern %rgb% will match ,, Related to discussion in openhab/openhab-webui#427 Signed-off-by: Laurent Garnier --- .../openhab/core/library/types/HSBType.java | 18 ++++++++++++++++++ .../core/library/types/HSBTypeTest.java | 9 +++++++++ 2 files changed, 27 insertions(+) diff --git a/bundles/org.openhab.core/src/main/java/org/openhab/core/library/types/HSBType.java b/bundles/org.openhab.core/src/main/java/org/openhab/core/library/types/HSBType.java index 1d5733aa627..ab638358483 100644 --- a/bundles/org.openhab.core/src/main/java/org/openhab/core/library/types/HSBType.java +++ b/bundles/org.openhab.core/src/main/java/org/openhab/core/library/types/HSBType.java @@ -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 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(); diff --git a/bundles/org.openhab.core/src/test/java/org/openhab/core/library/types/HSBTypeTest.java b/bundles/org.openhab.core/src/test/java/org/openhab/core/library/types/HSBTypeTest.java index bfa3321b7a9..85349538c13 100644 --- a/bundles/org.openhab.core/src/test/java/org/openhab/core/library/types/HSBTypeTest.java +++ b/bundles/org.openhab.core/src/test/java/org/openhab/core/library/types/HSBTypeTest.java @@ -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