mqtt2matter 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +23 -0
  4. package/README.md +172 -2
  5. package/dist/app.d.ts +34 -0
  6. package/dist/app.js +157 -0
  7. package/dist/app.js.map +1 -0
  8. package/dist/commands/import-z2m.d.ts +20 -0
  9. package/dist/commands/import-z2m.js +173 -0
  10. package/dist/commands/import-z2m.js.map +1 -0
  11. package/dist/commands/install.d.ts +41 -0
  12. package/dist/commands/install.js +250 -0
  13. package/dist/commands/install.js.map +1 -0
  14. package/dist/commands/update.d.ts +14 -0
  15. package/dist/commands/update.js +109 -0
  16. package/dist/commands/update.js.map +1 -0
  17. package/dist/config/index.d.ts +2 -0
  18. package/dist/config/index.js +3 -0
  19. package/dist/config/index.js.map +1 -0
  20. package/dist/config/load.d.ts +57 -0
  21. package/dist/config/load.js +137 -0
  22. package/dist/config/load.js.map +1 -0
  23. package/dist/config/schema.d.ts +496 -0
  24. package/dist/config/schema.js +115 -0
  25. package/dist/config/schema.js.map +1 -0
  26. package/dist/engine/payload.d.ts +94 -0
  27. package/dist/engine/payload.js +515 -0
  28. package/dist/engine/payload.js.map +1 -0
  29. package/dist/engine/runtime.d.ts +79 -0
  30. package/dist/engine/runtime.js +438 -0
  31. package/dist/engine/runtime.js.map +1 -0
  32. package/dist/engine/template.d.ts +20 -0
  33. package/dist/engine/template.js +264 -0
  34. package/dist/engine/template.js.map +1 -0
  35. package/dist/engine/units.d.ts +9 -0
  36. package/dist/engine/units.js +42 -0
  37. package/dist/engine/units.js.map +1 -0
  38. package/dist/families/climate.d.ts +11 -0
  39. package/dist/families/climate.js +68 -0
  40. package/dist/families/climate.js.map +1 -0
  41. package/dist/families/color.d.ts +30 -0
  42. package/dist/families/color.js +152 -0
  43. package/dist/families/color.js.map +1 -0
  44. package/dist/families/cover.d.ts +17 -0
  45. package/dist/families/cover.js +308 -0
  46. package/dist/families/cover.js.map +1 -0
  47. package/dist/families/fan.d.ts +16 -0
  48. package/dist/families/fan.js +154 -0
  49. package/dist/families/fan.js.map +1 -0
  50. package/dist/families/index.d.ts +32 -0
  51. package/dist/families/index.js +162 -0
  52. package/dist/families/index.js.map +1 -0
  53. package/dist/families/light.d.ts +36 -0
  54. package/dist/families/light.js +258 -0
  55. package/dist/families/light.js.map +1 -0
  56. package/dist/families/lock.d.ts +10 -0
  57. package/dist/families/lock.js +31 -0
  58. package/dist/families/lock.js.map +1 -0
  59. package/dist/families/on-off.d.ts +7 -0
  60. package/dist/families/on-off.js +56 -0
  61. package/dist/families/on-off.js.map +1 -0
  62. package/dist/families/power-source.d.ts +12 -0
  63. package/dist/families/power-source.js +60 -0
  64. package/dist/families/power-source.js.map +1 -0
  65. package/dist/families/registry.d.ts +40 -0
  66. package/dist/families/registry.js +72 -0
  67. package/dist/families/registry.js.map +1 -0
  68. package/dist/families/rvc.d.ts +40 -0
  69. package/dist/families/rvc.js +83 -0
  70. package/dist/families/rvc.js.map +1 -0
  71. package/dist/families/switch.d.ts +19 -0
  72. package/dist/families/switch.js +94 -0
  73. package/dist/families/switch.js.map +1 -0
  74. package/dist/importers/actions.d.ts +19 -0
  75. package/dist/importers/actions.js +98 -0
  76. package/dist/importers/actions.js.map +1 -0
  77. package/dist/importers/ha/areas.d.ts +6 -0
  78. package/dist/importers/ha/areas.js +279 -0
  79. package/dist/importers/ha/areas.js.map +1 -0
  80. package/dist/importers/ha/generate.d.ts +51 -0
  81. package/dist/importers/ha/generate.js +1376 -0
  82. package/dist/importers/ha/generate.js.map +1 -0
  83. package/dist/importers/ha/index.d.ts +6 -0
  84. package/dist/importers/ha/index.js +7 -0
  85. package/dist/importers/ha/index.js.map +1 -0
  86. package/dist/importers/ha/source.d.ts +36 -0
  87. package/dist/importers/ha/source.js +95 -0
  88. package/dist/importers/ha/source.js.map +1 -0
  89. package/dist/importers/ha/sync.d.ts +29 -0
  90. package/dist/importers/ha/sync.js +132 -0
  91. package/dist/importers/ha/sync.js.map +1 -0
  92. package/dist/importers/ha/templates.d.ts +18 -0
  93. package/dist/importers/ha/templates.js +285 -0
  94. package/dist/importers/ha/templates.js.map +1 -0
  95. package/dist/importers/ha/types.d.ts +78 -0
  96. package/dist/importers/ha/types.js +479 -0
  97. package/dist/importers/ha/types.js.map +1 -0
  98. package/dist/importers/index.d.ts +5 -0
  99. package/dist/importers/index.js +8 -0
  100. package/dist/importers/index.js.map +1 -0
  101. package/dist/importers/patch.d.ts +50 -0
  102. package/dist/importers/patch.js +224 -0
  103. package/dist/importers/patch.js.map +1 -0
  104. package/dist/importers/sync.d.ts +112 -0
  105. package/dist/importers/sync.js +220 -0
  106. package/dist/importers/sync.js.map +1 -0
  107. package/dist/importers/twins.d.ts +10 -0
  108. package/dist/importers/twins.js +34 -0
  109. package/dist/importers/twins.js.map +1 -0
  110. package/dist/importers/z2m/generate.d.ts +81 -0
  111. package/dist/importers/z2m/generate.js +1171 -0
  112. package/dist/importers/z2m/generate.js.map +1 -0
  113. package/dist/importers/z2m/index.d.ts +5 -0
  114. package/dist/importers/z2m/index.js +6 -0
  115. package/dist/importers/z2m/index.js.map +1 -0
  116. package/dist/importers/z2m/source.d.ts +18 -0
  117. package/dist/importers/z2m/source.js +46 -0
  118. package/dist/importers/z2m/source.js.map +1 -0
  119. package/dist/importers/z2m/sync.d.ts +29 -0
  120. package/dist/importers/z2m/sync.js +92 -0
  121. package/dist/importers/z2m/sync.js.map +1 -0
  122. package/dist/importers/z2m/types.d.ts +72 -0
  123. package/dist/importers/z2m/types.js +46 -0
  124. package/dist/importers/z2m/types.js.map +1 -0
  125. package/dist/index.d.ts +5 -0
  126. package/dist/index.js +7 -0
  127. package/dist/index.js.map +1 -0
  128. package/dist/log.d.ts +17 -0
  129. package/dist/log.js +54 -0
  130. package/dist/log.js.map +1 -0
  131. package/dist/main.d.ts +2 -0
  132. package/dist/main.js +202 -0
  133. package/dist/main.js.map +1 -0
  134. package/dist/matter/bridge.d.ts +113 -0
  135. package/dist/matter/bridge.js +467 -0
  136. package/dist/matter/bridge.js.map +1 -0
  137. package/dist/matter/check.d.ts +11 -0
  138. package/dist/matter/check.js +116 -0
  139. package/dist/matter/check.js.map +1 -0
  140. package/dist/matter/cluster-defaults.d.ts +6 -0
  141. package/dist/matter/cluster-defaults.js +63 -0
  142. package/dist/matter/cluster-defaults.js.map +1 -0
  143. package/dist/matter/commissioning.d.ts +21 -0
  144. package/dist/matter/commissioning.js +88 -0
  145. package/dist/matter/commissioning.js.map +1 -0
  146. package/dist/matter/device-types.d.ts +44 -0
  147. package/dist/matter/device-types.js +230 -0
  148. package/dist/matter/device-types.js.map +1 -0
  149. package/dist/matter/ids.d.ts +31 -0
  150. package/dist/matter/ids.js +83 -0
  151. package/dist/matter/ids.js.map +1 -0
  152. package/dist/matter/index.d.ts +7 -0
  153. package/dist/matter/index.js +8 -0
  154. package/dist/matter/index.js.map +1 -0
  155. package/dist/matter/node-manager.d.ts +39 -0
  156. package/dist/matter/node-manager.js +161 -0
  157. package/dist/matter/node-manager.js.map +1 -0
  158. package/dist/matter/shards.d.ts +26 -0
  159. package/dist/matter/shards.js +93 -0
  160. package/dist/matter/shards.js.map +1 -0
  161. package/dist/model/attribute.d.ts +18 -0
  162. package/dist/model/attribute.js +28 -0
  163. package/dist/model/attribute.js.map +1 -0
  164. package/dist/model/catalog.d.ts +79 -0
  165. package/dist/model/catalog.js +223 -0
  166. package/dist/model/catalog.js.map +1 -0
  167. package/dist/model/index.d.ts +7 -0
  168. package/dist/model/index.js +8 -0
  169. package/dist/model/index.js.map +1 -0
  170. package/dist/model/migrate.d.ts +4 -0
  171. package/dist/model/migrate.js +39 -0
  172. package/dist/model/migrate.js.map +1 -0
  173. package/dist/model/options.d.ts +102 -0
  174. package/dist/model/options.js +88 -0
  175. package/dist/model/options.js.map +1 -0
  176. package/dist/model/presets.d.ts +37 -0
  177. package/dist/model/presets.js +105 -0
  178. package/dist/model/presets.js.map +1 -0
  179. package/dist/model/schema.d.ts +1747 -0
  180. package/dist/model/schema.js +243 -0
  181. package/dist/model/schema.js.map +1 -0
  182. package/dist/model/validate.d.ts +21 -0
  183. package/dist/model/validate.js +484 -0
  184. package/dist/model/validate.js.map +1 -0
  185. package/dist/mqtt/client.d.ts +38 -0
  186. package/dist/mqtt/client.js +94 -0
  187. package/dist/mqtt/client.js.map +1 -0
  188. package/dist/mqtt/index.d.ts +2 -0
  189. package/dist/mqtt/index.js +3 -0
  190. package/dist/mqtt/index.js.map +1 -0
  191. package/dist/mqtt/topic-cache.d.ts +20 -0
  192. package/dist/mqtt/topic-cache.js +58 -0
  193. package/dist/mqtt/topic-cache.js.map +1 -0
  194. package/dist/server/auth.d.ts +59 -0
  195. package/dist/server/auth.js +185 -0
  196. package/dist/server/auth.js.map +1 -0
  197. package/dist/server/catalog.d.ts +52 -0
  198. package/dist/server/catalog.js +96 -0
  199. package/dist/server/catalog.js.map +1 -0
  200. package/dist/server/compact.d.ts +3 -0
  201. package/dist/server/compact.js +105 -0
  202. package/dist/server/compact.js.map +1 -0
  203. package/dist/server/config-store.d.ts +36 -0
  204. package/dist/server/config-store.js +155 -0
  205. package/dist/server/config-store.js.map +1 -0
  206. package/dist/server/events.d.ts +50 -0
  207. package/dist/server/events.js +71 -0
  208. package/dist/server/events.js.map +1 -0
  209. package/dist/server/http.d.ts +27 -0
  210. package/dist/server/http.js +168 -0
  211. package/dist/server/http.js.map +1 -0
  212. package/dist/server/importers.d.ts +40 -0
  213. package/dist/server/importers.js +75 -0
  214. package/dist/server/importers.js.map +1 -0
  215. package/dist/server/index.d.ts +6 -0
  216. package/dist/server/index.js +8 -0
  217. package/dist/server/index.js.map +1 -0
  218. package/dist/server/log-buffer.d.ts +22 -0
  219. package/dist/server/log-buffer.js +55 -0
  220. package/dist/server/log-buffer.js.map +1 -0
  221. package/dist/server/presets.d.ts +17 -0
  222. package/dist/server/presets.js +55 -0
  223. package/dist/server/presets.js.map +1 -0
  224. package/dist/server/preview.d.ts +19 -0
  225. package/dist/server/preview.js +121 -0
  226. package/dist/server/preview.js.map +1 -0
  227. package/dist/server/server.d.ts +107 -0
  228. package/dist/server/server.js +810 -0
  229. package/dist/server/server.js.map +1 -0
  230. package/dist/server/update.d.ts +60 -0
  231. package/dist/server/update.js +191 -0
  232. package/dist/server/update.js.map +1 -0
  233. package/docs/api.md +128 -0
  234. package/docs/architecture.md +121 -0
  235. package/docs/config.md +538 -0
  236. package/docs/importers.md +241 -0
  237. package/example/mqtt2matter.json +276 -0
  238. package/package.json +90 -4
  239. package/presets/mqtt-smarthome/button.json +47 -0
  240. package/presets/mqtt-smarthome/contact.json +37 -0
  241. package/presets/mqtt-smarthome/cover.json +50 -0
  242. package/presets/mqtt-smarthome/dimmer.json +57 -0
  243. package/presets/mqtt-smarthome/humidity.json +38 -0
  244. package/presets/mqtt-smarthome/light.json +47 -0
  245. package/presets/mqtt-smarthome/occupancy.json +46 -0
  246. package/presets/mqtt-smarthome/switch.json +47 -0
  247. package/presets/mqtt-smarthome/temperature.json +38 -0
  248. package/presets/openbeken/color-light.json +64 -0
  249. package/presets/openbeken/ct-light.json +51 -0
  250. package/presets/openbeken/dimmer.json +47 -0
  251. package/presets/openbeken/humidity.json +37 -0
  252. package/presets/openbeken/relay.json +40 -0
  253. package/presets/openbeken/temperature.json +41 -0
  254. package/presets/shelly-gen1/dimmer.json +48 -0
  255. package/presets/shelly-gen1/door-window.json +43 -0
  256. package/presets/shelly-gen1/ht.json +43 -0
  257. package/presets/shelly-gen1/relay-pm.json +60 -0
  258. package/presets/shelly-gen1/relay.json +36 -0
  259. package/presets/shelly-gen1/roller.json +52 -0
  260. package/presets/shelly-gen2/cover.json +68 -0
  261. package/presets/shelly-gen2/dimmer.json +61 -0
  262. package/presets/shelly-gen2/ht.json +47 -0
  263. package/presets/shelly-gen2/i4.json +82 -0
  264. package/presets/shelly-gen2/switch-pm.json +101 -0
  265. package/presets/shelly-gen2/switch.json +47 -0
  266. package/presets/tasmota/climate.json +52 -0
  267. package/presets/tasmota/color-light.json +63 -0
  268. package/presets/tasmota/ct-light.json +50 -0
  269. package/presets/tasmota/dimmer.json +45 -0
  270. package/presets/tasmota/relay.json +39 -0
  271. package/presets/tasmota/shutter.json +46 -0
  272. package/presets/tasmota/temperature-humidity.json +42 -0
  273. package/presets/tasmota/temperature.json +32 -0
  274. package/presets/valetudo/vacuum.json +103 -0
  275. package/presets/wled/dimmer.json +46 -0
  276. package/presets/wled/light.json +59 -0
  277. package/ui/dist/assets/index-BDtT6bdH.js +10 -0
  278. package/ui/dist/assets/index-CHiG-aoU.css +1 -0
  279. package/ui/dist/index.html +18 -0
