Zigbee2mqtt revisited: No more ugly transformations

As this thread is currently the best source for zigbee2mqtt-examples here is my solution to connect Lidl bulbs (but should work with other manufacturers too).
One problem is that the range of the brightness is hardware specific and not a percentage value like in OH. And there is a bug in z2m with hsb-payloads.

Solution:
For the brightness item there is a (not very well documented) feature (brightness_percent) to let z2m do the conversion.
Then for the color we need a transformation and we need the attribute_and_json option within the z2m-config enabled.

Here the example:
First the item-definition in file-format:

Thing mqtt:topic:Lidl1 "Lidl1" (mqtt:broker:MosquittoMqttBroker) { Channels:
  Type switch : state "State"           [ stateTopic = "zigbee2mqtt/Lidl1/state",      commandTopic = "zigbee2mqtt/Lidl1/set",             on="ON", off="OFF" ]
  Type color : color "Color"            [ stateTopic = "zigbee2mqtt/Lidl1/color-hsb",  commandTopic = "zigbee2mqtt/Lidl1/set" , transformationPatternOut="JS:color_hsb_fix.js"]
  Type dimmer : brightness "brightness" [ stateTopic = "zigbee2mqtt/Lidl1/brightness_percent", commandTopic = "zigbee2mqtt/Lidl1/set/brightness_percent" ]
  Type datetime : last_seen "last_seen" [ stateTopic = "zigbee2mqtt/Lidl1/last_seen" ]    
} 

Then the file transformation color_hsb_fix.js which has to be placed in the transform-folder:

(function(color){
  //var log = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.fix_hsb");
  //log.info("color_in: " + color) ;
  var bright = Number(color.split(/[,:]/)[2]) * 2.54;

  var returnVal = '{"brightness":' + bright.toFixed(0) + ',"color":{"h":' + Number(color.split(/[,:]/)[0]) + ',"s":' + Number(color.split(/[,:]/)[1]) + '}}';    
  return returnVal;
})(input)

The point here is to not send hsb (not working in z2m) but to send the brightness and for the color only “h” (Hue) and “s” (Saturation) in one json-payload.
Took me a while to figure this out, so I hope this may help somebody else.

4 Likes