{"version":3,"file":"XyColorControl.cjs","sources":["../../../../src/services/ESPRMMatterHelpers/XyColorControl.ts"],"sourcesContent":["/*\n * SPDX-FileCopyrightText: 2026 Espressif Systems (Shanghai) CO LTD\n *\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * XY-compound color backing for hue/saturation params on XY-only lights\n * (adapted to this SDK's inline-param model).\n *\n * A hue or saturation VALUE is a function of the (CurrentX, CurrentY) pair —\n * decoding a single attribute report is meaningless on its own — and a WRITE\n * needs the sibling component's current value to build the (X, Y) pair\n * `MoveToColor` requires. Registry resolvers are stateless `(rawValue) →\n * value` hooks with no node/endpoint identity, so the cross-attribute state\n * lives here instead, per `(node instance, endpointId)`.\n *\n * Lifetime: the cache is weakly keyed by the {@link ESPRMMatterNode} object\n * the app holds (params already reference their node through a `WeakRef`), so\n * it is collected together with the node — dropping a node, removing it from\n * a fabric or switching fabrics needs no SDK-side eviction hook. Two node\n * instances for the same physical node keep independent caches; writes take\n * hue and saturation from the sibling params first and use the cache only\n * when a param has no value.\n *\n * Ordering: reads and writes on one endpoint are serialised through a\n * per-endpoint queue. A write derives its pair from the state as it stands\n * when the write actually runs, so two sliders (hue, then saturation) dragged\n * in quick succession compose instead of the second `MoveToColor` reverting\n * the first.\n *\n * Consumed by {@link ESPRMMatterDeviceParam.setValue} (`MoveToColor` invoke\n * from the edited component plus the sibling's current value) and\n * {@link ESPRMMatterDeviceParam.getValue} (pair read). Subscription-report\n * pairing stays with the consumer that routes reports — this SDK's\n * subscription channel is node-blind, so apps that re-route raw\n * `cluster_768_attr_3/4` frames pair them with {@link matterXyToHueSaturation}.\n */\n\nimport type { ESPRMMatterNode } from \"../../ESPRMMatterNode\";\nimport type { ESPRMMatterDeviceParam } from \"../../ESPRMMatterDeviceParam\";\nimport { executeMatterControl } from \"../ESPMatterTransport\";\nimport {\n  MatterControlOperations,\n  MatterXyColorControl,\n} from \"../../utils/constants\";\nimport {\n  hueSaturationToMatterXy,\n  matterXyToHueSaturation,\n} from \"../../utils/colorXy\";\n\ninterface XyColorState {\n  /** Last known CurrentX/CurrentY wire values (from reads or writes). */\n  rawX?: number;\n  rawY?: number;\n  /** Tail of the endpoint's operation queue; never rejects. */\n  queue: Promise<unknown>;\n}\n\n/**\n * Per-node endpoint state. Weakly keyed so an entry lives exactly as long as\n * the node object; the inner map is bounded by the node's endpoint count.\n */\nlet xyStateByNode = new WeakMap<ESPRMMatterNode, Map<number, XyColorState>>();\n\nfunction stateFor(node: ESPRMMatterNode, endpointId: number): XyColorState {\n  let byEndpoint = xyStateByNode.get(node);\n  if (!byEndpoint) {\n    byEndpoint = new Map();\n    xyStateByNode.set(node, byEndpoint);\n  }\n  let state = byEndpoint.get(endpointId);\n  if (!state) {\n    state = { queue: Promise.resolve() };\n    byEndpoint.set(endpointId, state);\n  }\n  return state;\n}\n\n/**\n * Drops all cached XY color state for every node. Not required for normal\n * operation (entries follow their node's lifetime); useful in tests and when\n * an app wants a hard reset, e.g. on logout.\n */\nexport function clearXyColorStateMemory(): void {\n  xyStateByNode = new WeakMap();\n}\n\n/**\n * Runs `task` once every earlier read/write queued on the endpoint has\n * settled, and makes later operations wait for it in turn. A failed task does\n * not block the queue.\n */\nfunction serializeOnEndpoint<T>(\n  state: XyColorState,\n  task: () => Promise<T>,\n): Promise<T> {\n  const run = state.queue.then(task);\n  state.queue = run.catch(() => undefined);\n  return run;\n}\n\n/** The endpoint's XY-backed sibling params on the node's device model. */\nfunction xyColorParamsFor(\n  node: ESPRMMatterNode,\n  endpointId: number,\n): ESPRMMatterDeviceParam[] {\n  const params: ESPRMMatterDeviceParam[] = [];\n  for (const device of node.nodeConfig?.devices ?? []) {\n    for (const param of device.params ?? []) {\n      const matterParam = param as ESPRMMatterDeviceParam;\n      if (\n        matterParam.xyColorComponent !== undefined &&\n        matterParam.endpointId === endpointId\n      ) {\n        params.push(matterParam);\n      }\n    }\n  }\n  return params;\n}\n\n/**\n * MoveToColor command fields (tags 0–4) in the Matter data-value dictionary\n * shape the native control bridge consumes (TLV encoding happens natively) —\n * the same wire convention app registry resolvers use for their invoke\n * payloads.\n */\nfunction moveToColorCommandFields(\n  colorX: number,\n  colorY: number,\n): Record<string, unknown> {\n  const unsignedField = (contextTag: number, value: number) => ({\n    contextTag,\n    data: { type: \"UnsignedInteger\", value },\n  });\n  return {\n    type: \"Structure\",\n    value: [\n      unsignedField(0, colorX),\n      unsignedField(1, colorY),\n      unsignedField(2, 0), // TransitionTime\n      unsignedField(3, 0), // OptionsMask\n      unsignedField(4, 0), // OptionsOverride\n    ],\n  };\n}\n\n/** The sibling param's value as a number, or undefined when it has none. */\nfunction siblingValue(\n  siblings: ESPRMMatterDeviceParam[],\n  component: \"hue\" | \"saturation\",\n): number | undefined {\n  const sibling = siblings.find((p) => p.xyColorComponent === component);\n  const value = Number(sibling?.value);\n  return Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Current hue/sat of the endpoint: sibling params, else cached pair, else\n * defaults. Params come first: reports from other controllers update them,\n * not the cache.\n */\nfunction currentComponents(\n  siblings: ESPRMMatterDeviceParam[],\n  state: XyColorState,\n): { hue: number; saturation: number } {\n  const cached =\n    state.rawX !== undefined && state.rawY !== undefined\n      ? matterXyToHueSaturation(state.rawX, state.rawY)\n      : undefined;\n  return {\n    hue:\n      siblingValue(siblings, \"hue\") ??\n      cached?.hue ??\n      MatterXyColorControl.DEFAULT_HUE_DEG,\n    saturation:\n      siblingValue(siblings, \"saturation\") ??\n      cached?.saturation ??\n      MatterXyColorControl.DEFAULT_SATURATION_PCT,\n  };\n}\n\n/** Same convention as registry resolvers: decoded values are strings. */\nfunction reflectComponents(\n  siblings: ESPRMMatterDeviceParam[],\n  hue: number,\n  saturation: number,\n): void {\n  for (const sibling of siblings) {\n    sibling.value = String(\n      Math.round(sibling.xyColorComponent === \"hue\" ? hue : saturation),\n    );\n  }\n}\n\n/**\n * Writes one color component of an XY-backed endpoint by invoking\n * `MoveToColor` with the (X, Y) pair derived from the new component and the\n * sibling's current value, then reflects both components onto the live params\n * and the cache (a write is otherwise only visible once the device reports\n * X/Y back). Serialised with other reads/writes on the same endpoint.\n * @param param - XY-backed param being written (`xyColorComponent` set).\n * @param node - Node owning the param.\n * @param value - New component value as the caller supplied it.\n * @returns The transport response for the `MoveToColor` invoke.\n */\nexport async function writeXyColorParam(\n  param: ESPRMMatterDeviceParam,\n  node: ESPRMMatterNode,\n  value: unknown,\n): Promise<unknown> {\n  const matterNodeId = node.matterNodeId;\n  const endpointId = param.endpointId;\n  if (!matterNodeId || endpointId === undefined) {\n    throw new Error(\n      `Missing Matter addressing for XY color param ${param.name}`,\n    );\n  }\n  const edited = Number(value);\n  if (!Number.isFinite(edited)) {\n    throw new Error(\n      `Invalid ${param.xyColorComponent} value for ${param.name}: ${String(value)}`,\n    );\n  }\n  const state = stateFor(node, endpointId);\n  return serializeOnEndpoint(state, async () => {\n    // Resolve the sibling only now, so an earlier queued write's result is\n    // what this pair composes with.\n    const siblings = xyColorParamsFor(node, endpointId);\n    const current = currentComponents(siblings, state);\n    const hue = param.xyColorComponent === \"hue\" ? edited : current.hue;\n    const saturation =\n      param.xyColorComponent === \"saturation\" ? edited : current.saturation;\n\n    const { x, y } = hueSaturationToMatterXy(hue, saturation);\n    const response = await executeMatterControl(node, {\n      operation: MatterControlOperations.INVOKE,\n      matterNodeId,\n      endpointId,\n      clusterId: MatterXyColorControl.CLUSTER_ID,\n      commandId: MatterXyColorControl.MOVE_TO_COLOR_COMMAND_ID,\n      invokePayload: moveToColorCommandFields(x, y),\n    });\n    state.rawX = x;\n    state.rawY = y;\n    reflectComponents(siblings, hue, saturation);\n    return response;\n  });\n}\n\n/**\n * Reads the endpoint's CurrentX/CurrentY pair and projects it onto the\n * XY-backed params (both siblings — the pair decodes to both components).\n * Serialised with other reads/writes on the same endpoint so a slow read\n * cannot overwrite the cache with a pair older than a write that completed\n * meanwhile.\n * @param param - XY-backed param being read (`xyColorComponent` set).\n * @param node - Node owning the param.\n */\nexport async function readXyColorParam(\n  param: ESPRMMatterDeviceParam,\n  node: ESPRMMatterNode,\n): Promise<void> {\n  const matterNodeId = node.matterNodeId;\n  const endpointId = param.endpointId;\n  if (!matterNodeId || endpointId === undefined) {\n    throw new Error(\n      `Missing Matter addressing for XY color param ${param.name}`,\n    );\n  }\n  const readAttribute = async (attributeId: number): Promise<number> => {\n    const result = (await executeMatterControl(node, {\n      operation: MatterControlOperations.READ,\n      matterNodeId,\n      endpointId,\n      clusterId: MatterXyColorControl.CLUSTER_ID,\n      attributeId,\n    })) as { value?: unknown } | null;\n    return Number(result?.value);\n  };\n  const state = stateFor(node, endpointId);\n  return serializeOnEndpoint(state, async () => {\n    const [x, y] = await Promise.all([\n      readAttribute(MatterXyColorControl.CURRENT_X_ATTRIBUTE),\n      readAttribute(MatterXyColorControl.CURRENT_Y_ATTRIBUTE),\n    ]);\n    if (Number.isFinite(x)) state.rawX = x;\n    if (Number.isFinite(y)) state.rawY = y;\n    if (state.rawX === undefined || state.rawY === undefined) {\n      return;\n    }\n    const { hue, saturation } = matterXyToHueSaturation(\n      state.rawX,\n      state.rawY,\n    );\n    reflectComponents(xyColorParamsFor(node, endpointId), hue, saturation);\n  });\n}\n"],"names":["matterXyToHueSaturation","MatterXyColorControl","hueSaturationToMatterXy","executeMatterControl","MatterControlOperations"],"mappings":";;;;;;;;AAAA;;;;AAIG;AAuDH;;;AAGG;AACH,IAAI,aAAa,GAAG,IAAI,OAAO,EAA8C;AAE7E,SAAS,QAAQ,CAAC,IAAqB,EAAE,UAAkB,EAAA;IACzD,IAAI,UAAU,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC;IACxC,IAAI,CAAC,UAAU,EAAE;AACf,QAAA,UAAU,GAAG,IAAI,GAAG,EAAE;AACtB,QAAA,aAAa,CAAC,GAAG,CAAC,IAAI,EAAE,UAAU,CAAC;IACrC;IACA,IAAI,KAAK,GAAG,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC;IACtC,IAAI,CAAC,KAAK,EAAE;QACV,KAAK,GAAG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