@@ -0,0 +1,1171 @@
1
+ /* zigbee2mqtt → the manual model. One `bridge/devices` entry becomes one device: its exposes decide the
2
+ device types, clusters and mappings per zigbee2mqtt endpoint (`l1`, `l2`, … become child endpoints),
3
+ `action` enums become GenericSwitch children, `battery` a power source, a scene stored on the device or
4
+ the group a momentary outlet child that recalls it, and every device gets its availability topic. A `bridge/groups` entry becomes one endpoint with the union of its members' light,
5
+ switch or cover features. What is generated is the *baseline*; `source.raw` keeps what is needed to
6
+ regenerate it, so a user's edits can be carried over when zigbee2mqtt's description changes.
7
+
8
+ The topics are zigbee2mqtt's: `<base>/<friendly_name>` (state, JSON), `…/set`, `…/get`,
9
+ `…/availability`. Multi-endpoint devices are addressed through the property suffix (`state_l1`) on the
10
+ device's own `/set` topic. */
11
+ import { createHash } from 'node:crypto';
12
+ import { multiPressMax, parseActions } from "../actions.js";
13
+ import { canGet, canRead, canSet } from "./types.js";
14
+ export const SOURCE_KIND = 'z2m';
15
+ export const DEFAULT_BASE_TOPIC = 'zigbee2mqtt';
16
+ /** bumped when the generator's output for the same raw description changes */
17
+ export const GENERATOR_VERSION = 1;
18
+ export const deviceKey = (ieee) => `${SOURCE_KIND}:${ieee}`;
19
+ export const groupKey = (id) => `${SOURCE_KIND}:group:${id}`;
20
+ /** availability payloads: `{"state":"online"}` (zigbee2mqtt ≥ 1.22) or plain `online` (legacy) */
21
+ export const AVAILABILITY_TEMPLATE = '{{ value_json.state if value_json is defined and value_json.state is defined else value }}';
22
+ const MAX_LABEL = 32;
23
+ const label = (text) => text === undefined || text === '' ? undefined : text.slice(0, MAX_LABEL);
24
+ /** an endpoint id the schema accepts */
25
+ export function endpointId(name) {
26
+ const cleaned = name.replace(/[^A-Za-z0-9:._-]/g, '_');
27
+ return /^[A-Za-z0-9]/.test(cleaned) ? cleaned : `e${cleaned}`;
28
+ }
29
+ export function rawHash(raw) {
30
+ return `${GENERATOR_VERSION}.${createHash('sha256').update(JSON.stringify(raw)).digest('hex').slice(0, 12)}`;
31
+ }
32
+ /** the description trimmed: descriptions and labels of the exposes carry nothing the generator needs */
33
+ function trimExpose(expose) {
34
+ const trimmed = { ...expose };
35
+ delete trimmed.description;
36
+ delete trimmed.label;
37
+ if (trimmed.features !== undefined) {
38
+ trimmed.features = trimmed.features.map(trimExpose);
39
+ }
40
+ return trimmed;
41
+ }
42
+ /** a payload value as the text a map key or format value is written with */
43
+ function text(value, fallback) {
44
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
45
+ ? String(value)
46
+ : fallback;
47
+ }
48
+ function isScene(value) {
49
+ return (typeof value === 'object' &&
50
+ value !== null &&
51
+ typeof value.id === 'number' &&
52
+ typeof value.name === 'string');
53
+ }
54
+ /** scenes by id, sorted; the first name of an id wins */
55
+ function sceneList(lists) {
56
+ const byId = new Map();
57
+ for (const list of lists) {
58
+ for (const scene of Array.isArray(list) ? list : []) {
59
+ if (isScene(scene) && !byId.has(scene.id)) {
60
+ byId.set(scene.id, { id: scene.id, name: scene.name });
61
+ }
62
+ }
63
+ }
64
+ return [...byId.values()].sort((a, b) => a.id - b.id);
65
+ }
66
+ /** the scenes zigbee2mqtt lists on a device's endpoints (`endpoints.<n>.scenes`) */
67
+ export function deviceScenes(device) {
68
+ const endpoints = device.endpoints;
69
+ if (typeof endpoints !== 'object' || endpoints === null) {
70
+ return [];
71
+ }
72
+ return sceneList(Object.values(endpoints).map((ep) => ep?.scenes));
73
+ }
74
+ export function rawDevice(device, baseTopic) {
75
+ const definition = device.definition ?? null;
76
+ const scenes = deviceScenes(device);
77
+ return {
78
+ kind: 'device',
79
+ base_topic: baseTopic,
80
+ ieee_address: device.ieee_address,
81
+ friendly_name: device.friendly_name,
82
+ type: device.type,
83
+ ...(device.power_source === undefined ? {} : { power_source: device.power_source }),
84
+ ...(device.model_id === undefined ? {} : { model_id: device.model_id }),
85
+ ...(device.manufacturer === undefined ? {} : { manufacturer: device.manufacturer }),
86
+ definition: definition === null
87
+ ? null
88
+ : {
89
+ ...(definition.vendor === undefined ? {} : { vendor: definition.vendor }),
90
+ ...(definition.model === undefined ? {} : { model: definition.model }),
91
+ ...(definition.description === undefined ? {} : { description: definition.description }),
92
+ exposes: (definition.exposes ?? []).map(trimExpose),
93
+ },
94
+ ...(scenes.length === 0 ? {} : { scenes }),
95
+ };
96
+ }
97
+ /** ms a scene's outlet stays on after a recall */
98
+ export const SCENE_MOMENTARY = 1000;
99
+ /** the order device types take on an endpoint: the first is the endpoint's own type */
100
+ const TYPE_ORDER = [
101
+ 'ExtendedColorLight',
102
+ 'ColorTemperatureLight',
103
+ 'DimmableLight',
104
+ 'OnOffLight',
105
+ 'WindowCovering',
106
+ 'Thermostat',
107
+ 'DoorLock',
108
+ 'Fan',
109
+ 'OnOffPlugInUnit',
110
+ 'OccupancySensor',
111
+ 'ContactSensor',
112
+ 'WaterLeakDetector',
113
+ 'RainSensor',
114
+ 'SmokeCoAlarm',
115
+ 'AirQualitySensor',
116
+ 'TemperatureSensor',
117
+ 'HumiditySensor',
118
+ 'PressureSensor',
119
+ 'LightSensor',
120
+ 'GenericSwitch',
121
+ 'PowerSource',
122
+ ];
123
+ const typeRank = (name) => {
124
+ const i = TYPE_ORDER.indexOf(name);
125
+ return i === -1 ? TYPE_ORDER.length : i;
126
+ };
127
+ /** the Common Number semantic tag namespace (Matter namespaces, 0x07): `One`, `Two`, … for sibling endpoints */
128
+ const NUMBER_NAMESPACE = 7;
129
+ /** covers that echo the target position once before the real movement reports (the family's echo filter) */
130
+ const COVER_QUIRKS = {
131
+ E1757: { echoFilter: true },
132
+ E1926: { echoFilter: true },
133
+ };
134
+ class Builder {
135
+ drafts = new Map();
136
+ unmapped = [];
137
+ stateTopic;
138
+ setTopic;
139
+ getTopic;
140
+ hasBattery;
141
+ constructor(baseTopic, friendlyName, hasBattery) {
142
+ this.hasBattery = hasBattery;
143
+ this.stateTopic = `${baseTopic}/${friendlyName}`;
144
+ this.setTopic = `${this.stateTopic}/set`;
145
+ this.getTopic = `${this.stateTopic}/get`;
146
+ }
147
+ draft(z2mEndpoint, id = z2mEndpoint) {
148
+ let draft = this.drafts.get(id);
149
+ if (draft === undefined) {
150
+ draft = { z2mEndpoint, id, types: [], mappings: [], features: {}, options: {}, coalesce: 0, hasGet: false };
151
+ this.drafts.set(id, draft);
152
+ }
153
+ return draft;
154
+ }
155
+ addType(draft, type) {
156
+ if (!draft.types.includes(type)) {
157
+ draft.types.push(type);
158
+ draft.types.sort((a, b) => typeRank(a) - typeRank(b));
159
+ }
160
+ }
161
+ addFeature(draft, cluster, feature) {
162
+ const list = (draft.features[cluster] ??= []);
163
+ if (!list.includes(feature)) {
164
+ list.push(feature);
165
+ }
166
+ }
167
+ property(expose) {
168
+ return (expose.property ??
169
+ (expose.endpoint === undefined ? (expose.name ?? '') : `${expose.name}_${expose.endpoint}`));
170
+ }
171
+ /** a status half on the device's state topic */
172
+ status(expose, extra = {}) {
173
+ return { topic: this.stateTopic, extract: this.property(expose), ...extra };
174
+ }
175
+ /** a command half on the device's `/set` topic, the property as the JSON key */
176
+ command(expose, extra = {}) {
177
+ return { topic: this.setTopic, wrap: this.property(expose), ...extra };
178
+ }
179
+ /** a mapping from a feature's access bits; `get` on the endpoint's first gettable feature */
180
+ bind(draft, attribute, expose, statusExtra = {}, commandExtra = {}) {
181
+ const mapping = { attribute };
182
+ if (canRead(expose)) {
183
+ const status = this.status(expose, statusExtra);
184
+ if (canGet(expose) && !draft.hasGet) {
185
+ draft.hasGet = true;
186
+ status.get = { topic: this.getTopic, payload: JSON.stringify({ [this.property(expose)]: '' }) };
187
+ }
188
+ mapping.status = status;
189
+ }
190
+ if (canSet(expose)) {
191
+ mapping.command = this.command(expose, commandExtra);
192
+ }
193
+ if (mapping.status === undefined && mapping.command === undefined) {
194
+ return undefined;
195
+ }
196
+ draft.mappings.push(mapping);
197
+ return mapping;
198
+ }
199
+ skip(expose) {
200
+ const name = this.property(expose);
201
+ if (name !== '' && !this.unmapped.includes(name)) {
202
+ this.unmapped.push(name);
203
+ }
204
+ }
205
+ /* ----- specific exposes ----- */
206
+ light(expose) {
207
+ const features = expose.features ?? [];
208
+ const by = featureMap(features);
209
+ const endpoint = expose.endpoint ?? features[0]?.endpoint ?? '';
210
+ const draft = this.draft(endpoint);
211
+ const state = by.get('state');
212
+ const brightness = by.get('brightness');
213
+ const colorTemp = by.get('color_temp');
214
+ const xy = by.get('color_xy');
215
+ const hs = by.get('color_hs');
216
+ this.addType(draft, xy !== undefined || hs !== undefined
217
+ ? 'ExtendedColorLight'
218
+ : colorTemp !== undefined
219
+ ? 'ColorTemperatureLight'
220
+ : brightness !== undefined
221
+ ? 'DimmableLight'
222
+ : 'OnOffLight');
223
+ draft.coalesce = 50;
224
+ if (state !== undefined) {
225
+ this.onOff(draft, state);
226
+ }
227
+ if (brightness !== undefined) {
228
+ // zigbee2mqtt's brightness is Matter's level (1–254); a 0 is clamped to 1
229
+ const scale = { from: [1, 254], to: [1, 254] };
230
+ this.bind(draft, 'LevelControl.currentLevel', brightness, { scale }, { scale, round: 0 });
231
+ }
232
+ if (colorTemp !== undefined) {
233
+ this.bind(draft, 'ColorControl.colorTemperatureMireds', colorTemp);
234
+ const light = (draft.options.light ??= {});
235
+ if (colorTemp.value_min !== undefined) {
236
+ light.minMireds = Math.max(1, Math.round(colorTemp.value_min));
237
+ }
238
+ if (colorTemp.value_max !== undefined) {
239
+ light.maxMireds = Math.min(65279, Math.round(colorTemp.value_max));
240
+ }
241
+ }
242
+ if (xy !== undefined) {
243
+ this.bind(draft, 'ColorControl.colorXy', xy);
244
+ if (hs !== undefined) {
245
+ this.addFeature(draft, 'ColorControl', 'HueSaturation');
246
+ }
247
+ }
248
+ else if (hs !== undefined) {
249
+ this.bind(draft, 'ColorControl.colorHs', hs);
250
+ }
251
+ if ((xy !== undefined || hs !== undefined) && colorTemp !== undefined) {
252
+ // zigbee2mqtt reports which representation is current; without it the last report would win
253
+ const property = endpoint === '' ? 'color_mode' : `color_mode_${endpoint}`;
254
+ draft.mappings.push({
255
+ attribute: 'ColorControl.colorMode',
256
+ status: {
257
+ topic: this.stateTopic,
258
+ extract: property,
259
+ map: {
260
+ xy: 'CurrentXAndCurrentY',
261
+ hs: 'CurrentHueAndCurrentSaturation',
262
+ color_temp: 'ColorTemperatureMireds',
263
+ },
264
+ },
265
+ });
266
+ }
267
+ for (const feature of features) {
268
+ if (!['state', 'brightness', 'color_temp', 'color_xy', 'color_hs'].includes(feature.name ?? '')) {
269
+ this.skip(feature);
270
+ }
271
+ }
272
+ }
273
+ onOff(draft, state) {
274
+ const on = text(state.value_on, 'ON');
275
+ const off = text(state.value_off, 'OFF');
276
+ this.bind(draft, 'OnOff.onOff', state, { map: { [on]: true, [off]: false } }, { format: { true: on, false: off } });
277
+ }
278
+ switch(expose) {
279
+ const features = expose.features ?? [];
280
+ const by = featureMap(features);
281
+ const draft = this.draft(expose.endpoint ?? features[0]?.endpoint ?? '');
282
+ this.addType(draft, 'OnOffPlugInUnit');
283
+ const state = by.get('state');
284
+ if (state !== undefined) {
285
+ this.onOff(draft, state);
286
+ }
287
+ for (const feature of features) {
288
+ if (feature.name !== 'state') {
289
+ this.skip(feature);
290
+ }
291
+ }
292
+ }
293
+ cover(expose, model) {
294
+ const features = expose.features ?? [];
295
+ const by = featureMap(features);
296
+ const draft = this.draft(expose.endpoint ?? features[0]?.endpoint ?? '');
297
+ this.addType(draft, 'WindowCovering');
298
+ const position = by.get('position');
299
+ const tilt = by.get('tilt');
300
+ const state = by.get('state');
301
+ // zigbee2mqtt: 100 = open; Matter: 0 = open
302
+ const scale = { from: [0, 100], to: [10000, 0] };
303
+ if (position !== undefined) {
304
+ if (canRead(position)) {
305
+ const status = this.status(position, { scale });
306
+ if (canGet(position) && !draft.hasGet) {
307
+ draft.hasGet = true;
308
+ status.get = { topic: this.getTopic, payload: JSON.stringify({ [this.property(position)]: '' }) };
309
+ }
310
+ draft.mappings.push({ attribute: 'WindowCovering.currentPositionLiftPercent100ths', status });
311
+ }
312
+ if (canSet(position)) {
313
+ draft.mappings.push({
314
+ attribute: 'WindowCovering.targetPositionLiftPercent100ths',
315
+ command: this.command(position, { scale, round: 0 }),
316
+ });
317
+ }
318
+ }
319
+ if (tilt !== undefined) {
320
+ if (canRead(tilt)) {
321
+ draft.mappings.push({
322
+ attribute: 'WindowCovering.currentPositionTiltPercent100ths',
323
+ status: this.status(tilt, { scale }),
324
+ });
325
+ }
326
+ if (canSet(tilt)) {
327
+ draft.mappings.push({
328
+ attribute: 'WindowCovering.targetPositionTiltPercent100ths',
329
+ command: this.command(tilt, { scale, round: 0 }),
330
+ });
331
+ }
332
+ }
333
+ if (state !== undefined && canSet(state)) {
334
+ const values = (state.values ?? ['OPEN', 'CLOSE', 'STOP']).map(String);
335
+ const find = (word) => values.find((v) => v.toUpperCase() === word) ?? values.find((v) => v.toUpperCase().startsWith(word));
336
+ const open = find('OPEN');
337
+ const close = find('CLOSE');
338
+ const stop = find('STOP');
339
+ if (position === undefined) {
340
+ if (open !== undefined) {
341
+ draft.mappings.push({
342
+ invoke: 'WindowCovering.upOrOpen',
343
+ command: this.command(state, { payload: open }),
344
+ });
345
+ }
346
+ if (close !== undefined) {
347
+ draft.mappings.push({
348
+ invoke: 'WindowCovering.downOrClose',
349
+ command: this.command(state, { payload: close }),
350
+ });
351
+ }
352
+ }
353
+ if (stop !== undefined) {
354
+ draft.mappings.push({
355
+ invoke: 'WindowCovering.stopMotion',
356
+ command: this.command(state, { payload: stop }),
357
+ });
358
+ }
359
+ }
360
+ const quirks = model === undefined ? undefined : COVER_QUIRKS[model];
361
+ if (quirks !== undefined) {
362
+ draft.options.cover = { ...(draft.options.cover ?? {}), ...quirks };
363
+ }
364
+ for (const feature of features) {
365
+ if (!['position', 'tilt', 'state'].includes(feature.name ?? '')) {
366
+ this.skip(feature);
367
+ }
368
+ }
369
+ this.covers.push({ draft, state, positionAware: position !== undefined });
370
+ }
371
+ /** the covers of the walk; their movement mapping is decided when every expose was seen */
372
+ covers = [];
373
+ /** `moving` / `motor_state` enums seen on the walk, per zigbee2mqtt endpoint; the cover takes them */
374
+ motionExposes = new Map();
375
+ /** a movement report (`moving`, `motor_state`) or, for a state-only cover, the state itself → `motion` */
376
+ finishCovers() {
377
+ for (const { draft, state, positionAware } of this.covers) {
378
+ const motion = this.motionExposes.get(draft.z2mEndpoint);
379
+ if (motion !== undefined) {
380
+ const map = {};
381
+ for (const value of (motion.values ?? []).map(String)) {
382
+ const v = value.toUpperCase();
383
+ const kind = v.startsWith('UP') || v.startsWith('OPEN')
384
+ ? 'opening'
385
+ : v.startsWith('DOWN') || v.startsWith('CLOS')
386
+ ? 'closing'
387
+ : v.startsWith('STOP') || v === 'IDLE'
388
+ ? 'stopped'
389
+ : undefined;
390
+ if (kind !== undefined) {
391
+ map[value] = kind;
392
+ }
393
+ }
394
+ draft.mappings.push({ attribute: 'WindowCovering.motion', status: this.status(motion, { map }) });
395
+ this.unmapped.splice(this.unmapped.indexOf(this.property(motion)), 1);
396
+ continue;
397
+ }
398
+ if (!positionAware && state !== undefined && canRead(state)) {
399
+ const map = {};
400
+ for (const value of (state.values ?? []).map(String)) {
401
+ const v = value.toUpperCase();
402
+ if (v.startsWith('OPEN')) {
403
+ map[value] = 'open';
404
+ }
405
+ else if (v.startsWith('CLOS')) {
406
+ map[value] = 'closed';
407
+ }
408
+ else if (v.startsWith('STOP')) {
409
+ map[value] = 'stopped';
410
+ }
411
+ }
412
+ draft.mappings.push({ attribute: 'WindowCovering.motion', status: this.status(state, { map }) });
413
+ }
414
+ }
415
+ }
416
+ lock(expose) {
417
+ const features = expose.features ?? [];
418
+ const by = featureMap(features);
419
+ const state = by.get('state');
420
+ if (state === undefined || this.property(state).endsWith('child_lock')) {
421
+ // a child lock is a setting, not a door lock
422
+ for (const feature of features) {
423
+ this.skip(feature);
424
+ }
425
+ return;
426
+ }
427
+ const draft = this.draft(expose.endpoint ?? state.endpoint ?? '');
428
+ this.addType(draft, 'DoorLock');
429
+ const lockState = by.get('lock_state');
430
+ const on = text(state.value_on, 'LOCK');
431
+ const off = text(state.value_off, 'UNLOCK');
432
+ const mapping = { attribute: 'DoorLock.lockState' };
433
+ if (lockState !== undefined && canRead(lockState)) {
434
+ mapping.status = this.status(lockState, {
435
+ map: { locked: 'Locked', unlocked: 'Unlocked', not_fully_locked: 'NotFullyLocked' },
436
+ });
437
+ }
438
+ else if (canRead(state)) {
439
+ mapping.status = this.status(state, { map: { [on]: 'Locked', [off]: 'Unlocked' } });
440
+ }
441
+ if (canSet(state)) {
442
+ mapping.command = this.command(state, { format: { Locked: on, Unlocked: off } });
443
+ }
444
+ draft.mappings.push(mapping);
445
+ for (const feature of features) {
446
+ if (!['state', 'lock_state'].includes(feature.name ?? '')) {
447
+ this.skip(feature);
448
+ }
449
+ }
450
+ }
451
+ climate(expose) {
452
+ const features = expose.features ?? [];
453
+ const by = featureMap(features);
454
+ const draft = this.draft(expose.endpoint ?? features[0]?.endpoint ?? '');
455
+ this.addType(draft, 'Thermostat');
456
+ draft.coalesce = 50;
457
+ const climate = (draft.options.climate ??= {});
458
+ const local = by.get('local_temperature');
459
+ if (local !== undefined) {
460
+ this.bind(draft, 'Thermostat.localTemperature', local, { unit: temperatureUnit(local) });
461
+ }
462
+ const heat = by.get('occupied_heating_setpoint') ?? by.get('current_heating_setpoint');
463
+ if (heat !== undefined) {
464
+ const unit = temperatureUnit(heat);
465
+ this.bind(draft, 'Thermostat.occupiedHeatingSetpoint', heat, { unit }, { unit, round: 1 });
466
+ if (heat.value_min !== undefined) {
467
+ climate.minHeat = heat.value_min;
468
+ }
469
+ if (heat.value_max !== undefined) {
470
+ climate.maxHeat = heat.value_max;
471
+ }
472
+ }
473
+ const cool = by.get('occupied_cooling_setpoint') ?? by.get('current_cooling_setpoint');
474
+ if (cool !== undefined) {
475
+ const unit = temperatureUnit(cool);
476
+ this.bind(draft, 'Thermostat.occupiedCoolingSetpoint', cool, { unit }, { unit, round: 1 });
477
+ if (cool.value_min !== undefined) {
478
+ climate.minCool = cool.value_min;
479
+ }
480
+ if (cool.value_max !== undefined) {
481
+ climate.maxCool = cool.value_max;
482
+ }
483
+ }
484
+ const mode = by.get('system_mode');
485
+ if (mode !== undefined) {
486
+ const names = {
487
+ off: 'Off',
488
+ heat: 'Heat',
489
+ cool: 'Cool',
490
+ auto: 'Auto',
491
+ dry: 'Dry',
492
+ fan_only: 'FanOnly',
493
+ emergency_heating: 'EmergencyHeat',
494
+ precooling: 'Precooling',
495
+ };
496
+ const map = {};
497
+ const format = {};
498
+ for (const value of (mode.values ?? []).map(String)) {
499
+ const name = names[value];
500
+ if (name !== undefined) {
501
+ map[value] = name;
502
+ format[name] = value;
503
+ }
504
+ }
505
+ this.bind(draft, 'Thermostat.systemMode', mode, { map }, { format });
506
+ }
507
+ const running = by.get('running_state');
508
+ if (running !== undefined && canRead(running)) {
509
+ const map = {};
510
+ for (const value of (running.values ?? []).map(String)) {
511
+ map[value] = value === 'heat' ? 'heat' : value === 'cool' ? 'cool' : value === 'fan_only' ? 'fan' : '';
512
+ }
513
+ draft.mappings.push({ attribute: 'Thermostat.thermostatRunningState', status: this.status(running, { map }) });
514
+ }
515
+ const mapped = [
516
+ 'local_temperature',
517
+ 'occupied_heating_setpoint',
518
+ 'current_heating_setpoint',
519
+ 'occupied_cooling_setpoint',
520
+ 'current_cooling_setpoint',
521
+ 'system_mode',
522
+ 'running_state',
523
+ ];
524
+ for (const feature of features) {
525
+ if (!mapped.includes(feature.name ?? '')) {
526
+ this.skip(feature);
527
+ }
528
+ }
529
+ }
530
+ fan(expose) {
531
+ const features = expose.features ?? [];
532
+ const by = featureMap(features);
533
+ const draft = this.draft(expose.endpoint ?? features[0]?.endpoint ?? '');
534
+ this.addType(draft, 'Fan');
535
+ draft.coalesce = 50;
536
+ const state = by.get('state');
537
+ if (state !== undefined) {
538
+ this.onOff(draft, state);
539
+ }
540
+ const mode = by.get('mode');
541
+ if (mode !== undefined) {
542
+ const values = (mode.values ?? []).map(String);
543
+ const numeric = values.filter((v) => /^\d+$/.test(v)).map(Number);
544
+ const names = {
545
+ off: 'Off',
546
+ low: 'Low',
547
+ medium: 'Medium',
548
+ high: 'High',
549
+ auto: 'Auto',
550
+ on: 'On',
551
+ smart: 'Smart',
552
+ };
553
+ const map = {};
554
+ const format = {};
555
+ for (const value of values) {
556
+ const name = names[value];
557
+ if (name !== undefined) {
558
+ map[value] = name;
559
+ format[name] = value;
560
+ }
561
+ }
562
+ if (numeric.length >= 2) {
563
+ // numeric steps (`1` … `9`): the percent setting carries them; `off`/`auto` go through the mode
564
+ const max = Math.max(...numeric);
565
+ const percentMap = { off: 0 };
566
+ for (const n of numeric) {
567
+ percentMap[String(n)] = Math.round((n * 100) / max);
568
+ }
569
+ if (values.includes('auto')) {
570
+ // Matter has no percent setting in Auto: null, as the specification wants it
571
+ percentMap.auto = null;
572
+ }
573
+ this.bind(draft, 'FanControl.percentSetting', mode, { map: percentMap }, { template: `{{ 'off' if percent == 0 else ((percent * ${max} / 100) | round(0, 'ceil') | int) }}` });
574
+ if (format.Low === undefined && max >= 3) {
575
+ // the steps in thirds, both ways: a controller's Low/Medium/High writes the top step of its
576
+ // third, and every reported step reads back as its third — so the mode follows the speed
577
+ // instead of keeping the last named mode, and no step is "not in the map"
578
+ const low = Math.ceil(max / 3);
579
+ const medium = Math.ceil((2 * max) / 3);
580
+ format.Low = String(low);
581
+ format.Medium = String(medium);
582
+ format.High = String(max);
583
+ for (const n of numeric) {
584
+ map[String(n)] = n <= low ? 'Low' : n <= medium ? 'Medium' : 'High';
585
+ }
586
+ }
587
+ }
588
+ if (Object.keys(map).length > 0) {
589
+ this.bind(draft, 'FanControl.fanMode', mode, { map }, { format });
590
+ if (map.auto === 'Auto') {
591
+ this.addFeature(draft, 'FanControl', 'Auto');
592
+ }
593
+ }
594
+ }
595
+ const speed = by.get('speed');
596
+ if (speed !== undefined && mode === undefined) {
597
+ const min = speed.value_min ?? 0;
598
+ const max = speed.value_max ?? 100;
599
+ const scale = { from: [min, max], to: [0, 100] };
600
+ this.bind(draft, 'FanControl.percentSetting', speed, { scale, round: 0 }, { scale, round: 0 });
601
+ }
602
+ for (const feature of features) {
603
+ if (!['state', 'mode', 'speed'].includes(feature.name ?? '')) {
604
+ this.skip(feature);
605
+ }
606
+ }
607
+ }
608
+ /* ----- generic exposes by name ----- */
609
+ numeric(expose) {
610
+ if (!canRead(expose)) {
611
+ this.skip(expose);
612
+ return;
613
+ }
614
+ const name = expose.name ?? '';
615
+ const unit = expose.unit;
616
+ const draft = this.draft(expose.endpoint ?? '');
617
+ switch (name) {
618
+ case 'temperature':
619
+ this.addType(draft, 'TemperatureSensor');
620
+ this.bind(draft, 'TemperatureMeasurement.measuredValue', expose, { unit: temperatureUnit(expose) });
621
+ return;
622
+ case 'humidity':
623
+ this.addType(draft, 'HumiditySensor');
624
+ this.bind(draft, 'RelativeHumidityMeasurement.measuredValue', expose, { unit: 'percent100ths' });
625
+ return;
626
+ case 'pressure':
627
+ if (unit === 'hPa' || unit === 'mbar') {
628
+ this.addType(draft, 'PressureSensor');
629
+ this.bind(draft, 'PressureMeasurement.measuredValue', expose, { round: 0 });
630
+ return;
631
+ }
632
+ if (unit === 'kPa') {
633
+ this.addType(draft, 'PressureSensor');
634
+ this.bind(draft, 'PressureMeasurement.measuredValue', expose, {
635
+ scale: { from: [0, 1], to: [0, 10], clamp: false },
636
+ round: 0,
637
+ });
638
+ return;
639
+ }
640
+ break;
641
+ case 'illuminance_lux':
642
+ case 'illuminance':
643
+ if (name === 'illuminance_lux' || unit === 'lx') {
644
+ if (draft.mappings.some((b) => 'attribute' in b && b.attribute === 'IlluminanceMeasurement.measuredValue')) {
645
+ return;
646
+ }
647
+ this.addType(draft, 'LightSensor');
648
+ this.bind(draft, 'IlluminanceMeasurement.measuredValue', expose, { unit: 'lux' });
649
+ return;
650
+ }
651
+ break;
652
+ case 'battery': {
653
+ const power = this.draft('', 'power');
654
+ this.addType(power, 'PowerSource');
655
+ this.bind(power, 'PowerSource.batPercentRemaining', expose, { unit: 'halfPercent' });
656
+ return;
657
+ }
658
+ case 'voltage':
659
+ if (this.hasBattery && (unit === 'mV' || unit === 'V')) {
660
+ const power = this.draft('', 'power');
661
+ this.addType(power, 'PowerSource');
662
+ this.bind(power, 'PowerSource.batVoltage', expose, unit === 'V' ? { unit: 'volt' } : { round: 0 });
663
+ return;
664
+ }
665
+ break;
666
+ case 'co2':
667
+ this.addType(draft, 'AirQualitySensor');
668
+ this.bind(draft, 'CarbonDioxideConcentrationMeasurement.measuredValue', expose);
669
+ return;
670
+ case 'co':
671
+ this.addType(draft, 'AirQualitySensor');
672
+ this.bind(draft, 'CarbonMonoxideConcentrationMeasurement.measuredValue', expose);
673
+ return;
674
+ case 'voc':
675
+ case 'formaldehyd':
676
+ case 'formaldehyde': {
677
+ const cluster = name === 'voc'
678
+ ? 'TotalVolatileOrganicCompoundsConcentrationMeasurement'
679
+ : 'FormaldehydeConcentrationMeasurement';
680
+ if (unit === 'ppb') {
681
+ this.addType(draft, 'AirQualitySensor');
682
+ this.bind(draft, `${cluster}.measuredValue`, expose);
683
+ return;
684
+ }
685
+ if (unit === 'ppm') {
686
+ this.addType(draft, 'AirQualitySensor');
687
+ this.bind(draft, `${cluster}.measuredValue`, expose, {
688
+ scale: { from: [0, 1], to: [0, 1000], clamp: false },
689
+ });
690
+ return;
691
+ }
692
+ break;
693
+ }
694
+ case 'pm25':
695
+ case 'pm10':
696
+ case 'pm1': {
697
+ const cluster = name === 'pm25'
698
+ ? 'Pm25ConcentrationMeasurement'
699
+ : name === 'pm10'
700
+ ? 'Pm10ConcentrationMeasurement'
701
+ : 'Pm1ConcentrationMeasurement';
702
+ this.addType(draft, 'AirQualitySensor');
703
+ this.bind(draft, `${cluster}.measuredValue`, expose);
704
+ return;
705
+ }
706
+ default:
707
+ break;
708
+ }
709
+ this.skip(expose);
710
+ }
711
+ binary(expose) {
712
+ if (!canRead(expose)) {
713
+ this.skip(expose);
714
+ return;
715
+ }
716
+ const on = text(expose.value_on, 'true');
717
+ const off = text(expose.value_off, 'false');
718
+ const draft = this.draft(expose.endpoint ?? '');
719
+ switch (expose.name) {
720
+ case 'contact':
721
+ // zigbee2mqtt's "on" is the open contact; Matter's true is the closed one
722
+ this.addType(draft, 'ContactSensor');
723
+ this.bind(draft, 'BooleanState.stateValue', expose, { map: { [on]: false, [off]: true } });
724
+ return;
725
+ case 'occupancy':
726
+ case 'presence':
727
+ if (draft.mappings.some((b) => 'attribute' in b && b.attribute === 'OccupancySensing.occupancy')) {
728
+ return;
729
+ }
730
+ this.addType(draft, 'OccupancySensor');
731
+ this.bind(draft, 'OccupancySensing.occupancy', expose, { map: { [on]: true, [off]: false } });
732
+ return;
733
+ case 'water_leak':
734
+ this.addType(draft, 'WaterLeakDetector');
735
+ this.bind(draft, 'BooleanState.stateValue', expose, { map: { [on]: true, [off]: false } });
736
+ return;
737
+ case 'rain':
738
+ this.addType(draft, 'RainSensor');
739
+ this.bind(draft, 'BooleanState.stateValue', expose, { map: { [on]: true, [off]: false } });
740
+ return;
741
+ case 'smoke':
742
+ this.addType(draft, 'SmokeCoAlarm');
743
+ this.addFeature(draft, 'SmokeCoAlarm', 'SmokeAlarm');
744
+ this.bind(draft, 'SmokeCoAlarm.smokeState', expose, { map: { [on]: 'Critical', [off]: 'Normal' } });
745
+ return;
746
+ case 'carbon_monoxide':
747
+ this.addType(draft, 'SmokeCoAlarm');
748
+ this.addFeature(draft, 'SmokeCoAlarm', 'CoAlarm');
749
+ this.bind(draft, 'SmokeCoAlarm.coState', expose, { map: { [on]: 'Critical', [off]: 'Normal' } });
750
+ return;
751
+ case 'battery_low': {
752
+ const power = this.draft('', 'power');
753
+ this.addType(power, 'PowerSource');
754
+ this.bind(power, 'PowerSource.batChargeLevel', expose, { map: { [on]: 'Critical', [off]: 'Ok' } });
755
+ return;
756
+ }
757
+ default:
758
+ this.skip(expose);
759
+ }
760
+ }
761
+ enum(expose) {
762
+ if (!canRead(expose)) {
763
+ this.skip(expose);
764
+ return;
765
+ }
766
+ switch (expose.name) {
767
+ case 'air_quality': {
768
+ const draft = this.draft(expose.endpoint ?? '');
769
+ const names = {
770
+ excellent: 'Good',
771
+ good: 'Fair',
772
+ moderate: 'Moderate',
773
+ poor: 'Poor',
774
+ unhealthy: 'VeryPoor',
775
+ hazardous: 'ExtremelyPoor',
776
+ out_of_range: 'Unknown',
777
+ unknown: 'Unknown',
778
+ };
779
+ const map = {};
780
+ for (const value of (expose.values ?? []).map(String)) {
781
+ const name = names[value];
782
+ if (name !== undefined) {
783
+ map[value] = name;
784
+ }
785
+ }
786
+ this.addType(draft, 'AirQualitySensor');
787
+ this.bind(draft, 'AirQuality.airQuality', expose, { map });
788
+ return;
789
+ }
790
+ case 'action':
791
+ this.actions(expose);
792
+ return;
793
+ case 'moving':
794
+ case 'motor_state':
795
+ this.motionExposes.set(expose.endpoint ?? '', expose);
796
+ this.skip(expose);
797
+ return;
798
+ default:
799
+ this.skip(expose);
800
+ }
801
+ }
802
+ actions(expose) {
803
+ const { buttons, ignored } = parseActions(expose.values ?? []);
804
+ for (const value of ignored) {
805
+ this.unmapped.push(`action:${value}`);
806
+ }
807
+ for (const button of buttons) {
808
+ const id = button.name === '' ? 'button' : `button_${endpointId(button.name)}`;
809
+ const draft = this.draft(expose.endpoint ?? '', id);
810
+ this.addType(draft, 'GenericSwitch');
811
+ draft.options.switch = { multiPressMax: Math.max(2, multiPressMax(button)) };
812
+ draft.mappings.push({
813
+ event: 'Switch',
814
+ status: this.status(expose, { map: Object.fromEntries(button.kinds) }),
815
+ });
816
+ }
817
+ }
818
+ /** one momentary outlet per scene: on recalls it (`{"scene_recall": id}` on the set topic) */
819
+ scenes(scenes) {
820
+ for (const scene of scenes) {
821
+ const draft = this.draft('', `scene_${scene.id}`);
822
+ draft.scene = true;
823
+ draft.label = scene.name === '' ? `Scene ${scene.id}` : scene.name;
824
+ this.addType(draft, 'OnOffPlugInUnit');
825
+ draft.options.onOff = { momentary: SCENE_MOMENTARY };
826
+ draft.mappings.push({
827
+ attribute: 'OnOff.onOff',
828
+ command: { topic: this.setTopic, format: { true: JSON.stringify({ scene_recall: scene.id }) } },
829
+ });
830
+ }
831
+ }
832
+ walk(exposes, model) {
833
+ for (const expose of exposes) {
834
+ switch (expose.type) {
835
+ case 'light':
836
+ this.light(expose);
837
+ break;
838
+ case 'switch':
839
+ this.switch(expose);
840
+ break;
841
+ case 'cover':
842
+ this.cover(expose, model);
843
+ break;
844
+ case 'lock':
845
+ this.lock(expose);
846
+ break;
847
+ case 'climate':
848
+ this.climate(expose);
849
+ break;
850
+ case 'fan':
851
+ this.fan(expose);
852
+ break;
853
+ case 'numeric':
854
+ this.numeric(expose);
855
+ break;
856
+ case 'binary':
857
+ this.binary(expose);
858
+ break;
859
+ case 'enum':
860
+ this.enum(expose);
861
+ break;
862
+ default:
863
+ this.skip(expose);
864
+ }
865
+ }
866
+ this.finishCovers();
867
+ }
868
+ /** the endpoints in their final form: the main one first, children after; `undefined` when nothing maps */
869
+ endpoints() {
870
+ const drafts = [...this.drafts.values()].filter((d) => d.types.length > 0);
871
+ const power = drafts.find((d) => d.id === 'power');
872
+ const real = drafts.filter((d) => d !== power);
873
+ const isButton = (d) => d.types[0] === 'GenericSwitch';
874
+ const isFunction = (d) => !isButton(d) && d.scene !== true;
875
+ // the device itself: the device's own endpoint, else the first child that is no button or scene, else
876
+ // (a remote) its unnamed button, else the first button, else the first scene
877
+ let main = real.find((d) => d.z2mEndpoint === '' && isFunction(d)) ??
878
+ real.find((d) => isFunction(d)) ??
879
+ real.find((d) => d.id === 'button') ??
880
+ real[0];
881
+ if (main === undefined) {
882
+ return undefined;
883
+ }
884
+ if (power !== undefined) {
885
+ this.addType(main, 'PowerSource');
886
+ main.mappings.push(...power.mappings);
887
+ }
888
+ const ordered = [main, ...real.filter((d) => d !== main)];
889
+ main = ordered[0];
890
+ // child endpoints that share their device type with a sibling (or the device itself) carry a number
891
+ // tag in the Descriptor's TagList: Matter's disambiguation rule, which strict matter.js enforces
892
+ const typeCount = new Map();
893
+ for (const draft of ordered) {
894
+ const type = draft.types[0] ?? '';
895
+ typeCount.set(type, (typeCount.get(type) ?? 0) + 1);
896
+ }
897
+ let tag = 0;
898
+ return ordered.map((draft, i) => {
899
+ const endpoint = { deviceTypes: draft.types, mappings: draft.mappings };
900
+ if (i > 0) {
901
+ endpoint.id = endpointId(draft.id);
902
+ if ((typeCount.get(draft.types[0] ?? '') ?? 0) > 1) {
903
+ tag++;
904
+ draft.features.Descriptor = ['TagList'];
905
+ endpoint.attributes = {
906
+ Descriptor: {
907
+ tagList: [
908
+ {
909
+ mfgCode: null,
910
+ namespaceId: NUMBER_NAMESPACE,
911
+ tag,
912
+ label: (draft.label ?? draft.id).slice(0, 64),
913
+ },
914
+ ],
915
+ },
916
+ };
917
+ }
918
+ }
919
+ if (Object.keys(draft.features).length > 0) {
920
+ endpoint.features = draft.features;
921
+ }
922
+ if (Object.keys(draft.options).length > 0) {
923
+ endpoint.options = draft.options;
924
+ }
925
+ if (draft.coalesce > 0) {
926
+ endpoint.coalesce = draft.coalesce;
927
+ }
928
+ return endpoint;
929
+ });
930
+ }
931
+ }
932
+ function featureMap(features) {
933
+ const map = new Map();
934
+ for (const feature of features) {
935
+ if (feature.name !== undefined && !map.has(feature.name)) {
936
+ map.set(feature.name, feature);
937
+ }
938
+ }
939
+ return map;
940
+ }
941
+ function temperatureUnit(expose) {
942
+ return expose.unit === '°F' ? 'fahrenheit' : 'celsius';
943
+ }
944
+ function hasBatteryExpose(exposes) {
945
+ return exposes.some((e) => e.type === 'numeric' && e.name === 'battery');
946
+ }
947
+ /** why a bridge device cannot become a Matter device, or undefined when it can be tried */
948
+ export function unsupportedReason(device) {
949
+ if (device.type === 'Coordinator') {
950
+ return 'the coordinator';
951
+ }
952
+ if (device.supported === false) {
953
+ return 'not supported by zigbee2mqtt';
954
+ }
955
+ if (device.disabled === true) {
956
+ return 'disabled in zigbee2mqtt';
957
+ }
958
+ if (device.interview_completed === false) {
959
+ return 'interview not completed';
960
+ }
961
+ const definition = device.definition;
962
+ if (definition === undefined || definition === null || (definition.exposes ?? []).length === 0) {
963
+ return 'no exposes';
964
+ }
965
+ return undefined;
966
+ }
967
+ /** the baseline for a device description; undefined when nothing of it maps onto Matter */
968
+ export function generateDevice(raw) {
969
+ const exposes = raw.definition?.exposes ?? [];
970
+ const builder = new Builder(raw.base_topic, raw.friendly_name, hasBatteryExpose(exposes));
971
+ builder.walk(exposes, raw.definition?.model);
972
+ builder.scenes(raw.scenes ?? []);
973
+ const endpoints = builder.endpoints();
974
+ if (endpoints === undefined) {
975
+ return undefined;
976
+ }
977
+ const device = {
978
+ name: raw.friendly_name.slice(0, MAX_LABEL),
979
+ ...(label(raw.definition?.vendor) === undefined ? {} : { vendor: label(raw.definition?.vendor) }),
980
+ ...(label(raw.definition?.model) === undefined ? {} : { model: label(raw.definition?.model) }),
981
+ serial: raw.ieee_address.slice(0, MAX_LABEL),
982
+ source: { kind: 'z2m', key: raw.ieee_address, version: rawHash(raw), raw },
983
+ availability: { topic: `${builder.stateTopic}/availability`, template: AVAILABILITY_TEMPLATE },
984
+ endpoints,
985
+ };
986
+ return { device, unmapped: builder.unmapped };
987
+ }
988
+ /* ----- groups ----- */
989
+ export function groupUnion(group, devices) {
990
+ const union = {
991
+ kind: undefined,
992
+ brightness: false,
993
+ colorTemp: undefined,
994
+ xy: false,
995
+ hs: false,
996
+ position: false,
997
+ tilt: false,
998
+ members: 0,
999
+ };
1000
+ const kinds = new Set();
1001
+ for (const member of group.members) {
1002
+ const device = devices.get(member.ieee_address);
1003
+ if (device === undefined) {
1004
+ continue;
1005
+ }
1006
+ union.members++;
1007
+ for (const expose of device.definition?.exposes ?? []) {
1008
+ const by = featureMap(expose.features ?? []);
1009
+ if (expose.type === 'light') {
1010
+ kinds.add('light');
1011
+ union.brightness ||= by.has('brightness');
1012
+ const ct = by.get('color_temp');
1013
+ if (ct !== undefined) {
1014
+ const min = ct.value_min;
1015
+ const max = ct.value_max;
1016
+ union.colorTemp = {
1017
+ min: minOf(union.colorTemp?.min, min),
1018
+ max: maxOf(union.colorTemp?.max, max),
1019
+ };
1020
+ }
1021
+ union.xy ||= by.has('color_xy');
1022
+ union.hs ||= by.has('color_hs');
1023
+ }
1024
+ else if (expose.type === 'switch') {
1025
+ kinds.add('switch');
1026
+ }
1027
+ else if (expose.type === 'cover') {
1028
+ kinds.add('cover');
1029
+ union.position ||= by.has('position');
1030
+ union.tilt ||= by.has('tilt');
1031
+ }
1032
+ }
1033
+ }
1034
+ union.kind = kinds.has('light')
1035
+ ? 'light'
1036
+ : kinds.has('switch')
1037
+ ? 'switch'
1038
+ : kinds.has('cover') && kinds.size === 1
1039
+ ? 'cover'
1040
+ : undefined;
1041
+ return union;
1042
+ }
1043
+ const minOf = (a, b) => a === undefined ? b : b === undefined ? a : Math.min(a, b);
1044
+ const maxOf = (a, b) => a === undefined ? b : b === undefined ? a : Math.max(a, b);
1045
+ export function rawGroup(group, devices, baseTopic) {
1046
+ return {
1047
+ kind: 'group',
1048
+ base_topic: baseTopic,
1049
+ id: group.id,
1050
+ friendly_name: group.friendly_name,
1051
+ members: group.members.map((m) => ({ ieee_address: m.ieee_address, endpoint: m.endpoint })),
1052
+ union: groupUnion(group, devices),
1053
+ ...(sceneList([group.scenes]).length === 0 ? {} : { scenes: sceneList([group.scenes]) }),
1054
+ };
1055
+ }
1056
+ /** a synthetic expose list that describes the union, so the group goes through the same builder */
1057
+ function unionExposes(union) {
1058
+ const all = 7;
1059
+ if (union.kind === 'light') {
1060
+ const features = [
1061
+ { type: 'binary', name: 'state', property: 'state', access: all, value_on: 'ON', value_off: 'OFF' },
1062
+ ];
1063
+ if (union.brightness) {
1064
+ features.push({
1065
+ type: 'numeric',
1066
+ name: 'brightness',
1067
+ property: 'brightness',
1068
+ access: all,
1069
+ value_min: 0,
1070
+ value_max: 254,
1071
+ });
1072
+ }
1073
+ if (union.colorTemp !== undefined) {
1074
+ features.push({
1075
+ type: 'numeric',
1076
+ name: 'color_temp',
1077
+ property: 'color_temp',
1078
+ access: all,
1079
+ ...(union.colorTemp.min === undefined ? {} : { value_min: union.colorTemp.min }),
1080
+ ...(union.colorTemp.max === undefined ? {} : { value_max: union.colorTemp.max }),
1081
+ });
1082
+ }
1083
+ if (union.xy) {
1084
+ features.push({ type: 'composite', name: 'color_xy', property: 'color', access: all });
1085
+ }
1086
+ if (union.hs) {
1087
+ features.push({ type: 'composite', name: 'color_hs', property: 'color', access: all });
1088
+ }
1089
+ return [{ type: 'light', features }];
1090
+ }
1091
+ if (union.kind === 'switch') {
1092
+ return [
1093
+ {
1094
+ type: 'switch',
1095
+ features: [
1096
+ { type: 'binary', name: 'state', property: 'state', access: all, value_on: 'ON', value_off: 'OFF' },
1097
+ ],
1098
+ },
1099
+ ];
1100
+ }
1101
+ if (union.kind === 'cover') {
1102
+ const features = [
1103
+ { type: 'enum', name: 'state', property: 'state', access: 3, values: ['OPEN', 'CLOSE', 'STOP'] },
1104
+ ];
1105
+ if (union.position) {
1106
+ features.push({
1107
+ type: 'numeric',
1108
+ name: 'position',
1109
+ property: 'position',
1110
+ access: all,
1111
+ value_min: 0,
1112
+ value_max: 100,
1113
+ });
1114
+ }
1115
+ if (union.tilt) {
1116
+ features.push({ type: 'numeric', name: 'tilt', property: 'tilt', access: all, value_min: 0, value_max: 100 });
1117
+ }
1118
+ return [{ type: 'cover', features }];
1119
+ }
1120
+ return [];
1121
+ }
1122
+ export function groupUnsupportedReason(union, scenes = []) {
1123
+ if (union.members === 0) {
1124
+ return 'no members';
1125
+ }
1126
+ // a group of other members still recalls its scenes
1127
+ if (union.kind === undefined && scenes.length === 0) {
1128
+ return 'the members are neither lights, switches nor covers';
1129
+ }
1130
+ return undefined;
1131
+ }
1132
+ export function generateGroup(raw) {
1133
+ const builder = new Builder(raw.base_topic, raw.friendly_name, false);
1134
+ builder.walk(unionExposes(raw.union), undefined);
1135
+ builder.scenes(raw.scenes ?? []);
1136
+ const endpoints = builder.endpoints();
1137
+ if (endpoints === undefined) {
1138
+ return undefined;
1139
+ }
1140
+ // a group has no `/get`; zigbee2mqtt answers for its members
1141
+ for (const endpoint of endpoints) {
1142
+ for (const mapping of endpoint.mappings ?? []) {
1143
+ if (mapping.status !== undefined) {
1144
+ delete mapping.status.get;
1145
+ }
1146
+ }
1147
+ }
1148
+ const device = {
1149
+ name: raw.friendly_name.slice(0, MAX_LABEL),
1150
+ vendor: 'Zigbee2MQTT',
1151
+ model: 'Group',
1152
+ serial: `group-${raw.id}`,
1153
+ source: { kind: 'z2m', key: `group:${raw.id}`, version: rawHash(raw), raw },
1154
+ endpoints,
1155
+ };
1156
+ return { device, unmapped: builder.unmapped };
1157
+ }
1158
+ export function isRaw(value) {
1159
+ if (typeof value !== 'object' || value === null) {
1160
+ return false;
1161
+ }
1162
+ const raw = value;
1163
+ return ((raw.kind === 'device' || raw.kind === 'group') &&
1164
+ typeof raw.base_topic === 'string' &&
1165
+ typeof raw.friendly_name === 'string');
1166
+ }
1167
+ /** regenerate the baseline from what `source.raw` holds */
1168
+ export function generate(raw) {
1169
+ return raw.kind === 'device' ? generateDevice(raw) : generateGroup(raw);
1170
+ }
1171
+ //# sourceMappingURL=generate.js.map