forked from openhab/openhab-addons
/
MySensorsRGBWTypeConverter.java
73 lines (58 loc) · 2.45 KB
/
MySensorsRGBWTypeConverter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/** Copyright (c) 2010-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.mysensors.converter;
import java.awt.Color;
import org.eclipse.smarthome.core.library.types.HSBType;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used to convert a String from an incoming MySensors message to a HSBType
*
* @author Tim Oberföll
*
*/
public class MySensorsRGBWTypeConverter implements MySensorsTypeConverter {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Override
public State fromString(String s) {
int r = Integer.parseInt(s.substring(0, 1), 16);
int g = Integer.parseInt(s.substring(2, 3), 16);
int b = Integer.parseInt(s.substring(4, 5), 16);
HSBType hsbValue = HSBType.fromRGB(r, g, b);
return hsbValue;
}
@Override
public String fromCommand(Command value) {
String r = "", g = "", b = "", w = "";
if(value instanceof HSBType) {
HSBType hsbValue = (HSBType) value;
Color color = Color.getHSBColor(hsbValue.getHue().floatValue() / 360, hsbValue.getSaturation().floatValue() / 100, hsbValue.getBrightness().floatValue() / 100);
int redValue = color.getRed();
int greenValue = color.getGreen();
int blueValue = color.getBlue();
int whiteValue = Math.min(redValue, Math.min(greenValue, blueValue));
r = Integer.toHexString(redValue);
g = Integer.toHexString(greenValue);
b = Integer.toHexString(blueValue);
w = Integer.toHexString(whiteValue);
if(r.length() == 1)
r = "0" + r;
if(g.length() == 1)
g = "0" + g;
if(b.length() == 1)
b = "0" + b;
if(w.length() == 1)
w = "0" + w;
}
logger.debug("Converting RGBW Int to Hex: R {}, G {}, B {}, W {}", r, g, b, w);
String hexString = r.concat(g).concat(b).concat(w);
return hexString;
}
}