+ "func": "// Mapping of directives to Home Assistant services\nconst directiveToServiceMapping = {\n TurnOff: \"turn_off\",\n TurnOn: \"turn_on\",\n SetBrightness: \"turn_on\",\n SetColorTemperature: \"turn_on\",\n SetColor: \"turn_on\",\n AdjustBrightness: \"turn_on\"\n};\n\n// Extract metadata from the message, defaulting to an empty object\nconst { domain, entityId } = msg.metadata ?? {};\nconst service = directiveToServiceMapping[msg.payload.directive];\n\n// Set the node status visually in the Node-RED flow\nupdateNodeStatus(service, msg.payload.directive);\n\n// Generate payload data based on the service and message\nconst payloadData = generatePayloadData();\n\n// Construct and return the full payload\nreturn constructPayload(domain, service, payloadData);\n\n// Function definitions below\n\nfunction updateNodeStatus(service, directive) {\n node.status({\n fill: service === 'turn_on' ? 'yellow' : 'grey',\n shape: 'dot',\n text: directive\n });\n}\n\nfunction generatePayloadData() {\n const data = { entity_id: `${domain}.${entityId}` };\n\n if (service === \"turn_on\") {\n Object.assign(data, handleTurnOnConditions());\n }\n\n return data;\n}\n\nfunction handleTurnOnConditions() {\n const data = {};\n if (hasBrightness()) {\n data.brightness_pct = msg.payload.brightness;\n }\n if (isColorModeHSB()) {\n data.xy_color = msg.payload.color_xy;\n }\n if (isTemperatureMode()) {\n data.color_temp = convertKelvinToMireds(msg.payload.colorTemperatureInKelvin);\n }\n return data;\n}\n\nfunction hasBrightness() {\n return msg.payload.brightness !== undefined;\n}\n\nfunction isColorModeHSB() {\n return msg.payload.color_xy !== undefined && msg.payload.lightMode === \"hsb\";\n}\n\nfunction isTemperatureMode() {\n return msg.payload.colorTemperatureInKelvin !== undefined && msg.payload.lightMode === \"temp\";\n}\n\nfunction convertKelvinToMireds(kelvin) {\n // Converts Kelvin to Mireds to comply with Home Assistant's expected units\n return Math.round(1000000 / kelvin);\n}\n\nfunction constructPayload(domain, service, data) {\n return {\n payload: {\n domain,\n service,\n data\n }\n };\n}\n",
0 commit comments