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
package/dist/app.js ADDED
@@ -0,0 +1,157 @@
1
+ /* The application: the MQTT connection, the Matter node manager and the mapping runtime between them.
2
+ Start order: connect to the broker (so retained status is there when the endpoints come up), build the
3
+ bridges and endpoints, wire the mappings (which subscribes the status topics), go online, log the
4
+ pairing codes. */
5
+ import { createRequire } from 'node:module';
6
+ import { MappingRuntime } from "./engine/runtime.js";
7
+ import { silentLogger } from "./log.js";
8
+ import { NodeManager } from "./matter/node-manager.js";
9
+ import { validateDevice, validateDevices } from "./model/validate.js";
10
+ import { MqttClient } from "./mqtt/client.js";
11
+ const pkg = createRequire(import.meta.url)('../package.json');
12
+ export const VERSION = pkg.version;
13
+ export class App {
14
+ log;
15
+ mqtt;
16
+ nodes;
17
+ runtime;
18
+ config;
19
+ started = false;
20
+ constructor(config, options = {}) {
21
+ this.config = config;
22
+ this.log = options.log ?? silentLogger;
23
+ const mqttOptions = {
24
+ url: config.mqtt.url,
25
+ username: config.mqtt.username,
26
+ password: config.mqtt.password,
27
+ clientId: config.mqtt.clientId,
28
+ ...(options.mqttConnectTimeout === undefined ? {} : { connectTimeout: options.mqttConnectTimeout }),
29
+ };
30
+ this.mqtt = new MqttClient(mqttOptions, this.log.child('mqtt'));
31
+ this.nodes = new NodeManager({ config, softwareVersion: VERSION, log: this.log.child('matter') });
32
+ this.runtime = new MappingRuntime({
33
+ publish: async (topic, payload, { retain, qos }) => {
34
+ await this.mqtt.publish(topic, payload, { retain, qos });
35
+ },
36
+ }, this.log.child('mappings'), { codecs: options.codecs ?? new Map() });
37
+ this.mqtt.on('message', (topic, payload) => {
38
+ this.runtime.handleMessage(topic, payload).catch((error) => {
39
+ this.log.error(`handling ${topic} failed`, error);
40
+ });
41
+ });
42
+ this.mqtt.on('connect', () => {
43
+ if (this.started) {
44
+ // a reconnect: ask the devices that need asking for their state again
45
+ this.runtime.publishGets().catch((error) => {
46
+ this.log.error('publishing the get requests failed', error);
47
+ });
48
+ }
49
+ });
50
+ }
51
+ async start() {
52
+ if (this.started) {
53
+ return;
54
+ }
55
+ this.started = true;
56
+ for (const [key, result] of validateDevices(this.config.devices)) {
57
+ for (const issue of result.issues) {
58
+ this.log[issue.level === 'error' ? 'error' : 'warn'](`${key} ${issue.path}: ${issue.message}`);
59
+ }
60
+ const device = this.config.devices[key];
61
+ if (!result.ok && device?.enabled === true) {
62
+ this.log.error(`${key}: not built, the configuration has errors`);
63
+ device.enabled = false;
64
+ }
65
+ }
66
+ await this.mqtt.connect();
67
+ await this.nodes.prepare();
68
+ await this.nodes.start();
69
+ const handles = this.nodes.handles();
70
+ for (const [key, device] of Object.entries(this.config.devices)) {
71
+ const handle = handles.get(key);
72
+ if (handle === undefined) {
73
+ continue;
74
+ }
75
+ this.runtime.bind(key, device, handle.targets());
76
+ }
77
+ const subscriptions = [];
78
+ this.runtime.onTopic((topic) => {
79
+ subscriptions.push(this.mqtt.subscribe(topic).catch((error) => {
80
+ this.log.error(`subscribing ${topic} failed`, error);
81
+ }));
82
+ });
83
+ // the status topics are subscribed before anything is asked to report
84
+ await Promise.all(subscriptions);
85
+ await this.runtime.publishGets();
86
+ for (const info of this.nodes.info()) {
87
+ const codes = info.pairingCodes;
88
+ if (codes === undefined) {
89
+ continue;
90
+ }
91
+ if (info.commissioned) {
92
+ this.log.info(`bridge ${info.id}: commissioned, port ${info.port}`);
93
+ }
94
+ else {
95
+ this.log.info(`bridge ${info.id}: not commissioned — manual pairing code ${codes.manualPairingCode}, QR ${codes.qrPairingCode}`);
96
+ }
97
+ }
98
+ }
99
+ get running() {
100
+ return this.started;
101
+ }
102
+ /**
103
+ * Add or replace a device while running: its old endpoint and mappings go, the new entry is validated,
104
+ * built in its bridge and wired. A device with errors is kept in the configuration but not built.
105
+ */
106
+ async applyDevice(key, device) {
107
+ this.runtime.unbind(key);
108
+ await this.nodes.removeDevice(key);
109
+ this.config.devices[key] = device;
110
+ if (!this.started) {
111
+ return undefined;
112
+ }
113
+ const result = validateDevice(device);
114
+ for (const issue of result.issues) {
115
+ this.log[issue.level === 'error' ? 'error' : 'warn'](`${key} ${issue.path}: ${issue.message}`);
116
+ }
117
+ if (!device.enabled) {
118
+ return undefined;
119
+ }
120
+ if (!result.ok) {
121
+ this.log.error(`${key}: not built, the configuration has errors`);
122
+ return undefined;
123
+ }
124
+ const handle = await this.nodes.addDevice(key, device);
125
+ if (handle !== undefined) {
126
+ this.runtime.bind(key, device, handle.targets());
127
+ }
128
+ return handle;
129
+ }
130
+ /** remove a device while running */
131
+ async removeDevice(key) {
132
+ this.runtime.unbind(key);
133
+ await this.nodes.removeDevice(key);
134
+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
135
+ delete this.config.devices[key];
136
+ }
137
+ async stop() {
138
+ if (!this.started) {
139
+ return;
140
+ }
141
+ this.started = false;
142
+ try {
143
+ await this.runtime.flush();
144
+ }
145
+ finally {
146
+ // the nodes close their storage whatever happened to the last publishes
147
+ this.runtime.close();
148
+ try {
149
+ await this.nodes.stop();
150
+ }
151
+ finally {
152
+ await this.mqtt.close();
153
+ }
154
+ }
155
+ }
156
+ }
157
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA;;;oBAGoB;AAEpB,OAAO,EAAC,a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AAE,CAAC,CAAC;QACrD,CAAC;QACD,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,oCAAoC;IACpC,KAAK,CAAC,YAAY,CAAC,GAAW;QAC1B,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACzB,MAAM,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;QACnC,gEAAgE;QAChE,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED,KAAK,CAAC,IAAI;QACN,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO;QACX,CAAC;QACD,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC;YACD,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QAC/B,CAAC;gBAAS,CAAC;YACP,wEAAwE;YACxE,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;YACrB,IAAI,CAAC;gBACD,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;YAC5B,CAAC;oBAAS,CAAC;gBACP,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAC5B,CAAC;QACL,CAAC;IACL,CAAC;CACJ"}
@@ -0,0 +1,20 @@
1
+ import { z2m } from '../importers/index.ts';
2
+ import { type Logger } from '../log.ts';
3
+ export interface ImportZ2mArgs {
4
+ configPath?: string | undefined;
5
+ baseTopic: string;
6
+ dryRun: boolean;
7
+ groups: boolean;
8
+ /** seconds to wait for the retained bridge topics */
9
+ timeout: number;
10
+ }
11
+ export declare function parseImportArgs(argv: readonly string[]): ImportZ2mArgs;
12
+ /** one line per device, the way the report reads on a terminal */
13
+ export declare function formatReport(report: readonly z2m.SyncEntry[]): string[];
14
+ export interface ImportIo {
15
+ out(line: string): void;
16
+ log?: Logger;
17
+ env?: Record<string, string | undefined>;
18
+ }
19
+ /** run the import; returns the process exit code */
20
+ export declare function importZ2m(args: ImportZ2mArgs, io: ImportIo): Promise<number>;
@@ -0,0 +1,173 @@
1
+ /* `mqtt2matter --import-z2m [config.json] [--base-topic zigbee2mqtt] [--dry-run] [--no-groups]
2
+ [--timeout 15]`: connect to the broker of the configuration, read the retained `bridge/devices` and
3
+ `bridge/groups`, adopt every supported device that is not in the file yet, re-sync the ones that are
4
+ (the user's edits carried over, conflicts listed), mark the ones zigbee2mqtt no longer describes as
5
+ orphaned, write the file back and report. The normal start afterwards logs the pairing code. */
6
+ import { writeFile } from 'node:fs/promises';
7
+ import { applyEnv, ConfigError, loadConfig, parseConfig } from "../config/index.js";
8
+ import { z2m } from "../importers/index.js";
9
+ import { describeError, silentLogger } from "../log.js";
10
+ import { DevicesSchema, validateDevices } from "../model/index.js";
11
+ import { MqttClient } from "../mqtt/index.js";
12
+ export function parseImportArgs(argv) {
13
+ const args = { baseTopic: z2m.DEFAULT_BASE_TOPIC, dryRun: false, groups: true, timeout: 15 };
14
+ for (let i = 0; i < argv.length; i++) {
15
+ const arg = argv[i] ?? '';
16
+ if (arg === '--base-topic') {
17
+ args.baseTopic = argv[++i] ?? args.baseTopic;
18
+ }
19
+ else if (arg.startsWith('--base-topic=')) {
20
+ args.baseTopic = arg.slice('--base-topic='.length);
21
+ }
22
+ else if (arg === '--dry-run') {
23
+ args.dryRun = true;
24
+ }
25
+ else if (arg === '--no-groups') {
26
+ args.groups = false;
27
+ }
28
+ else if (arg === '--timeout') {
29
+ args.timeout = Number(argv[++i] ?? args.timeout);
30
+ }
31
+ else if (arg.startsWith('--timeout=')) {
32
+ args.timeout = Number(arg.slice('--timeout='.length));
33
+ }
34
+ else if (arg.startsWith('--')) {
35
+ throw new ConfigError(`unknown option ${arg}`);
36
+ }
37
+ else {
38
+ args.configPath = arg;
39
+ }
40
+ }
41
+ if (!Number.isFinite(args.timeout) || args.timeout <= 0) {
42
+ throw new ConfigError('--timeout needs a number of seconds');
43
+ }
44
+ return args;
45
+ }
46
+ function isRecord(value) {
47
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
48
+ }
49
+ const MARK = {
50
+ new: '+',
51
+ updated: '~',
52
+ restored: '~',
53
+ unchanged: '=',
54
+ orphaned: '-',
55
+ invalid: '!',
56
+ unsupported: '?',
57
+ covered: '*',
58
+ };
59
+ /** one line per device, the way the report reads on a terminal */
60
+ export function formatReport(report) {
61
+ const lines = [];
62
+ for (const entry of report) {
63
+ const types = entry.device?.endpoints.map((e) => `${e.id ?? 'main'}: ${e.deviceTypes.join('+')}`).join(', ');
64
+ const detail = entry.status === 'unsupported' || entry.status === 'invalid'
65
+ ? entry.notes.join('; ')
66
+ : entry.status === 'covered'
67
+ ? `the same device as ${entry.covered ?? '?'}: not adopted (the UI can replace it)`
68
+ : (types ?? '');
69
+ lines.push(`${MARK[entry.status]} ${entry.status.padEnd(11)} ${entry.key} ${entry.name} ${detail}`);
70
+ for (const conflict of entry.conflicts) {
71
+ lines.push(` conflict ${conflict.path}: ${conflict.reason} (edit ${JSON.stringify(conflict.user)}, importer ${JSON.stringify(conflict.now)})`);
72
+ }
73
+ if (entry.unmapped.length > 0 && entry.status !== 'unchanged') {
74
+ lines.push(` not mapped: ${entry.unmapped.join(', ')}`);
75
+ }
76
+ if (entry.status === 'invalid') {
77
+ for (const note of entry.notes) {
78
+ lines.push(` ${note}`);
79
+ }
80
+ }
81
+ }
82
+ return lines;
83
+ }
84
+ /** run the import; returns the process exit code */
85
+ export async function importZ2m(args, io) {
86
+ const env = io.env ?? process.env;
87
+ const log = io.log ?? silentLogger;
88
+ const { config, path, raw } = await loadConfig({
89
+ ...(args.configPath === undefined ? {} : { path: args.configPath }),
90
+ env,
91
+ });
92
+ const existing = DevicesSchema.safeParse(raw.devices ?? {});
93
+ if (!existing.success) {
94
+ throw new ConfigError(`${path}: the devices do not validate; fix the file first`);
95
+ }
96
+ const devices = (isRecord(raw.devices) ? raw.devices : {});
97
+ const source = new z2m.Z2mSource(args.baseTopic);
98
+ const mqtt = new MqttClient({
99
+ url: config.mqtt.url,
100
+ username: config.mqtt.username,
101
+ password: config.mqtt.password,
102
+ clientId: config.mqtt.clientId,
103
+ connectTimeout: args.timeout * 1000,
104
+ }, log.child('mqtt'));
105
+ io.out(`connecting to ${config.mqtt.url}, reading ${source.devicesTopic}${args.groups ? ` and ${source.groupsTopic}` : ''}`);
106
+ let error;
107
+ mqtt.on('message', (topic, payload) => {
108
+ try {
109
+ source.handle(topic, payload);
110
+ }
111
+ catch (e) {
112
+ error = e;
113
+ }
114
+ });
115
+ try {
116
+ await mqtt.connect();
117
+ await mqtt.subscribe(source.devicesTopic);
118
+ if (args.groups) {
119
+ await mqtt.subscribe(source.groupsTopic);
120
+ }
121
+ const deadline = Date.now() + args.timeout * 1000;
122
+ while (source.devices === undefined && error === undefined && Date.now() < deadline) {
123
+ await new Promise((resolve) => setTimeout(resolve, 50));
124
+ }
125
+ if (error !== undefined) {
126
+ throw error instanceof Error ? error : new Error(describeError(error));
127
+ }
128
+ if (source.devices === undefined) {
129
+ throw new ConfigError(`no retained ${source.devicesTopic} within ${args.timeout} s — is zigbee2mqtt on this broker, and is its base topic "${args.baseTopic}"?`);
130
+ }
131
+ // the groups come right after the devices; give them a moment
132
+ const groupsDeadline = Date.now() + 2000;
133
+ while (args.groups && source.groups === undefined && Date.now() < groupsDeadline) {
134
+ await new Promise((resolve) => setTimeout(resolve, 50));
135
+ }
136
+ }
137
+ finally {
138
+ await mqtt.close();
139
+ }
140
+ if (!args.groups) {
141
+ source.groups = undefined;
142
+ }
143
+ const discovery = source.discover();
144
+ const { devices: adopted, report } = z2m.adopt(devices, discovery);
145
+ for (const line of formatReport(report)) {
146
+ io.out(line);
147
+ }
148
+ const count = (status) => report.filter((e) => e.status === status).length;
149
+ io.out(`${count('new')} new, ${count('updated') + count('restored')} updated, ${count('unchanged')} unchanged, ${count('orphaned')} orphaned, ${count('invalid')} invalid, ${count('unsupported')} unsupported`);
150
+ const nextRaw = { ...raw, devices: adopted };
151
+ const next = parseConfig(applyEnv(nextRaw, env));
152
+ let errors = 0;
153
+ for (const [key, result] of validateDevices(next.devices)) {
154
+ for (const issue of result.issues) {
155
+ io.out(`${issue.level.toUpperCase()} ${key} ${issue.path}: ${issue.message}`);
156
+ if (issue.level === 'error') {
157
+ errors++;
158
+ }
159
+ }
160
+ }
161
+ if (args.dryRun) {
162
+ io.out(`dry run: ${path} not written`);
163
+ }
164
+ else {
165
+ await writeFile(path, `${JSON.stringify(nextRaw, null, 2)}\n`, 'utf8');
166
+ io.out(`written ${path}: ${Object.keys(adopted).length} devices`);
167
+ }
168
+ if (errors > 0) {
169
+ io.out(`${errors} device(s) have errors and will not be built; edit them or run --check`);
170
+ }
171
+ return 0;
172
+ }
173
+ //# sourceMappingURL=import-z2m.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"import-z2m.js","sourceRoot":"","sources":["../../src/commands/import-z2m.ts"],"names":[],"mappings":"AAAA;;;;kGAIkG;AAElG,OAAO,EAAC,SAAS,EAAC,MAAM,kBAAkB,CAAC;AAE3C,OAAO,EAAC,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,WAAW,EAAC,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAC,GAAG,EAAC,MAAM,uBAAuB,CAAC;AAC1C,OAAO,EAAC,aAAa,EAAe,YAAY,EAAC,MAAM,WAAW,CAAC;AACnE,OAAO,EAAC,aAAa,EAAqB,eAAe,EAAC,MAAM,mBAAmB,CAAC;AACpF,OAAO,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAW5C,MAAM,UAAU,eAAe,CAAC,IAAuB;IACnD,MAAM,IAAI,GAAkB,EAAC,SAAS,EAAE,GAAG,CAAC,kBAAkB,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAC,CAAC;IAC1G,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CA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GAAG,WAAW,CAAC,QAAQ,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IACjD,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;QACxD,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;YAChC,EAAE,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,GAAG,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9E,IAAI,KAAK,CAAC,KAAK,KAAK,OAAO,EAAE,CAAC;gBAC1B,MAAM,EAAE,CAAC;YACb,CAAC;QACL,CAAC;IACL,CAAC;IACD,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,EAAE,CAAC,GAAG,CAAC,YAAY,IAAI,cAAc,CAAC,CAAC;IAC3C,CAAC;SAAM,CAAC;QACJ,MAAM,SAAS,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACvE,EAAE,CAAC,GAAG,CAAC,WAAW,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,CAAC;IACtE,CAAC;IACD,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;QACb,EAAE,CAAC,GAAG,CAAC,GAAG,MAAM,wEAAwE,CAAC,CAAC;IAC9F,CAAC;IACD,OAAO,CAAC,CAAC;AACb,CAAC"}
@@ -0,0 +1,41 @@
1
+ export declare const SERVICE = "mqtt2matter";
2
+ export declare const UNIT_PATH = "/etc/systemd/system/mqtt2matter.service";
3
+ export declare const CONFIG_DIR = "/etc/mqtt2matter";
4
+ export declare const CONFIG_FILE = "/etc/mqtt2matter/mqtt2matter.json";
5
+ export declare const STATE_DIR = "/var/lib/mqtt2matter";
6
+ export declare const UPDATE_DIR = "/var/lib/mqtt2matter/update";
7
+ export declare const UPDATE_PATH_UNIT = "/etc/systemd/system/mqtt2matter-update.path";
8
+ export declare const UPDATE_SERVICE_UNIT = "/etc/systemd/system/mqtt2matter-update.service";
9
+ /** the exit code of a restart from the UI: the unit restarts the service on it (RestartForceExitStatus) and counts
10
+ it as a clean stop (SuccessExitStatus) */
11
+ export declare const RESTART_EXIT_CODE = 75;
12
+ export interface InstallArgs {
13
+ uninstall: boolean;
14
+ dryRun: boolean;
15
+ /** the broker written into a new configuration file */
16
+ mqttUrl?: string | undefined;
17
+ }
18
+ export declare function parseInstallArgs(argv: readonly string[]): InstallArgs;
19
+ /** what the installer needs from the host; the CLI passes the real ones, the tests fakes */
20
+ export interface InstallHost {
21
+ /** prepended to every path written or read: '' on a real host, a temporary directory in the tests */
22
+ root: string;
23
+ /** the node binary and the package's main.js, as the unit starts them */
24
+ execStart: string;
25
+ /** run a command; throws when it fails */
26
+ exec(command: string, args: readonly string[]): void;
27
+ /** whether a command succeeds */
28
+ succeeds(command: string, args: readonly string[]): boolean;
29
+ /** why this host cannot install a service (not Linux, not root, no systemd), or undefined */
30
+ unsuitable(): string | undefined;
31
+ out(line: string): void;
32
+ }
33
+ export declare function unitFile(execStart: string): string;
34
+ export declare function updatePathUnit(): string;
35
+ /** the root oneshot: installs the requested version with npm and restarts the service */
36
+ export declare function updateServiceUnit(execStart: string): string;
37
+ /** a new configuration file: the broker and the storage; everything else is the schema's default */
38
+ export declare function initialConfig(mqttUrl: string | undefined): string;
39
+ export declare function runInstall(args: InstallArgs, host: InstallHost): Promise<void>;
40
+ /** this host, as `sudo mqtt2matter --install` finds it */
41
+ export declare function systemHost(out: (line: string) => void): InstallHost;
@@ -0,0 +1,250 @@
1
+ /* `mqtt2matter --install [--mqtt-url <url>] [--dry-run]` and `mqtt2matter --uninstall`: run mqtt2matter as the
2
+ systemd service `mqtt2matter.service`.
3
+
4
+ /etc/systemd/system/mqtt2matter.service the unit, rewritten on every --install (ExecStart follows node)
5
+ /etc/systemd/system/mqtt2matter-update.path, mqtt2matter-update.service
6
+ the update from the UI: the path unit sees the request the service
7
+ writes into /var/lib/mqtt2matter/update and starts the root oneshot
8
+ `mqtt2matter --apply-update` (commands/update.ts)
9
+ /etc/mqtt2matter/mqtt2matter.json the configuration; created once, never overwritten — the UI edits it,
10
+ so the directory belongs to the service user
11
+ /var/lib/mqtt2matter/ matter.js storage (fabrics, endpoint numbers) and the shard map
12
+ system user mqtt2matter the unit runs as it
13
+
14
+ One process serves every bridge, so there is one unit, not one per instance. Uninstalling keeps the
15
+ configuration and the storage: the fabrics in it are what the controllers paired with. */
16
+ import { execFileSync } from 'node:child_process';
17
+ import { existsSync, realpathSync } from 'node:fs';
18
+ import { chmod, mkdir, rm, stat, writeFile } from 'node:fs/promises';
19
+ import { join } from 'node:path';
20
+ import { ConfigError } from "../config/index.js";
21
+ export const SERVICE = 'mqtt2matter';
22
+ export const UNIT_PATH = `/etc/systemd/system/${SERVICE}.service`;
23
+ export const CONFIG_DIR = `/etc/${SERVICE}`;
24
+ export const CONFIG_FILE = `${CONFIG_DIR}/${SERVICE}.json`;
25
+ export const STATE_DIR = `/var/lib/${SERVICE}`;
26
+ export const UPDATE_DIR = `${STATE_DIR}/update`;
27
+ export const UPDATE_PATH_UNIT = `/etc/systemd/system/${SERVICE}-update.path`;
28
+ export const UPDATE_SERVICE_UNIT = `/etc/systemd/system/${SERVICE}-update.service`;
29
+ /** the exit code of a restart from the UI: the unit restarts the service on it (RestartForceExitStatus) and counts
30
+ it as a clean stop (SuccessExitStatus) */
31
+ export const RESTART_EXIT_CODE = 75;
32
+ export function parseInstallArgs(argv) {
33
+ const args = { uninstall: false, dryRun: false };
34
+ for (let i = 0; i < argv.length; i++) {
35
+ const arg = argv[i] ?? '';
36
+ if (arg === '--install') {
37
+ continue;
38
+ }
39
+ else if (arg === '--uninstall') {
40
+ args.uninstall = true;
41
+ }
42
+ else if (arg === '--dry-run') {
43
+ args.dryRun = true;
44
+ }
45
+ else if (arg === '--mqtt-url') {
46
+ args.mqttUrl = argv[++i];
47
+ if (args.mqttUrl === undefined || args.mqttUrl === '') {
48
+ throw new ConfigError('--mqtt-url needs a URL');
49
+ }
50
+ }
51
+ else if (arg.startsWith('--mqtt-url=')) {
52
+ args.mqttUrl = arg.slice('--mqtt-url='.length);
53
+ }
54
+ else {
55
+ throw new ConfigError(`unknown option ${arg}`);
56
+ }
57
+ }
58
+ return args;
59
+ }
60
+ export function unitFile(execStart) {
61
+ return `[Unit]
62
+ Description=mqtt2matter: MQTT to Matter bridge
63
+ Documentation=https://github.com/hobbyquaker/mqtt2matter#readme
64
+ After=network-online.target
65
+ Wants=network-online.target
66
+
67
+ [Service]
68
+ Type=simple
69
+ User=${SERVICE}
70
+ Group=${SERVICE}
71
+ Environment=MQTT2MATTER_CONFIG=${CONFIG_FILE}
72
+ # the UI's restart and update: an exit with ${RESTART_EXIT_CODE} comes back; the update goes through ${SERVICE}-update.path
73
+ Environment=MQTT2MATTER_SUPERVISOR=systemd
74
+ Environment=MQTT2MATTER_UPDATE_DIR=${UPDATE_DIR}
75
+ WorkingDirectory=${STATE_DIR}
76
+ ExecStart=${execStart}
77
+ Restart=on-failure
78
+ RestartForceExitStatus=${RESTART_EXIT_CODE}
79
+ # …and is a clean stop, not a failure, in the journal (the forced restart happens all the same)
80
+ SuccessExitStatus=${RESTART_EXIT_CODE}
81
+ RestartSec=5
82
+ TimeoutStopSec=30
83
+ SyslogIdentifier=${SERVICE}
84
+ StateDirectory=${SERVICE}
85
+ StateDirectoryMode=0750
86
+ # the UI writes the configuration back
87
+ ReadWritePaths=${CONFIG_DIR}
88
+ NoNewPrivileges=true
89
+ ProtectSystem=full
90
+ ProtectHome=true
91
+ PrivateTmp=true
92
+
93
+ [Install]
94
+ WantedBy=multi-user.target
95
+ `;
96
+ }
97
+ export function updatePathUnit() {
98
+ return `[Unit]
99
+ Description=mqtt2matter: an update requested from the UI
100
+
101
+ [Path]
102
+ PathExists=${UPDATE_DIR}/request
103
+ Unit=${SERVICE}-update.service
104
+
105
+ [Install]
106
+ WantedBy=multi-user.target
107
+ `;
108
+ }
109
+ /** the root oneshot: installs the requested version with npm and restarts the service */
110
+ export function updateServiceUnit(execStart) {
111
+ return `[Unit]
112
+ Description=mqtt2matter: install the version requested from the UI, then restart mqtt2matter
113
+
114
+ [Service]
115
+ Type=oneshot
116
+ # npm keeps its cache under HOME, which systemd does not set for a system service
117
+ Environment=HOME=/root
118
+ ExecStart=${execStart} --apply-update
119
+ TimeoutStartSec=900
120
+ SyslogIdentifier=${SERVICE}-update
121
+ `;
122
+ }
123
+ /** a new configuration file: the broker and the storage; everything else is the schema's default */
124
+ export function initialConfig(mqttUrl) {
125
+ return `${JSON.stringify({ mqtt: { url: mqttUrl ?? 'mqtt://localhost:1883' }, storage: STATE_DIR, devices: {} }, null, 2)}\n`;
126
+ }
127
+ async function exists(path) {
128
+ try {
129
+ await stat(path);
130
+ return true;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ async function install(args, host) {
137
+ const at = (path) => join(host.root, path);
138
+ const unit = unitFile(host.execStart);
139
+ const configExists = await exists(at(CONFIG_FILE));
140
+ if (args.dryRun) {
141
+ host.out(`would write ${UNIT_PATH}:\n\n${unit}`);
142
+ host.out(configExists ? `would keep ${CONFIG_FILE}` : `would create ${CONFIG_FILE}:\n${initialConfig(args.mqttUrl)}`);
143
+ host.out(`would write ${UPDATE_PATH_UNIT}:\n\n${updatePathUnit()}`);
144
+ host.out(`would write ${UPDATE_SERVICE_UNIT}:\n\n${updateServiceUnit(host.execStart)}`);
145
+ host.out(`would create the system user ${SERVICE}, ${STATE_DIR}, ${UPDATE_DIR}, enable ${SERVICE}-update.path, and enable and start ${SERVICE}.service`);
146
+ return;
147
+ }
148
+ const reason = host.unsuitable();
149
+ if (reason !== undefined) {
150
+ throw new ConfigError(`--install: ${reason}`);
151
+ }
152
+ if (!host.succeeds('id', ['-u', SERVICE])) {
153
+ host.out(`creating the system user ${SERVICE}`);
154
+ host.exec('useradd', [
155
+ '--system',
156
+ '--no-create-home',
157
+ '--home-dir',
158
+ STATE_DIR,
159
+ '--shell',
160
+ '/usr/sbin/nologin',
161
+ SERVICE,
162
+ ]);
163
+ }
164
+ await mkdir(at(STATE_DIR), { recursive: true, mode: 0o750 });
165
+ await mkdir(at(UPDATE_DIR), { recursive: true, mode: 0o750 });
166
+ await mkdir(at(CONFIG_DIR), { recursive: true, mode: 0o750 });
167
+ if (configExists) {
168
+ host.out(`kept ${CONFIG_FILE}`);
169
+ if (args.mqttUrl !== undefined) {
170
+ host.out(`--mqtt-url ignored: ${CONFIG_FILE} exists; change the broker in the UI or in the file`);
171
+ }
172
+ }
173
+ else {
174
+ await writeFile(at(CONFIG_FILE), initialConfig(args.mqttUrl), { mode: 0o640 });
175
+ host.out(`wrote ${CONFIG_FILE}`);
176
+ }
177
+ // the configuration holds the broker's credentials: the service user's alone
178
+ host.exec('chown', ['-R', `${SERVICE}:${SERVICE}`, at(CONFIG_DIR), at(STATE_DIR)]);
179
+ await chmod(at(CONFIG_FILE), 0o640);
180
+ await mkdir(join(host.root, '/etc/systemd/system'), { recursive: true });
181
+ await writeFile(at(UNIT_PATH), unit, { mode: 0o644 });
182
+ host.out(`wrote ${UNIT_PATH} (ExecStart=${host.execStart})`);
183
+ await writeFile(at(UPDATE_PATH_UNIT), updatePathUnit(), { mode: 0o644 });
184
+ await writeFile(at(UPDATE_SERVICE_UNIT), updateServiceUnit(host.execStart), { mode: 0o644 });
185
+ host.out(`wrote ${UPDATE_PATH_UNIT} and ${UPDATE_SERVICE_UNIT} (the update from the UI)`);
186
+ host.exec('systemctl', ['daemon-reload']);
187
+ host.exec('systemctl', ['enable', '--now', `${SERVICE}-update.path`]);
188
+ host.exec('systemctl', ['enable', `${SERVICE}.service`]);
189
+ // restart rather than start: a reinstall has to bring a running service onto the new unit
190
+ host.exec('systemctl', ['restart', `${SERVICE}.service`]);
191
+ host.out(`${SERVICE}.service enabled and started`);
192
+ host.out(`the pairing code and QR: journalctl -u ${SERVICE} -f; the UI: http://<this host>:8282`);
193
+ }
194
+ async function uninstall(args, host) {
195
+ if (args.dryRun) {
196
+ host.out(`would stop and disable ${SERVICE}.service and ${SERVICE}-update.path and remove their units; ${CONFIG_DIR} and ${STATE_DIR} stay`);
197
+ return;
198
+ }
199
+ const reason = host.unsuitable();
200
+ if (reason !== undefined) {
201
+ throw new ConfigError(`--uninstall: ${reason}`);
202
+ }
203
+ if (!host.succeeds('systemctl', ['disable', '--now', `${SERVICE}.service`])) {
204
+ host.out(`${SERVICE}.service was not enabled`);
205
+ }
206
+ host.succeeds('systemctl', ['disable', '--now', `${SERVICE}-update.path`]);
207
+ for (const path of [UNIT_PATH, UPDATE_PATH_UNIT, UPDATE_SERVICE_UNIT]) {
208
+ await rm(join(host.root, path), { force: true });
209
+ }
210
+ host.exec('systemctl', ['daemon-reload']);
211
+ host.out(`removed ${UNIT_PATH}, ${UPDATE_PATH_UNIT}, ${UPDATE_SERVICE_UNIT}`);
212
+ // the storage holds the fabrics: removing it unpairs the bridge from every controller
213
+ host.out(`kept ${CONFIG_DIR} and ${STATE_DIR} (the pairings); delete them by hand when they are no longer needed`);
214
+ }
215
+ export async function runInstall(args, host) {
216
+ await (args.uninstall ? uninstall(args, host) : install(args, host));
217
+ }
218
+ /** this host, as `sudo mqtt2matter --install` finds it */
219
+ export function systemHost(out) {
220
+ return {
221
+ root: '',
222
+ execStart: `${process.execPath} ${realpathSync(process.argv[1] ?? '')}`,
223
+ exec: (command, args) => {
224
+ execFileSync(command, args, { stdio: ['ignore', 'inherit', 'inherit'] });
225
+ },
226
+ succeeds: (command, args) => {
227
+ try {
228
+ execFileSync(command, args, { stdio: 'ignore' });
229
+ return true;
230
+ }
231
+ catch {
232
+ return false;
233
+ }
234
+ },
235
+ unsuitable: () => {
236
+ if (process.platform !== 'linux') {
237
+ return 'needs Linux with systemd';
238
+ }
239
+ if (process.getuid?.() !== 0) {
240
+ return 'needs root: sudo mqtt2matter --install';
241
+ }
242
+ if (!existsSync('/run/systemd/system')) {
243
+ return 'systemd is not running on this host';
244
+ }
245
+ return undefined;
246
+ },
247
+ out,
248
+ };
249
+ }
250
+ //# sourceMappingURL=install.js.map