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,1376 @@
1
+ /* Home Assistant MQTT discovery → the manual model. All entities of one Home Assistant device (its
2
+ `device.identifiers`) become one Matter device: the primary entity (a light, switch, cover, climate,
3
+ lock, fan, valve) is the node's own endpoint, every other entity a child endpoint, a battery sensor the
4
+ node's power source, event entities and device triggers GenericSwitch buttons. The component → device
5
+ type table is docs/importers.md's. Templates go to the payload engine when it can run them
6
+ (templates.ts); a mapping whose template it cannot run is left out and listed with the template.
7
+ What is generated is the *baseline*; `source.raw` keeps the expanded configs so a user's edits can be
8
+ carried over when a device announces itself again. */
9
+ import { createHash } from 'node:crypto';
10
+ import { multiPressMax, parseAction, parseActions } from "../actions.js";
11
+ import { areaTag } from "./areas.js";
12
+ import { checkTemplate } from "./templates.js";
13
+ import { deviceIdentity } from "./types.js";
14
+ export const SOURCE_KIND = 'ha-discovery';
15
+ /** bumped when the generator's output for the same raw description changes */
16
+ export const GENERATOR_VERSION = 1;
17
+ const MAX_LABEL = 32;
18
+ const MAX_KEY = 64;
19
+ export function isRaw(value) {
20
+ if (typeof value !== 'object' || value === null) {
21
+ return false;
22
+ }
23
+ const raw = value;
24
+ return (raw.kind === 'ha' &&
25
+ typeof raw.prefix === 'string' &&
26
+ typeof raw.identity === 'string' &&
27
+ Array.isArray(raw.entities));
28
+ }
29
+ export function rawHash(raw) {
30
+ return `${GENERATOR_VERSION}.${createHash('sha256').update(JSON.stringify(raw)).digest('hex').slice(0, 12)}`;
31
+ }
32
+ /** a device key the schema accepts: `ha:` plus the identity, cleaned; long ones are cut and hashed */
33
+ export function deviceKey(identity) {
34
+ const cleaned = identity.replace(/[^A-Za-z0-9:._-]/g, '_');
35
+ const key = `ha:${cleaned}`;
36
+ if (key.length <= MAX_KEY) {
37
+ return key;
38
+ }
39
+ const hash = createHash('sha256').update(identity).digest('hex').slice(0, 8);
40
+ return `${key.slice(0, MAX_KEY - 9)}-${hash}`;
41
+ }
42
+ /** an endpoint id the schema accepts */
43
+ export function endpointId(name) {
44
+ const cleaned = name.replace(/[^A-Za-z0-9:._-]/g, '_').slice(0, MAX_KEY);
45
+ return /^[A-Za-z0-9]/.test(cleaned) ? cleaned : `e${cleaned}`;
46
+ }
47
+ const IEEE = /^(?:0x)?([0-9a-fA-F]{16})$/;
48
+ const IEEE_COLONS = /^([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){7})$/;
49
+ /** an IEEE address in zigbee2mqtt's form (`0x` and 16 lower-case hex digits), or undefined */
50
+ function ieeeOf(value) {
51
+ const plain = IEEE.exec(value)?.[1] ?? IEEE_COLONS.exec(value)?.[1]?.replaceAll(':', '');
52
+ return plain === undefined ? undefined : `0x${plain.toLowerCase()}`;
53
+ }
54
+ /**
55
+ * The key of the zigbee2mqtt importer's native description of the same device, when there is one: the
56
+ * identifiers zigbee2mqtt's own discovery uses (`zigbee2mqtt_<ieee>`, `zigbee2mqtt_<n>_<group id>` — with or
57
+ * without an `origin`, which older versions do not send), else a Zigbee IEEE address among the connections
58
+ * (`["zigbee", "0x…"]`, `["ieee", "…"]`) or the identifiers of another source describing a Zigbee device.
59
+ */
60
+ export function nativeKey(identity, device) {
61
+ const identifiers = [
62
+ identity,
63
+ ...(typeof device?.identifiers === 'string' ? [device.identifiers] : []),
64
+ ...(Array.isArray(device?.identifiers) ? device.identifiers : []),
65
+ ].filter((id) => typeof id === 'string');
66
+ for (const id of identifiers) {
67
+ const own = /^zigbee2mqtt_(0x[0-9a-fA-F]{16})$/.exec(id);
68
+ if (own?.[1] !== undefined) {
69
+ return `z2m:${own[1].toLowerCase()}`;
70
+ }
71
+ const group = /^zigbee2mqtt_\d+_(\d+)$/.exec(id);
72
+ if (group?.[1] !== undefined) {
73
+ return `z2m:group:${group[1]}`;
74
+ }
75
+ }
76
+ for (const connection of Array.isArray(device?.connections) ? device.connections : []) {
77
+ // the payload is foreign JSON: the declared tuple type is not checked when it is parsed
78
+ const [type, value] = Array.isArray(connection) ? connection : [];
79
+ if (typeof type === 'string' && typeof value === 'string') {
80
+ const zigbee = type.toLowerCase() === 'zigbee' || type.toLowerCase() === 'ieee';
81
+ const ieee = zigbee ? ieeeOf(value) : undefined;
82
+ if (ieee !== undefined) {
83
+ return `z2m:${ieee}`;
84
+ }
85
+ }
86
+ }
87
+ for (const id of identifiers) {
88
+ // a bare address only in its 0x form: 16 hex digits alone could be any serial number
89
+ const ieee = id.startsWith('0x') ? ieeeOf(id) : undefined;
90
+ if (ieee !== undefined) {
91
+ return `z2m:${ieee}`;
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+ /** config keys the generator never reads: dropped from `source.raw` so the file stays lean and private */
97
+ const DROPPED_KEYS = new Set([
98
+ 'icon',
99
+ 'entity_picture',
100
+ 'json_attributes_topic',
101
+ 'json_attributes_template',
102
+ 'json_attributes',
103
+ 'default_entity_id',
104
+ 'force_update',
105
+ 'migrate_discovery',
106
+ 'qos',
107
+ 'encoding',
108
+ ]);
109
+ export function trimConfig(config) {
110
+ const out = {};
111
+ for (const [key, value] of Object.entries(config)) {
112
+ if (DROPPED_KEYS.has(key) || key === 'device' || key === 'origin' || value === undefined) {
113
+ continue;
114
+ }
115
+ out[key] = value;
116
+ }
117
+ return out;
118
+ }
119
+ export function trimDevice(device) {
120
+ const out = {};
121
+ for (const key of [
122
+ 'identifiers',
123
+ 'connections',
124
+ 'name',
125
+ 'manufacturer',
126
+ 'model',
127
+ 'model_id',
128
+ 'sw_version',
129
+ 'hw_version',
130
+ 'serial_number',
131
+ 'suggested_area',
132
+ 'via_device',
133
+ ]) {
134
+ if (device[key] !== undefined) {
135
+ out[key] = device[key];
136
+ }
137
+ }
138
+ return out;
139
+ }
140
+ export function trimOrigin(origin) {
141
+ if (origin === undefined) {
142
+ return undefined;
143
+ }
144
+ const out = {};
145
+ if (typeof origin.name === 'string') {
146
+ out.name = origin.name;
147
+ }
148
+ if (typeof origin.sw_version === 'string') {
149
+ out.sw_version = origin.sw_version;
150
+ }
151
+ return out;
152
+ }
153
+ /** ms a scene's outlet stays on after it was activated */
154
+ export const SCENE_MOMENTARY = 1000;
155
+ /** the order device types take on an endpoint and the order entities take as the device's own endpoint */
156
+ const TYPE_ORDER = [
157
+ 'ExtendedColorLight',
158
+ 'ColorTemperatureLight',
159
+ 'DimmableLight',
160
+ 'OnOffLight',
161
+ 'WindowCovering',
162
+ 'Thermostat',
163
+ 'DoorLock',
164
+ 'Fan',
165
+ 'WaterValve',
166
+ 'OnOffPlugInUnit',
167
+ 'OccupancySensor',
168
+ 'ContactSensor',
169
+ 'WaterLeakDetector',
170
+ 'WaterFreezeDetector',
171
+ 'RainSensor',
172
+ 'SmokeCoAlarm',
173
+ 'AirQualitySensor',
174
+ 'TemperatureSensor',
175
+ 'HumiditySensor',
176
+ 'PressureSensor',
177
+ 'FlowSensor',
178
+ 'LightSensor',
179
+ 'GenericSwitch',
180
+ 'PowerSource',
181
+ ];
182
+ const typeRank = (name) => {
183
+ const i = TYPE_ORDER.indexOf(name);
184
+ return i === -1 ? TYPE_ORDER.length : i;
185
+ };
186
+ /** the order components are walked: primaries first, so the first draft is the device's own endpoint */
187
+ const COMPONENT_ORDER = [
188
+ 'light',
189
+ 'cover',
190
+ 'climate',
191
+ 'lock',
192
+ 'fan',
193
+ 'valve',
194
+ 'switch',
195
+ 'binary_sensor',
196
+ 'sensor',
197
+ 'event',
198
+ 'device_trigger',
199
+ ];
200
+ const componentRank = (name) => {
201
+ const i = COMPONENT_ORDER.indexOf(name);
202
+ return i === -1 ? COMPONENT_ORDER.length : i;
203
+ };
204
+ const PRIMARY = new Set(['light', 'switch', 'cover', 'climate', 'lock', 'fan', 'valve']);
205
+ /** the Common Number semantic tag namespace (Matter namespaces, 0x07): sibling endpoints of one type */
206
+ const NUMBER_NAMESPACE = 7;
207
+ /** the Common Area namespace (0x10): the area a device is in */
208
+ const AREA_NAMESPACE = 16;
209
+ const text = (value, fallback) => typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : fallback;
210
+ const str = (value) => (typeof value === 'string' && value !== '' ? value : undefined);
211
+ const num = (value) => {
212
+ if (typeof value === 'number' && Number.isFinite(value)) {
213
+ return value;
214
+ }
215
+ if (typeof value === 'string' && value.trim() !== '') {
216
+ const n = Number(value);
217
+ return Number.isFinite(n) ? n : undefined;
218
+ }
219
+ return undefined;
220
+ };
221
+ const list = (value) => Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
222
+ const label = (value) => value === undefined || value === '' ? undefined : value.slice(0, MAX_LABEL);
223
+ function entityName(entity) {
224
+ const name = entity.config.name;
225
+ return typeof name === 'string' && name !== '' ? name : entity.id;
226
+ }
227
+ class Builder {
228
+ drafts = new Map();
229
+ unmapped = [];
230
+ /** the device's power source, merged into the device's own endpoint at the end */
231
+ power;
232
+ availability;
233
+ availabilityFrom;
234
+ /** device triggers accumulate per topic and button */
235
+ triggers = new Map();
236
+ draft(id, entity, primary = false) {
237
+ let unique = endpointId(id);
238
+ let n = 1;
239
+ while (this.drafts.has(unique) && this.drafts.get(unique)?.entity !== entity) {
240
+ n++;
241
+ unique = `${endpointId(id)}_${n}`;
242
+ }
243
+ let draft = this.drafts.get(unique);
244
+ if (draft === undefined) {
245
+ draft = {
246
+ id: unique,
247
+ entity,
248
+ primary,
249
+ types: [],
250
+ mappings: [],
251
+ features: {},
252
+ attributes: {},
253
+ options: {},
254
+ coalesce: 0,
255
+ };
256
+ this.drafts.set(unique, draft);
257
+ }
258
+ return draft;
259
+ }
260
+ powerDraft() {
261
+ this.power ??= {
262
+ id: 'power',
263
+ entity: undefined,
264
+ primary: false,
265
+ types: ['PowerSource'],
266
+ mappings: [],
267
+ features: {},
268
+ attributes: {},
269
+ options: {},
270
+ coalesce: 0,
271
+ };
272
+ return this.power;
273
+ }
274
+ addType(draft, type) {
275
+ if (!draft.types.includes(type)) {
276
+ draft.types.push(type);
277
+ draft.types.sort((a, b) => typeRank(a) - typeRank(b));
278
+ }
279
+ }
280
+ addFeature(draft, cluster, feature) {
281
+ const features = (draft.features[cluster] ??= []);
282
+ if (!features.includes(feature)) {
283
+ features.push(feature);
284
+ }
285
+ }
286
+ skip(entity, reason) {
287
+ this.unmapped.push(`${entity.component} "${entityName(entity)}": ${reason}`);
288
+ }
289
+ /** a template the engine can run, or undefined (listed) */
290
+ template(entity, field, side, extra = []) {
291
+ const source = entity.config[field];
292
+ if (typeof source !== 'string' || source === '') {
293
+ return undefined;
294
+ }
295
+ const check = checkTemplate(source, side, extra);
296
+ if (!check.ok) {
297
+ this.unmapped.push(`${entity.component} "${entityName(entity)}": ${field} ${check.reason}: ${source}`);
298
+ return `\u0000${source}`;
299
+ }
300
+ return source;
301
+ }
302
+ /** a status half; undefined when the template cannot be run (already listed) or there is no topic */
303
+ status(entity, topicField, templateField, extra = {}) {
304
+ const topic = str(entity.config[topicField]);
305
+ if (topic === undefined) {
306
+ return undefined;
307
+ }
308
+ const half = { topic, ...extra };
309
+ if (templateField !== undefined) {
310
+ const template = this.template(entity, templateField, 'status');
311
+ if (template?.startsWith('\u0000') === true) {
312
+ return undefined;
313
+ }
314
+ if (template !== undefined) {
315
+ half.template = template;
316
+ }
317
+ }
318
+ const expire = num(entity.config.expire_after);
319
+ if (expire !== undefined && expire > 0) {
320
+ half.expire = expire;
321
+ }
322
+ return half;
323
+ }
324
+ /** a command half; undefined when the template cannot be run (already listed) or there is no topic */
325
+ command(entity, topicField, templateField, extra = {},
326
+ /** `{% set … %}` lines that give Home Assistant's variables their meaning before the template */
327
+ prelude = '', extraVariables = []) {
328
+ const topic = str(entity.config[topicField]);
329
+ if (topic === undefined) {
330
+ return undefined;
331
+ }
332
+ const half = { topic, ...extra };
333
+ if (templateField !== undefined) {
334
+ const template = this.template(entity, templateField, 'command', extraVariables);
335
+ if (template?.startsWith('\u0000') === true) {
336
+ return undefined;
337
+ }
338
+ if (template !== undefined) {
339
+ delete half.format;
340
+ half.template = prelude + template;
341
+ }
342
+ }
343
+ if (entity.config.optimistic === true) {
344
+ half.optimistic = true;
345
+ }
346
+ if (entity.config.retain === true) {
347
+ half.retain = true;
348
+ }
349
+ return half;
350
+ }
351
+ bind(draft, target, status, command) {
352
+ if (status === undefined && command === undefined) {
353
+ return;
354
+ }
355
+ draft.mappings.push({
356
+ ...target,
357
+ ...(status === undefined ? {} : { status }),
358
+ ...(command === undefined ? {} : { command }),
359
+ });
360
+ }
361
+ takeAvailability(entity) {
362
+ const c = entity.config;
363
+ const entries = c.availability;
364
+ let availability;
365
+ if (Array.isArray(entries) && entries.length > 0) {
366
+ const topics = entries.map((entry) => {
367
+ const topic = { topic: entry.topic };
368
+ if (entry.value_template !== undefined) {
369
+ topic.template = entry.value_template;
370
+ }
371
+ else if (typeof c.availability_template === 'string') {
372
+ topic.template = c.availability_template;
373
+ }
374
+ if (entry.payload_available !== undefined) {
375
+ topic.online = entry.payload_available;
376
+ }
377
+ if (entry.payload_not_available !== undefined) {
378
+ topic.offline = entry.payload_not_available;
379
+ }
380
+ return topic;
381
+ });
382
+ const mode = c.availability_mode;
383
+ availability =
384
+ topics.length === 1 && mode === undefined
385
+ ? topics[0]
386
+ : { topics, mode: mode === 'all' || mode === 'any' ? mode : 'latest' };
387
+ }
388
+ else if (typeof c.availability_topic === 'string' && c.availability_topic !== '') {
389
+ const topic = { topic: c.availability_topic };
390
+ if (typeof c.availability_template === 'string') {
391
+ topic.template = c.availability_template;
392
+ }
393
+ if (typeof c.payload_available === 'string') {
394
+ topic.online = c.payload_available;
395
+ }
396
+ if (typeof c.payload_not_available === 'string') {
397
+ topic.offline = c.payload_not_available;
398
+ }
399
+ availability = topic;
400
+ }
401
+ if (availability === undefined) {
402
+ return;
403
+ }
404
+ for (const topic of 'topics' in availability ? availability.topics : [availability]) {
405
+ if (topic.template !== undefined && !checkTemplate(topic.template, 'status').ok) {
406
+ delete topic.template;
407
+ }
408
+ }
409
+ // the device takes the availability of its primary entity, else the first entity that has one
410
+ if (this.availability === undefined || (PRIMARY.has(entity.component) && this.availabilityFrom !== 'primary')) {
411
+ this.availability = availability;
412
+ this.availabilityFrom = PRIMARY.has(entity.component) ? 'primary' : 'entity';
413
+ }
414
+ }
415
+ /* ----- the components ----- */
416
+ onOffMapping(entity, draft, stateTopic, stateTemplate, on, off, stateOn = on, stateOff = off) {
417
+ // lights and fans document `state_value_template`; the older `value_template` is still what Tasmota sends
418
+ const templateField = entity.config[stateTemplate] === undefined && typeof entity.config.value_template === 'string'
419
+ ? 'value_template'
420
+ : stateTemplate;
421
+ const status = this.status(entity, stateTopic, templateField, { map: { [stateOn]: true, [stateOff]: false } });
422
+ const command = this.command(entity, 'command_topic', 'command_template', { format: { true: on, false: off } }, `{% set value = ${JSON.stringify(on)} if value else ${JSON.stringify(off)} %}`);
423
+ this.bind(draft, { attribute: 'OnOff.onOff' }, status, command);
424
+ }
425
+ /** a scene: a momentary outlet; on activates it (`payload_on` to the command topic), off does nothing */
426
+ scene(entity) {
427
+ const command = this.command(entity, 'command_topic', undefined, {
428
+ payload: text(entity.config.payload_on, 'ON'),
429
+ });
430
+ if (command === undefined) {
431
+ this.skip(entity, 'no command_topic');
432
+ return;
433
+ }
434
+ const draft = this.draft(entity.id, entity);
435
+ draft.scene = true;
436
+ draft.label = entityName(entity);
437
+ this.addType(draft, 'OnOffPlugInUnit');
438
+ draft.options.onOff = { momentary: SCENE_MOMENTARY };
439
+ this.bind(draft, { attribute: 'OnOff.onOff' }, undefined, command);
440
+ }
441
+ switch(entity) {
442
+ const c = entity.config;
443
+ const draft = this.draft(entity.id, entity, true);
444
+ this.addType(draft, 'OnOffPlugInUnit');
445
+ const on = text(c.payload_on, 'ON');
446
+ const off = text(c.payload_off, 'OFF');
447
+ this.onOffMapping(entity, draft, 'state_topic', 'value_template', on, off, text(c.state_on, on), text(c.state_off, off));
448
+ }
449
+ light(entity) {
450
+ const c = entity.config;
451
+ const schema = str(c.schema) ?? 'default';
452
+ if (schema === 'json') {
453
+ this.lightJson(entity);
454
+ return;
455
+ }
456
+ if (schema === 'template') {
457
+ this.lightTemplate(entity);
458
+ return;
459
+ }
460
+ const draft = this.draft(entity.id, entity, true);
461
+ const on = text(c.payload_on, 'ON');
462
+ const off = text(c.payload_off, 'OFF');
463
+ const brightness = str(c.brightness_command_topic) !== undefined || str(c.brightness_state_topic) !== undefined;
464
+ const colorTemp = str(c.color_temp_command_topic) !== undefined || str(c.color_temp_state_topic) !== undefined;
465
+ const hs = str(c.hs_command_topic) !== undefined || str(c.hs_state_topic) !== undefined;
466
+ const xy = str(c.xy_command_topic) !== undefined || str(c.xy_state_topic) !== undefined;
467
+ const rgb = str(c.rgb_command_topic) !== undefined || str(c.rgb_state_topic) !== undefined;
468
+ this.addType(draft, hs || xy || rgb
469
+ ? 'ExtendedColorLight'
470
+ : colorTemp
471
+ ? 'ColorTemperatureLight'
472
+ : brightness
473
+ ? 'DimmableLight'
474
+ : 'OnOffLight');
475
+ this.lightOptions(draft, c);
476
+ this.onOffMapping(entity, draft, 'state_topic', 'state_value_template', on, off);
477
+ if (brightness) {
478
+ const scale = num(c.brightness_scale) ?? 255;
479
+ const steps = { scale: { from: [1, scale], to: [1, 254] } };
480
+ this.bind(draft, { attribute: 'LevelControl.currentLevel' }, this.status(entity, 'brightness_state_topic', 'brightness_value_template', { ...steps, type: 'number' }), this.command(entity, 'brightness_command_topic', 'brightness_command_template', { ...steps, round: 0 }));
481
+ }
482
+ if (colorTemp) {
483
+ const kelvin = c.color_temp_kelvin === true;
484
+ const unit = kelvin ? { unit: 'kelvin' } : {};
485
+ this.bind(draft, { attribute: 'ColorControl.colorTemperatureMireds' }, this.status(entity, 'color_temp_state_topic', 'color_temp_value_template', { ...unit, type: 'number' }), this.command(entity, 'color_temp_command_topic', 'color_temp_command_template', { ...unit, round: 0 }));
486
+ }
487
+ if (xy) {
488
+ this.bind(draft, { attribute: 'ColorControl.colorXy' }, this.status(entity, 'xy_state_topic', 'xy_value_template'), this.command(entity, 'xy_command_topic', 'xy_command_template', { template: '{{ x }},{{ y }}' }));
489
+ }
490
+ if (hs) {
491
+ if (xy) {
492
+ this.addFeature(draft, 'ColorControl', 'HueSaturation');
493
+ }
494
+ this.bind(draft, { attribute: 'ColorControl.colorHs' }, this.status(entity, 'hs_state_topic', 'hs_value_template'), this.command(entity, 'hs_command_topic', 'hs_command_template', {
495
+ template: '{{ hue }},{{ saturation }}',
496
+ }));
497
+ }
498
+ if (rgb) {
499
+ this.bind(draft, { attribute: 'ColorControl.colorRgb' }, this.status(entity, 'rgb_state_topic', 'rgb_value_template'), this.command(entity, 'rgb_command_topic', 'rgb_command_template', {
500
+ template: '{{ red }},{{ green }},{{ blue }}',
501
+ }));
502
+ }
503
+ if ((hs || xy || rgb) && colorTemp) {
504
+ this.colorMode(entity, draft, 'color_mode_state_topic', 'color_mode_value_template', hs && !xy);
505
+ }
506
+ for (const [field, what] of [
507
+ ['rgbw_command_topic', 'RGBW white channel'],
508
+ ['rgbww_command_topic', 'RGBWW white channels'],
509
+ ['white_command_topic', 'white mode'],
510
+ ['effect_command_topic', 'effects'],
511
+ ]) {
512
+ if (str(c[field]) !== undefined) {
513
+ this.skip(entity, `${what} have no Matter equivalent`);
514
+ }
515
+ }
516
+ }
517
+ lightOptions(draft, c) {
518
+ const light = (draft.options.light ??= {});
519
+ const onCommandType = str(c.on_command_type);
520
+ if (onCommandType === 'first' || onCommandType === 'last' || onCommandType === 'brightness') {
521
+ light.onCommandType = onCommandType;
522
+ }
523
+ const maxKelvin = num(c.max_kelvin);
524
+ const minKelvin = num(c.min_kelvin);
525
+ const minMireds = num(c.min_mireds) ?? (maxKelvin === undefined || maxKelvin <= 0 ? undefined : 1e6 / maxKelvin);
526
+ const maxMireds = num(c.max_mireds) ?? (minKelvin === undefined || minKelvin <= 0 ? undefined : 1e6 / minKelvin);
527
+ if (minMireds !== undefined) {
528
+ light.minMireds = Math.max(1, Math.round(minMireds));
529
+ }
530
+ if (maxMireds !== undefined) {
531
+ light.maxMireds = Math.min(65279, Math.round(maxMireds));
532
+ }
533
+ if (Object.keys(light).length === 0) {
534
+ delete draft.options.light;
535
+ }
536
+ }
537
+ colorMode(entity, draft, topicField, templateField, hsOnly) {
538
+ const colour = hsOnly ? 'CurrentHueAndCurrentSaturation' : 'CurrentXAndCurrentY';
539
+ const status = this.status(entity, topicField, templateField, {
540
+ map: {
541
+ xy: 'CurrentXAndCurrentY',
542
+ hs: 'CurrentHueAndCurrentSaturation',
543
+ rgb: colour,
544
+ rgbw: colour,
545
+ rgbww: colour,
546
+ color_temp: 'ColorTemperatureMireds',
547
+ },
548
+ });
549
+ this.bind(draft, { attribute: 'ColorControl.colorMode' }, status);
550
+ }
551
+ lightJson(entity) {
552
+ const c = entity.config;
553
+ const draft = this.draft(entity.id, entity, true);
554
+ const modes = new Set(list(c.supported_color_modes));
555
+ const brightness = c.brightness === true || modes.has('brightness');
556
+ const colorTemp = modes.has('color_temp');
557
+ const xy = modes.has('xy');
558
+ const hs = modes.has('hs');
559
+ const rgb = modes.has('rgb') || modes.has('rgbw') || modes.has('rgbww');
560
+ this.addType(draft, xy || hs || rgb
561
+ ? 'ExtendedColorLight'
562
+ : colorTemp
563
+ ? 'ColorTemperatureLight'
564
+ : brightness
565
+ ? 'DimmableLight'
566
+ : 'OnOffLight');
567
+ this.lightOptions(draft, c);
568
+ draft.coalesce = 50;
569
+ const state = str(c.state_topic);
570
+ const command = str(c.command_topic);
571
+ const status = (extract, extra = {}) => {
572
+ if (state === undefined) {
573
+ return undefined;
574
+ }
575
+ const half = { topic: state, extract, ...extra };
576
+ const expire = num(c.expire_after);
577
+ if (expire !== undefined && expire > 0) {
578
+ half.expire = expire;
579
+ }
580
+ return half;
581
+ };
582
+ const cmd = (extra) => command === undefined
583
+ ? undefined
584
+ : { topic: command, ...extra, ...(c.retain === true ? { retain: true } : {}) };
585
+ this.bind(draft, { attribute: 'OnOff.onOff' }, status('state', { map: { ON: true, OFF: false } }), cmd({ wrap: 'state', format: { true: 'ON', false: 'OFF' } }));
586
+ if (brightness) {
587
+ const scale = num(c.brightness_scale) ?? 255;
588
+ const steps = { scale: { from: [1, scale], to: [1, 254] } };
589
+ this.bind(draft, { attribute: 'LevelControl.currentLevel' }, status('brightness', { ...steps, type: 'number' }), cmd({ wrap: 'brightness', ...steps, round: 0 }));
590
+ }
591
+ if (colorTemp) {
592
+ const unit = c.color_temp_kelvin === true ? { unit: 'kelvin' } : {};
593
+ this.bind(draft, { attribute: 'ColorControl.colorTemperatureMireds' }, status('color_temp', { ...unit, type: 'number' }), cmd({ wrap: 'color_temp', ...unit, round: 0 }));
594
+ }
595
+ if (xy) {
596
+ this.bind(draft, { attribute: 'ColorControl.colorXy' }, status('color'), cmd({ wrap: 'color' }));
597
+ if (hs) {
598
+ this.addFeature(draft, 'ColorControl', 'HueSaturation');
599
+ }
600
+ }
601
+ else if (hs) {
602
+ this.bind(draft, { attribute: 'ColorControl.colorHs' }, status('color'), cmd({ template: '{"state": "ON", "color": {"h": {{ hue }}, "s": {{ saturation }}}}' }));
603
+ }
604
+ else if (rgb) {
605
+ this.bind(draft, { attribute: 'ColorControl.colorRgb' }, status('color'), cmd({ template: '{"state": "ON", "color": {"r": {{ red }}, "g": {{ green }}, "b": {{ blue }}}}' }));
606
+ }
607
+ if ((xy || hs || rgb) && colorTemp) {
608
+ const colour = hs && !xy ? 'CurrentHueAndCurrentSaturation' : 'CurrentXAndCurrentY';
609
+ this.bind(draft, { attribute: 'ColorControl.colorMode' }, status('color_mode', {
610
+ map: {
611
+ xy: 'CurrentXAndCurrentY',
612
+ hs: 'CurrentHueAndCurrentSaturation',
613
+ rgb: colour,
614
+ rgbw: colour,
615
+ rgbww: colour,
616
+ color_temp: 'ColorTemperatureMireds',
617
+ },
618
+ }));
619
+ }
620
+ if (modes.has('rgbw') || modes.has('rgbww') || modes.has('white')) {
621
+ this.skip(entity, 'white channels have no Matter equivalent');
622
+ }
623
+ if (c.effect === true) {
624
+ this.skip(entity, 'effects have no Matter equivalent');
625
+ }
626
+ }
627
+ lightTemplate(entity) {
628
+ const c = entity.config;
629
+ const draft = this.draft(entity.id, entity, true);
630
+ const brightness = str(c.brightness_template) !== undefined;
631
+ const colorTemp = str(c.color_temp_template) !== undefined;
632
+ this.addType(draft, colorTemp ? 'ColorTemperatureLight' : brightness ? 'DimmableLight' : 'OnOffLight');
633
+ this.lightOptions(draft, c);
634
+ const on = this.template(entity, 'command_on_template', 'command');
635
+ const off = this.template(entity, 'command_off_template', 'command');
636
+ const usable = (t) => t?.startsWith('\u0000') === true ? undefined : t;
637
+ const onTemplate = usable(on);
638
+ const offTemplate = usable(off);
639
+ const command = str(c.command_topic);
640
+ const onOffCommand = command !== undefined && onTemplate !== undefined && offTemplate !== undefined
641
+ ? { topic: command, template: `{% if value %}${onTemplate}{% else %}${offTemplate}{% endif %}` }
642
+ : undefined;
643
+ this.bind(draft, { attribute: 'OnOff.onOff', comment: 'command_on_template / command_off_template' }, this.status(entity, 'state_topic', 'state_template', { map: { on: true, off: false } }), onOffCommand);
644
+ if (brightness) {
645
+ const steps = { scale: { from: [1, 255], to: [1, 254] } };
646
+ this.bind(draft, { attribute: 'LevelControl.currentLevel', comment: 'command_on_template' }, this.status(entity, 'state_topic', 'brightness_template', { ...steps, type: 'number' }), command !== undefined && onTemplate !== undefined
647
+ ? { topic: command, template: onTemplate, ...steps, round: 0 }
648
+ : undefined);
649
+ }
650
+ if (colorTemp) {
651
+ this.bind(draft, { attribute: 'ColorControl.colorTemperatureMireds', comment: 'command_on_template' }, this.status(entity, 'state_topic', 'color_temp_template', { type: 'number' }), command !== undefined && onTemplate !== undefined
652
+ ? { topic: command, template: onTemplate, round: 0 }
653
+ : undefined);
654
+ }
655
+ if (str(c.red_template) !== undefined || str(c.hue_template) !== undefined) {
656
+ this.skip(entity, 'colour through separate templates is not mapped');
657
+ }
658
+ }
659
+ cover(entity) {
660
+ const c = entity.config;
661
+ const draft = this.draft(entity.id, entity, true);
662
+ this.addType(draft, 'WindowCovering');
663
+ const positionOpen = num(c.position_open) ?? 100;
664
+ const positionClosed = num(c.position_closed) ?? 0;
665
+ // Home Assistant counts position_open (100) = open; Matter 0 = open
666
+ const scale = { from: [positionClosed, positionOpen], to: [10000, 0] };
667
+ const positionAware = str(c.position_topic) !== undefined;
668
+ if (positionAware) {
669
+ this.bind(draft, { attribute: 'WindowCovering.currentPositionLiftPercent100ths' }, this.status(entity, 'position_topic', 'position_template', { scale, type: 'number' }));
670
+ }
671
+ if (str(c.set_position_topic) !== undefined) {
672
+ this.bind(draft, { attribute: 'WindowCovering.targetPositionLiftPercent100ths' }, undefined, this.command(entity, 'set_position_topic', 'set_position_template', { scale, round: 0 }, '{% set position = open %}', ['position']));
673
+ }
674
+ const stateTopic = str(c.state_topic);
675
+ if (stateTopic !== undefined) {
676
+ const map = {};
677
+ const put = (field, fallback, kind) => {
678
+ map[text(c[field], fallback)] = kind;
679
+ };
680
+ put('state_opening', 'opening', 'opening');
681
+ put('state_closing', 'closing', 'closing');
682
+ put('state_stopped', 'stopped', 'stopped');
683
+ if (!positionAware) {
684
+ put('state_open', 'open', 'open');
685
+ put('state_closed', 'closed', 'closed');
686
+ }
687
+ this.bind(draft, { attribute: 'WindowCovering.motion' }, this.status(entity, 'state_topic', 'value_template', { map }));
688
+ }
689
+ const command = str(c.command_topic);
690
+ if (command !== undefined) {
691
+ const open = c.payload_open === null ? undefined : text(c.payload_open, 'OPEN');
692
+ const close = c.payload_close === null ? undefined : text(c.payload_close, 'CLOSE');
693
+ const stop = c.payload_stop === null ? undefined : text(c.payload_stop, 'STOP');
694
+ if (!positionAware || str(c.set_position_topic) === undefined) {
695
+ if (open !== undefined) {
696
+ this.bind(draft, { invoke: 'WindowCovering.upOrOpen' }, undefined, { topic: command, payload: open });
697
+ }
698
+ if (close !== undefined) {
699
+ this.bind(draft, { invoke: 'WindowCovering.downOrClose' }, undefined, {
700
+ topic: command,
701
+ payload: close,
702
+ });
703
+ }
704
+ }
705
+ if (stop !== undefined) {
706
+ this.bind(draft, { invoke: 'WindowCovering.stopMotion' }, undefined, { topic: command, payload: stop });
707
+ }
708
+ }
709
+ if (str(c.tilt_status_topic) !== undefined || str(c.tilt_command_topic) !== undefined) {
710
+ const tiltMin = num(c.tilt_min) ?? 0;
711
+ const tiltMax = num(c.tilt_max) ?? 100;
712
+ const closed = num(c.tilt_closed_value) ?? tiltMin;
713
+ const opened = num(c.tilt_opened_value) ?? tiltMax;
714
+ const tilt = { from: [closed, opened], to: [10000, 0] };
715
+ this.bind(draft, { attribute: 'WindowCovering.currentPositionTiltPercent100ths' }, this.status(entity, 'tilt_status_topic', 'tilt_status_template', { scale: tilt, type: 'number' }));
716
+ this.bind(draft, { attribute: 'WindowCovering.targetPositionTiltPercent100ths' }, undefined, this.command(entity, 'tilt_command_topic', 'tilt_command_template', { scale: tilt, round: 0 }, '{% set tilt_position = open %}', ['tilt_position']));
717
+ }
718
+ const deviceClass = str(c.device_class);
719
+ if (deviceClass === 'garage' || deviceClass === 'gate' || deviceClass === 'door') {
720
+ this.unmapped.push(`${entity.component} "${entityName(entity)}": device_class ${deviceClass} is shown as a window covering`);
721
+ }
722
+ }
723
+ climate(entity) {
724
+ const c = entity.config;
725
+ const draft = this.draft(entity.id, entity, true);
726
+ this.addType(draft, 'Thermostat');
727
+ draft.coalesce = 50;
728
+ const unit = str(c.temperature_unit) === 'F' ? 'fahrenheit' : 'celsius';
729
+ const climate = (draft.options.climate ??= {});
730
+ const modes = list(c.modes).length > 0 ? list(c.modes) : ['auto', 'off', 'cool', 'heat', 'dry', 'fan_only'];
731
+ const heat = modes.includes('heat') || modes.includes('auto') || modes.includes('heat_cool');
732
+ const cool = modes.includes('cool') || modes.includes('auto') || modes.includes('heat_cool');
733
+ this.bind(draft, { attribute: 'Thermostat.localTemperature' }, this.status(entity, 'current_temperature_topic', 'current_temperature_template', { unit, type: 'number' }));
734
+ const minTemp = num(c.min_temp);
735
+ const maxTemp = num(c.max_temp);
736
+ const ranged = str(c.temperature_low_command_topic) !== undefined || str(c.temperature_high_command_topic) !== undefined;
737
+ if (heat || !cool) {
738
+ this.bind(draft, { attribute: 'Thermostat.occupiedHeatingSetpoint' }, this.status(entity, ranged ? 'temperature_low_state_topic' : 'temperature_state_topic', ranged ? 'temperature_low_state_template' : 'temperature_state_template', { unit, type: 'number' }), this.command(entity, ranged ? 'temperature_low_command_topic' : 'temperature_command_topic', ranged ? 'temperature_low_command_template' : 'temperature_command_template', { unit, round: 1 }));
739
+ if (minTemp !== undefined) {
740
+ climate.minHeat = minTemp;
741
+ }
742
+ if (maxTemp !== undefined) {
743
+ climate.maxHeat = maxTemp;
744
+ }
745
+ }
746
+ if (cool) {
747
+ this.bind(draft, { attribute: 'Thermostat.occupiedCoolingSetpoint' }, this.status(entity, ranged ? 'temperature_high_state_topic' : 'temperature_state_topic', ranged ? 'temperature_high_state_template' : 'temperature_state_template', { unit, type: 'number' }), this.command(entity, ranged ? 'temperature_high_command_topic' : 'temperature_command_topic', ranged ? 'temperature_high_command_template' : 'temperature_command_template', { unit, round: 1 }));
748
+ if (minTemp !== undefined) {
749
+ climate.minCool = minTemp;
750
+ }
751
+ if (maxTemp !== undefined) {
752
+ climate.maxCool = maxTemp;
753
+ }
754
+ }
755
+ const names = {
756
+ off: 'Off',
757
+ heat: 'Heat',
758
+ cool: 'Cool',
759
+ auto: 'Auto',
760
+ heat_cool: 'Auto',
761
+ dry: 'Dry',
762
+ fan_only: 'FanOnly',
763
+ };
764
+ const map = {};
765
+ const format = {};
766
+ const sets = [];
767
+ for (const mode of modes) {
768
+ const name = names[mode];
769
+ if (name !== undefined) {
770
+ map[mode] = name;
771
+ format[name] ??= mode;
772
+ }
773
+ }
774
+ for (const [name, mode] of Object.entries(format)) {
775
+ sets.push(`${JSON.stringify(mode)} if name == ${JSON.stringify(name)}`);
776
+ }
777
+ this.bind(draft, { attribute: 'Thermostat.systemMode' }, this.status(entity, 'mode_state_topic', 'mode_state_template', { map }), this.command(entity, 'mode_command_topic', 'mode_command_template', { format }, `{% set value = ${sets.join(' else ')} else name | lower %}`));
778
+ this.bind(draft, { attribute: 'Thermostat.thermostatRunningState' }, this.status(entity, 'action_topic', 'action_template', {
779
+ map: { heating: 'heat', cooling: 'cool', fan: 'fan', drying: '', idle: '', off: '', preheating: 'heat' },
780
+ }));
781
+ if (Object.keys(climate).length === 0) {
782
+ delete draft.options.climate;
783
+ }
784
+ if (str(c.current_humidity_topic) !== undefined) {
785
+ const humidity = this.draft(`${entity.id}_humidity`, entity);
786
+ this.addType(humidity, 'HumiditySensor');
787
+ this.bind(humidity, { attribute: 'RelativeHumidityMeasurement.measuredValue' }, this.status(entity, 'current_humidity_topic', 'current_humidity_template', {
788
+ unit: 'percent100ths',
789
+ type: 'number',
790
+ }));
791
+ }
792
+ for (const [field, what] of [
793
+ ['fan_mode_command_topic', 'fan modes'],
794
+ ['swing_mode_command_topic', 'swing modes'],
795
+ ['preset_mode_command_topic', 'preset modes'],
796
+ ['target_humidity_command_topic', 'the target humidity'],
797
+ ]) {
798
+ if (str(c[field]) !== undefined) {
799
+ this.skip(entity, `${what} are not mapped`);
800
+ }
801
+ }
802
+ }
803
+ lock(entity) {
804
+ const c = entity.config;
805
+ const draft = this.draft(entity.id, entity, true);
806
+ this.addType(draft, 'DoorLock');
807
+ const lock = text(c.payload_lock, 'LOCK');
808
+ const unlock = text(c.payload_unlock, 'UNLOCK');
809
+ const map = {
810
+ [text(c.state_locked, 'LOCKED')]: 'Locked',
811
+ [text(c.state_unlocked, 'UNLOCKED')]: 'Unlocked',
812
+ [text(c.state_jammed, 'JAMMED')]: 'NotFullyLocked',
813
+ };
814
+ this.bind(draft, { attribute: 'DoorLock.lockState' }, this.status(entity, 'state_topic', 'value_template', { map }), this.command(entity, 'command_topic', 'command_template', { format: { Locked: lock, Unlocked: unlock } }, `{% set value = ${JSON.stringify(lock)} if name == "Locked" else ${JSON.stringify(unlock)} %}`, ['code']));
815
+ }
816
+ fan(entity) {
817
+ const c = entity.config;
818
+ const draft = this.draft(entity.id, entity, true);
819
+ this.addType(draft, 'Fan');
820
+ draft.coalesce = 50;
821
+ const on = text(c.payload_on, 'ON');
822
+ const off = text(c.payload_off, 'OFF');
823
+ this.onOffMapping(entity, draft, 'state_topic', 'state_value_template', on, off);
824
+ if (str(c.percentage_command_topic) !== undefined || str(c.percentage_state_topic) !== undefined) {
825
+ const max = num(c.speed_range_max) ?? 100;
826
+ const scale = { from: [0, max], to: [0, 100] };
827
+ this.bind(draft, { attribute: 'FanControl.percentSetting' }, this.status(entity, 'percentage_state_topic', 'percentage_value_template', { scale, type: 'number' }), this.command(entity, 'percentage_command_topic', 'percentage_command_template', { scale, round: 0 }));
828
+ }
829
+ const presets = list(c.preset_modes);
830
+ if (presets.length > 0) {
831
+ const names = {
832
+ off: 'Off',
833
+ low: 'Low',
834
+ medium: 'Medium',
835
+ high: 'High',
836
+ auto: 'Auto',
837
+ on: 'On',
838
+ smart: 'Smart',
839
+ };
840
+ const map = {};
841
+ const format = {};
842
+ const sets = [];
843
+ for (const preset of presets) {
844
+ const name = names[preset.toLowerCase()];
845
+ if (name !== undefined) {
846
+ map[preset] = name;
847
+ format[name] = preset;
848
+ sets.push(`${JSON.stringify(preset)} if name == ${JSON.stringify(name)}`);
849
+ }
850
+ }
851
+ if (Object.keys(map).length > 0) {
852
+ this.bind(draft, { attribute: 'FanControl.fanMode' }, this.status(entity, 'preset_mode_state_topic', 'preset_mode_value_template', { map }), this.command(entity, 'preset_mode_command_topic', 'preset_mode_command_template', { format }, `{% set value = ${sets.join(' else ')} else name | lower %}`));
853
+ if (Object.values(map).includes('Auto')) {
854
+ this.addFeature(draft, 'FanControl', 'Auto');
855
+ }
856
+ }
857
+ const other = presets.filter((p) => names[p.toLowerCase()] === undefined);
858
+ if (other.length > 0) {
859
+ this.skip(entity, `preset modes ${other.join(', ')} have no fan mode`);
860
+ }
861
+ }
862
+ if (str(c.oscillation_command_topic) !== undefined) {
863
+ this.skip(entity, 'oscillation is not mapped');
864
+ }
865
+ if (str(c.direction_command_topic) !== undefined) {
866
+ this.skip(entity, 'direction is not mapped');
867
+ }
868
+ }
869
+ valve(entity) {
870
+ const c = entity.config;
871
+ const draft = this.draft(entity.id, entity, true);
872
+ this.addType(draft, 'WaterValve');
873
+ const map = {
874
+ [text(c.state_open, 'open')]: 'Open',
875
+ [text(c.state_opening, 'opening')]: 'Transitioning',
876
+ [text(c.state_closed, 'closed')]: 'Closed',
877
+ [text(c.state_closing, 'closing')]: 'Transitioning',
878
+ };
879
+ this.bind(draft, { attribute: 'ValveConfigurationAndControl.currentState' }, this.status(entity, 'state_topic', 'value_template', { map }));
880
+ const command = str(c.command_topic);
881
+ if (command !== undefined) {
882
+ this.bind(draft, { invoke: 'ValveConfigurationAndControl.open' }, undefined, {
883
+ topic: command,
884
+ payload: text(c.payload_open, 'OPEN'),
885
+ });
886
+ this.bind(draft, { invoke: 'ValveConfigurationAndControl.close' }, undefined, {
887
+ topic: command,
888
+ payload: text(c.payload_close, 'CLOSE'),
889
+ });
890
+ }
891
+ }
892
+ binarySensor(entity) {
893
+ const c = entity.config;
894
+ const on = text(c.payload_on, 'ON');
895
+ const off = text(c.payload_off, 'OFF');
896
+ const deviceClass = str(c.device_class);
897
+ const status = (map) => this.status(entity, 'state_topic', 'value_template', { map });
898
+ const sensor = (type, attribute, map) => {
899
+ const draft = this.draft(entity.id, entity);
900
+ this.addType(draft, type);
901
+ this.bind(draft, { attribute }, status(map));
902
+ };
903
+ switch (deviceClass) {
904
+ case 'door':
905
+ case 'window':
906
+ case 'opening':
907
+ case 'garage_door':
908
+ // Home Assistant's "on" is the open contact; Matter's true is the closed one
909
+ sensor('ContactSensor', 'BooleanState.stateValue', { [on]: false, [off]: true });
910
+ return;
911
+ case 'motion':
912
+ case 'occupancy':
913
+ case 'presence':
914
+ case 'moving':
915
+ sensor('OccupancySensor', 'OccupancySensing.occupancy', { [on]: true, [off]: false });
916
+ return;
917
+ case 'moisture':
918
+ sensor('WaterLeakDetector', 'BooleanState.stateValue', { [on]: true, [off]: false });
919
+ return;
920
+ case 'cold':
921
+ sensor('WaterFreezeDetector', 'BooleanState.stateValue', { [on]: true, [off]: false });
922
+ return;
923
+ case 'smoke': {
924
+ const draft = this.draft(entity.id, entity);
925
+ this.addType(draft, 'SmokeCoAlarm');
926
+ this.addFeature(draft, 'SmokeCoAlarm', 'SmokeAlarm');
927
+ this.bind(draft, { attribute: 'SmokeCoAlarm.smokeState' }, status({ [on]: 'Critical', [off]: 'Normal' }));
928
+ return;
929
+ }
930
+ case 'carbon_monoxide': {
931
+ const draft = this.draft(entity.id, entity);
932
+ this.addType(draft, 'SmokeCoAlarm');
933
+ this.addFeature(draft, 'SmokeCoAlarm', 'CoAlarm');
934
+ this.bind(draft, { attribute: 'SmokeCoAlarm.coState' }, status({ [on]: 'Critical', [off]: 'Normal' }));
935
+ return;
936
+ }
937
+ case 'battery':
938
+ this.bind(this.powerDraft(), { attribute: 'PowerSource.batChargeLevel' }, status({ [on]: 'Critical', [off]: 'Ok' }));
939
+ return;
940
+ case 'battery_charging': {
941
+ const power = this.powerDraft();
942
+ this.addFeature(power, 'PowerSource', 'Rechargeable');
943
+ // mandatory with the feature; `Unknown` until the first report
944
+ power.attributes.PowerSource = { ...power.attributes.PowerSource, batChargeState: 0 };
945
+ this.bind(power, { attribute: 'PowerSource.batChargeState' }, status({ [on]: 'IsCharging', [off]: 'IsNotCharging' }));
946
+ return;
947
+ }
948
+ default:
949
+ this.skip(entity, deviceClass === undefined
950
+ ? 'no device_class; a binary sensor without one has no Matter sensor type'
951
+ : `device_class ${deviceClass} has no Matter sensor type`);
952
+ }
953
+ }
954
+ sensor(entity) {
955
+ const c = entity.config;
956
+ const unit = str(c.unit_of_measurement);
957
+ // the unit alone settles a few classes; nothing is guessed from names
958
+ const deviceClass = str(c.device_class) ??
959
+ (unit === '°C' || unit === '°F' ? 'temperature' : unit === 'lx' ? 'illuminance' : undefined);
960
+ const draft = () => this.draft(entity.id, entity);
961
+ const bindStatus = (d, type, attribute, extra) => {
962
+ this.addType(d, type);
963
+ this.bind(d, { attribute }, this.status(entity, 'state_topic', 'value_template', { type: 'number', ...extra }));
964
+ };
965
+ const factor = (f) => ({ scale: { from: [0, 1], to: [0, f], clamp: false } });
966
+ switch (deviceClass) {
967
+ case 'temperature':
968
+ if (unit === '°C' || unit === 'C' || unit === undefined) {
969
+ bindStatus(draft(), 'TemperatureSensor', 'TemperatureMeasurement.measuredValue', { unit: 'celsius' });
970
+ return;
971
+ }
972
+ if (unit === '°F' || unit === 'F') {
973
+ bindStatus(draft(), 'TemperatureSensor', 'TemperatureMeasurement.measuredValue', {
974
+ unit: 'fahrenheit',
975
+ });
976
+ return;
977
+ }
978
+ break;
979
+ case 'humidity':
980
+ if (unit === '%' || unit === undefined) {
981
+ bindStatus(draft(), 'HumiditySensor', 'RelativeHumidityMeasurement.measuredValue', {
982
+ unit: 'percent100ths',
983
+ });
984
+ return;
985
+ }
986
+ break;
987
+ case 'pressure':
988
+ case 'atmospheric_pressure': {
989
+ const factors = {
990
+ hPa: 1,
991
+ mbar: 1,
992
+ kPa: 10,
993
+ Pa: 0.01,
994
+ bar: 1000,
995
+ psi: 68.9476,
996
+ inHg: 33.8639,
997
+ mmHg: 1.33322,
998
+ };
999
+ const f = unit === undefined ? undefined : factors[unit];
1000
+ if (f !== undefined) {
1001
+ bindStatus(draft(), 'PressureSensor', 'PressureMeasurement.measuredValue', {
1002
+ ...(f === 1 ? {} : factor(f)),
1003
+ round: 0,
1004
+ });
1005
+ return;
1006
+ }
1007
+ break;
1008
+ }
1009
+ case 'illuminance':
1010
+ if (unit === 'lx' || unit === undefined) {
1011
+ bindStatus(draft(), 'LightSensor', 'IlluminanceMeasurement.measuredValue', { unit: 'lux' });
1012
+ return;
1013
+ }
1014
+ break;
1015
+ case 'battery':
1016
+ if (unit === '%' || unit === undefined) {
1017
+ this.bind(this.powerDraft(), { attribute: 'PowerSource.batPercentRemaining' }, this.status(entity, 'state_topic', 'value_template', { type: 'number', unit: 'halfPercent' }));
1018
+ return;
1019
+ }
1020
+ break;
1021
+ case 'carbon_dioxide':
1022
+ if (unit === 'ppm') {
1023
+ bindStatus(draft(), 'AirQualitySensor', 'CarbonDioxideConcentrationMeasurement.measuredValue', {});
1024
+ return;
1025
+ }
1026
+ break;
1027
+ case 'carbon_monoxide':
1028
+ if (unit === 'ppm') {
1029
+ bindStatus(draft(), 'AirQualitySensor', 'CarbonMonoxideConcentrationMeasurement.measuredValue', {});
1030
+ return;
1031
+ }
1032
+ break;
1033
+ case 'pm1':
1034
+ case 'pm25':
1035
+ case 'pm10': {
1036
+ if (unit === 'µg/m³' || unit === 'μg/m³') {
1037
+ const cluster = deviceClass === 'pm25'
1038
+ ? 'Pm25ConcentrationMeasurement'
1039
+ : deviceClass === 'pm10'
1040
+ ? 'Pm10ConcentrationMeasurement'
1041
+ : 'Pm1ConcentrationMeasurement';
1042
+ bindStatus(draft(), 'AirQualitySensor', `${cluster}.measuredValue`, {});
1043
+ return;
1044
+ }
1045
+ break;
1046
+ }
1047
+ case 'volatile_organic_compounds_parts':
1048
+ case 'volatile_organic_compounds':
1049
+ case 'nitrogen_dioxide':
1050
+ case 'ozone':
1051
+ case 'formaldehyde': {
1052
+ const clusters = {
1053
+ volatile_organic_compounds_parts: 'TotalVolatileOrganicCompoundsConcentrationMeasurement',
1054
+ volatile_organic_compounds: 'TotalVolatileOrganicCompoundsConcentrationMeasurement',
1055
+ nitrogen_dioxide: 'NitrogenDioxideConcentrationMeasurement',
1056
+ ozone: 'OzoneConcentrationMeasurement',
1057
+ formaldehyde: 'FormaldehydeConcentrationMeasurement',
1058
+ };
1059
+ const cluster = clusters[deviceClass] ?? '';
1060
+ if (unit === 'ppb') {
1061
+ bindStatus(draft(), 'AirQualitySensor', `${cluster}.measuredValue`, {});
1062
+ return;
1063
+ }
1064
+ if (unit === 'ppm') {
1065
+ bindStatus(draft(), 'AirQualitySensor', `${cluster}.measuredValue`, factor(1000));
1066
+ return;
1067
+ }
1068
+ break;
1069
+ }
1070
+ case 'aqi': {
1071
+ // the US AQI bands onto Matter's six levels
1072
+ const d = draft();
1073
+ this.addType(d, 'AirQualitySensor');
1074
+ const base = this.status(entity, 'state_topic', 'value_template');
1075
+ if (base !== undefined) {
1076
+ const inner = base.template === undefined ? 'value' : `(${base.template.replace(/^\{\{|\}\}$/g, '').trim()})`;
1077
+ base.template = `{% set aqi = ${inner} | float(-1) %}{{ 'Unknown' if aqi < 0 else 'Good' if aqi <= 50 else 'Fair' if aqi <= 100 else 'Moderate' if aqi <= 150 else 'Poor' if aqi <= 200 else 'VeryPoor' if aqi <= 300 else 'ExtremelyPoor' }}`;
1078
+ this.bind(d, { attribute: 'AirQuality.airQuality' }, base);
1079
+ }
1080
+ return;
1081
+ }
1082
+ case 'volume_flow_rate':
1083
+ if (unit === 'm³/h') {
1084
+ bindStatus(draft(), 'FlowSensor', 'FlowMeasurement.measuredValue', { ...factor(10), round: 0 });
1085
+ return;
1086
+ }
1087
+ break;
1088
+ case 'voltage':
1089
+ case 'current':
1090
+ case 'power':
1091
+ case 'energy':
1092
+ case 'apparent_power':
1093
+ case 'reactive_power':
1094
+ case 'power_factor':
1095
+ case 'frequency':
1096
+ this.skip(entity, `device_class ${deviceClass}: electrical measurement is not mapped yet`);
1097
+ return;
1098
+ default:
1099
+ break;
1100
+ }
1101
+ if (deviceClass === undefined) {
1102
+ this.skip(entity, `no device_class${unit === undefined ? '' : ` (${unit})`}; no Matter sensor type`);
1103
+ }
1104
+ else {
1105
+ this.skip(entity, `device_class ${deviceClass}${unit === undefined ? '' : ` in ${unit}`} has no Matter sensor type`);
1106
+ }
1107
+ }
1108
+ event(entity) {
1109
+ const c = entity.config;
1110
+ const types = list(c.event_types);
1111
+ const { buttons, ignored } = parseActions(types);
1112
+ for (const value of ignored) {
1113
+ this.unmapped.push(`${entity.component} "${entityName(entity)}": event type ${value} is no press`);
1114
+ }
1115
+ const topic = str(c.state_topic);
1116
+ if (topic === undefined) {
1117
+ return;
1118
+ }
1119
+ for (const button of buttons) {
1120
+ const draft = this.draft(button.name === '' ? entity.id : `${entity.id}_${button.name}`, entity);
1121
+ this.addType(draft, 'GenericSwitch');
1122
+ draft.options.switch = { multiPressMax: Math.max(2, multiPressMax(button)) };
1123
+ const status = this.status(entity, 'state_topic', 'value_template', {
1124
+ extract: 'event_type',
1125
+ map: Object.fromEntries(button.kinds),
1126
+ });
1127
+ if (status?.template !== undefined) {
1128
+ // a value_template renders the event type itself
1129
+ delete status.extract;
1130
+ }
1131
+ this.bind(draft, { event: 'Switch' }, status);
1132
+ }
1133
+ }
1134
+ deviceTrigger(entity) {
1135
+ const c = entity.config;
1136
+ const topic = str(c.topic);
1137
+ const type = str(c.type);
1138
+ const subtype = str(c.subtype);
1139
+ const payload = c.payload;
1140
+ if (topic === undefined || type === undefined || subtype === undefined || payload === undefined) {
1141
+ this.skip(entity, 'a device trigger needs topic, type, subtype and payload');
1142
+ return;
1143
+ }
1144
+ if (str(c.automation_type) !== 'trigger') {
1145
+ this.skip(entity, `automation_type ${str(c.automation_type) ?? '?'} is not a trigger`);
1146
+ return;
1147
+ }
1148
+ let name;
1149
+ let kind;
1150
+ if (type === 'action') {
1151
+ const parsed = parseAction(subtype);
1152
+ if (parsed === undefined) {
1153
+ this.unmapped.push(`${entity.component}: action ${subtype} is no press`);
1154
+ return;
1155
+ }
1156
+ name = parsed.button;
1157
+ kind = parsed.kind;
1158
+ }
1159
+ else {
1160
+ name = subtype;
1161
+ kind = parseAction(type.replace(/^button_/, ''))?.kind;
1162
+ if (kind === undefined) {
1163
+ this.unmapped.push(`${entity.component}: trigger type ${type} is no press`);
1164
+ return;
1165
+ }
1166
+ }
1167
+ const template = this.template(entity, 'value_template', 'status');
1168
+ if (template?.startsWith('\u0000') === true) {
1169
+ return;
1170
+ }
1171
+ const key = `${topic}\u0000${name}`;
1172
+ let trigger = this.triggers.get(key);
1173
+ if (trigger === undefined) {
1174
+ trigger = { topic, template, button: { name, kinds: new Map() } };
1175
+ this.triggers.set(key, trigger);
1176
+ }
1177
+ trigger.button.kinds.set(text(payload, JSON.stringify(payload)), kind);
1178
+ }
1179
+ finishTriggers() {
1180
+ for (const { topic, template, button } of this.triggers.values()) {
1181
+ const draft = this.draft(button.name === '' ? 'button' : `button_${button.name}`, undefined);
1182
+ this.addType(draft, 'GenericSwitch');
1183
+ draft.options.switch = { multiPressMax: Math.max(2, multiPressMax(button)) };
1184
+ const status = { topic, map: Object.fromEntries(button.kinds) };
1185
+ if (template !== undefined) {
1186
+ status.template = template;
1187
+ }
1188
+ this.bind(draft, { event: 'Switch' }, status);
1189
+ }
1190
+ }
1191
+ walk(entities) {
1192
+ const sorted = [...entities].sort((a, b) => componentRank(a.component) - componentRank(b.component) || a.id.localeCompare(b.id));
1193
+ for (const entity of sorted) {
1194
+ const c = entity.config;
1195
+ const category = str(c.entity_category);
1196
+ const battery = (entity.component === 'sensor' || entity.component === 'binary_sensor') &&
1197
+ (str(c.device_class) === 'battery' || str(c.device_class) === 'battery_charging');
1198
+ // settings and metrics are not the device's function — except the battery, which Matter has a place for
1199
+ if (category !== undefined && !battery) {
1200
+ this.skip(entity, `${category} entity (a setting or a metric, not the device's function)`);
1201
+ continue;
1202
+ }
1203
+ if (c.enabled_by_default === false) {
1204
+ this.skip(entity, 'disabled by default');
1205
+ continue;
1206
+ }
1207
+ this.takeAvailability(entity);
1208
+ switch (entity.component) {
1209
+ case 'switch':
1210
+ this.switch(entity);
1211
+ break;
1212
+ case 'light':
1213
+ this.light(entity);
1214
+ break;
1215
+ case 'cover':
1216
+ this.cover(entity);
1217
+ break;
1218
+ case 'climate':
1219
+ this.climate(entity);
1220
+ break;
1221
+ case 'lock':
1222
+ this.lock(entity);
1223
+ break;
1224
+ case 'fan':
1225
+ this.fan(entity);
1226
+ break;
1227
+ case 'valve':
1228
+ this.valve(entity);
1229
+ break;
1230
+ case 'binary_sensor':
1231
+ this.binarySensor(entity);
1232
+ break;
1233
+ case 'sensor':
1234
+ this.sensor(entity);
1235
+ break;
1236
+ case 'event':
1237
+ this.event(entity);
1238
+ break;
1239
+ case 'device_trigger':
1240
+ case 'device_automation':
1241
+ this.deviceTrigger(entity);
1242
+ break;
1243
+ case 'button':
1244
+ this.skip(entity, 'a Matter button emits events, it cannot be pressed; no equivalent');
1245
+ break;
1246
+ case 'number':
1247
+ case 'select':
1248
+ case 'text':
1249
+ this.skip(entity, 'not representable in Matter (unmapped by default)');
1250
+ break;
1251
+ case 'scene':
1252
+ this.scene(entity);
1253
+ break;
1254
+ default:
1255
+ this.skip(entity, `the ${entity.component} component has no Matter equivalent`);
1256
+ }
1257
+ }
1258
+ this.finishTriggers();
1259
+ }
1260
+ get deviceAvailability() {
1261
+ return this.availability;
1262
+ }
1263
+ /** the endpoints in their final form: the device's own first, children after; undefined when nothing maps */
1264
+ endpoints(area) {
1265
+ const real = [...this.drafts.values()].filter((d) => d.types.length > 0 && d.mappings.length > 0);
1266
+ const isButton = (d) => d.types[0] === 'GenericSwitch';
1267
+ let main = real.find((d) => d.primary) ??
1268
+ real.find((d) => !isButton(d) && d.scene !== true) ??
1269
+ real.find((d) => !isButton(d)) ??
1270
+ real[0];
1271
+ if (main === undefined) {
1272
+ if (this.power !== undefined && this.power.mappings.length > 0) {
1273
+ main = this.power;
1274
+ }
1275
+ else {
1276
+ return undefined;
1277
+ }
1278
+ }
1279
+ else if (this.power !== undefined && this.power.mappings.length > 0) {
1280
+ this.addType(main, 'PowerSource');
1281
+ main.mappings.push(...this.power.mappings);
1282
+ for (const [cluster, features] of Object.entries(this.power.features)) {
1283
+ for (const feature of features) {
1284
+ this.addFeature(main, cluster, feature);
1285
+ }
1286
+ }
1287
+ for (const [cluster, attributes] of Object.entries(this.power.attributes)) {
1288
+ main.attributes[cluster] = { ...main.attributes[cluster], ...attributes };
1289
+ }
1290
+ }
1291
+ const ordered = [main, ...real.filter((d) => d !== main)];
1292
+ const typeCount = new Map();
1293
+ for (const draft of ordered) {
1294
+ const type = draft.types[0] ?? '';
1295
+ typeCount.set(type, (typeCount.get(type) ?? 0) + 1);
1296
+ }
1297
+ let tag = 0;
1298
+ return ordered.map((draft, i) => {
1299
+ const endpoint = { deviceTypes: draft.types, mappings: draft.mappings };
1300
+ const tags = [];
1301
+ if (i > 0) {
1302
+ endpoint.id = draft.id;
1303
+ // children sharing their device type with a sibling carry a number tag: Matter's disambiguation rule
1304
+ if ((typeCount.get(draft.types[0] ?? '') ?? 0) > 1) {
1305
+ tag++;
1306
+ tags.push({
1307
+ mfgCode: null,
1308
+ namespaceId: NUMBER_NAMESPACE,
1309
+ tag,
1310
+ label: (draft.label ?? draft.id).slice(0, 64),
1311
+ });
1312
+ }
1313
+ }
1314
+ else if (area !== undefined) {
1315
+ const found = areaTag(area);
1316
+ if (found !== undefined) {
1317
+ tags.push({ mfgCode: null, namespaceId: AREA_NAMESPACE, tag: found.id, label: area.slice(0, 64) });
1318
+ }
1319
+ }
1320
+ if (tags.length > 0) {
1321
+ draft.features.Descriptor = ['TagList'];
1322
+ draft.attributes.Descriptor = { tagList: tags };
1323
+ }
1324
+ if (Object.keys(draft.features).length > 0) {
1325
+ endpoint.features = draft.features;
1326
+ }
1327
+ if (Object.keys(draft.attributes).length > 0) {
1328
+ endpoint.attributes = draft.attributes;
1329
+ }
1330
+ if (Object.keys(draft.options).length > 0) {
1331
+ endpoint.options = draft.options;
1332
+ }
1333
+ if (draft.coalesce > 0) {
1334
+ endpoint.coalesce = draft.coalesce;
1335
+ }
1336
+ return endpoint;
1337
+ });
1338
+ }
1339
+ }
1340
+ /** the baseline for a device description, or — when nothing of it maps onto Matter — only the reasons */
1341
+ export function generateReport(raw) {
1342
+ const builder = new Builder();
1343
+ builder.walk(raw.entities);
1344
+ const area = label(str(raw.device.suggested_area));
1345
+ const endpoints = builder.endpoints(area);
1346
+ if (endpoints === undefined) {
1347
+ return { unmapped: builder.unmapped };
1348
+ }
1349
+ const first = raw.entities[0];
1350
+ const name = label(str(raw.device.name)) ?? (first === undefined ? raw.identity : label(entityName(first))) ?? raw.identity;
1351
+ const vendor = label(str(raw.device.manufacturer));
1352
+ const model = label(str(raw.device.model));
1353
+ const serial = label(str(raw.device.serial_number)) ?? raw.identity.slice(0, MAX_LABEL);
1354
+ const availability = builder.deviceAvailability;
1355
+ const device = {
1356
+ name: name.slice(0, MAX_LABEL),
1357
+ ...(vendor === undefined ? {} : { vendor }),
1358
+ ...(model === undefined ? {} : { model }),
1359
+ serial,
1360
+ source: { kind: 'ha-discovery', key: raw.identity, version: rawHash(raw), raw },
1361
+ ...(availability === undefined ? {} : { availability }),
1362
+ endpoints,
1363
+ };
1364
+ return { device, unmapped: builder.unmapped };
1365
+ }
1366
+ /** the baseline for a device description; undefined when nothing of it maps onto Matter */
1367
+ export function generateDevice(raw) {
1368
+ const report = generateReport(raw);
1369
+ return report.device === undefined ? undefined : { device: report.device, unmapped: report.unmapped };
1370
+ }
1371
+ /** regenerate the baseline from what `source.raw` holds */
1372
+ export function generate(raw) {
1373
+ return generateDevice(raw);
1374
+ }
1375
+ export { deviceIdentity };
1376
+ //# sourceMappingURL=generate.js.map