Skip to content

Instantly share code, notes, and snippets.

@noelhibbard
Last active April 9, 2024 07:25
Show Gist options
  • Save noelhibbard/0241c82b9dd2749edc553e49b661fa9e to your computer and use it in GitHub Desktop.
Save noelhibbard/0241c82b9dd2749edc553e49b661fa9e to your computer and use it in GitHub Desktop.
homebridge-mqttthing codec for IKEA bulbs
let states = []
module.exports = {
init: function () {
return {
encode(message, info) {
let { topic } = info
let state = states.find(_state => _state.topic === topic.replace(/\/set$/, ''))
if (!state) return
switch (info.property) {
case 'on':
state.state = message
return JSON.stringify({ state: message })
case 'brightness':
state.brightness = brightnessToZigbee(message)
return JSON.stringify({
state: state.state,
brightness: state.brightness,
})
case 'HSV':
let [hue, saturation, brightness] = message.split(',').map(Number)
Object.assign(state, { hue, saturation, brightness: brightnessToZigbee(brightness) })
return JSON.stringify({
state: state.state,
brightness: state.brightness,
color: { hue, saturation },
})
}
},
decode(message, info) {
let { topic } = info
let { state, color, brightness } = JSON.parse(message)
let hue = color?.hue || 0
let saturation = color?.saturation || 0
let decodedBrightness = brightnessFromZigbee(brightness)
upsertState({ topic: topic.replace(/\/set$/, ''), state, hue, saturation, brightness: decodedBrightness })
switch (info.property) {
case 'on':
return state
case 'brightness':
return decodedBrightness
case 'HSV':
return `${hue},${saturation},${decodedBrightness}`
}
}
}
}
}
function upsertState(state) {
let savedState = states.find(_state => _state.topic === state.topic)
savedState ? Object.assign(savedState, state) : states.push(state)
}
function brightnessToZigbee(brightness) {
return Math.round(parseInt(brightness) / 100 * 254)
}
function brightnessFromZigbee(brightness) {
return Math.round(parseInt(brightness) / 254 * 100)
}
@noelhibbard
Copy link
Author

This codec is intended to be used with an IKEA bulb paired with zigbee2MQTT. Make sure to go into the device settings tab for the bulb in zigbee2MQTT and check the "retain" check box.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment