Zigbee2mqtt revisited: No more ugly transformations

Well my previous “solution” was bad as it does not convert the brightness part to the correct values as @anon71759204 pointed out earlier :wink: So here is what i came up with which now everything is working as expected: (Also most parts are c + p from other community members which i’m really glad that they share thier findings with us.)

openHAB channel config:

channels:
  - id: LEDKochinselXY
    channelTypeUID: mqtt:color
    label: LEDKochinselXY
    description: null
    configuration:
      commandTopic: zigbee2mqtt/LEDKochinsel/set
      colorMode: XYY
      transformationPatternOut: JS:zigbeeColorOUT.js
      formatBeforePublish: "%"
      stateTopic: zigbee2mqtt/LEDKochinsel
      transformationPattern: JS:zigbeeColorIN.js

transformation scripts:

zigbeeColorOUT.js

(function(color){
	// convert 100% to 254 Steps of brightness
	var bright = Number(color.split(/[,:]/)[2]) * 2.54;
	// example output to mqtt: {"brightness":239,"color":{"x":0.601297,"y":0.311017}}
	return '{"brightness":' + bright.toFixed(0) + ',"color":{"x":' + color.split(/[,:]/)[0] + ',"y":' + color.split(/[,:]/)[1] + '}}';
})(input)

zigbeeColorIN.js

// example input: {"brightness":50,"color":{"hue":359,"saturation":100,"x":0.6942,"y":0.2963},"color_mode":"xy","color_temp":158}
(function(color){
	// convert 254 Steps to 100% of brightness
	var bright = Number(color.split(/[,:]/)[1]) / 2.54;
	// example output to openHAB: x,y,brightness - f.e.: 0.6942,0.2963,50
	return color.split(/[,:]/)[8] + "," + color.split(/[,:}]/)[10] + "," + bright.toFixed(0);
})(input)
8 Likes