@project-chip/matter-node.js-examples 0.7.5-alpha.0-20240222-8696097f → 0.8.0-alpha.0-20240309-64eaef67

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/README.md +44 -0
  2. package/dist/esm/examples/BridgedDeviceNode.js +147 -0
  3. package/dist/esm/examples/BridgedDeviceNode.js.map +7 -0
  4. package/dist/esm/examples/{BridgedDevicesNode.js → BridgedDevicesNodeLegacy.js} +2 -2
  5. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +7 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js +116 -127
  7. package/dist/esm/examples/ComposedDeviceNode.js.map +3 -3
  8. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +138 -0
  9. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +7 -0
  10. package/dist/esm/examples/ControllerNode.js +24 -20
  11. package/dist/esm/examples/ControllerNode.js.map +2 -2
  12. package/dist/esm/examples/ControllerNodeLegacy.js +227 -0
  13. package/dist/esm/examples/ControllerNodeLegacy.js.map +7 -0
  14. package/dist/esm/examples/DeviceNode.js +118 -159
  15. package/dist/esm/examples/DeviceNode.js.map +2 -2
  16. package/dist/esm/examples/DeviceNodeFull.js +253 -0
  17. package/dist/esm/examples/DeviceNodeFull.js.map +7 -0
  18. package/dist/esm/examples/DeviceNodeFullLegacy.js +171 -0
  19. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +7 -0
  20. package/dist/esm/examples/IlluminatedRollerShade.js +85 -0
  21. package/dist/esm/examples/IlluminatedRollerShade.js.map +7 -0
  22. package/dist/esm/examples/LightDevice.js +34 -0
  23. package/dist/esm/examples/LightDevice.js.map +7 -0
  24. package/dist/esm/examples/MultiDeviceNode.js +133 -134
  25. package/dist/esm/examples/MultiDeviceNode.js.map +3 -3
  26. package/dist/esm/examples/MultiDeviceNodeLegacy.js +146 -0
  27. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +7 -0
  28. package/dist/esm/examples/SensorDeviceNode.js +167 -0
  29. package/dist/esm/examples/SensorDeviceNode.js.map +7 -0
  30. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +115 -0
  31. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +7 -0
  32. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +115 -0
  33. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +7 -0
  34. package/dist/esm/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.js → DummyWifiNetworkCommissioningServerLegacy.js} +16 -14
  35. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +7 -0
  36. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +110 -0
  37. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +7 -0
  38. package/dist/esm/tutorial/example01.js +5 -0
  39. package/dist/esm/tutorial/example01.js.map +7 -0
  40. package/dist/esm/tutorial/example02.js +7 -0
  41. package/dist/esm/tutorial/example02.js.map +7 -0
  42. package/dist/esm/tutorial/example03.js +15 -0
  43. package/dist/esm/tutorial/example03.js.map +7 -0
  44. package/dist/esm/tutorial/example04.js +10 -0
  45. package/dist/esm/tutorial/example04.js.map +7 -0
  46. package/dist/esm/tutorial/example05.js +14 -0
  47. package/dist/esm/tutorial/example05.js.map +7 -0
  48. package/package.json +9 -6
  49. package/src/examples/BridgedDeviceNode.ts +260 -0
  50. package/src/examples/{BridgedDevicesNode.ts → BridgedDevicesNodeLegacy.ts} +6 -1
  51. package/src/examples/ComposedDeviceNode.ts +173 -223
  52. package/src/examples/ComposedDeviceNodeLegacy.ts +252 -0
  53. package/src/examples/ControllerNode.ts +28 -22
  54. package/src/examples/ControllerNodeLegacy.ts +354 -0
  55. package/src/examples/DeviceNode.ts +173 -273
  56. package/src/examples/DeviceNodeFull.ts +440 -0
  57. package/src/examples/DeviceNodeFullLegacy.ts +307 -0
  58. package/src/examples/IlluminatedRollerShade.ts +130 -0
  59. package/src/examples/LightDevice.ts +60 -0
  60. package/src/examples/MultiDeviceNode.ts +184 -236
  61. package/src/examples/MultiDeviceNodeLegacy.ts +267 -0
  62. package/src/examples/SensorDeviceNode.ts +236 -0
  63. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +156 -0
  64. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +153 -0
  65. package/src/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.ts → DummyWifiNetworkCommissioningServerLegacy.ts} +16 -13
  66. package/src/examples/cluster/MyFancyOwnFunctionality.ts +185 -0
  67. package/src/tsconfig.json +9 -1
  68. package/src/tutorial/example01.ts +6 -0
  69. package/src/tutorial/example02.ts +9 -0
  70. package/src/tutorial/example03.ts +19 -0
  71. package/src/tutorial/example04.ts +13 -0
  72. package/src/tutorial/example05.ts +19 -0
  73. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  74. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningClusterServer.js.map +0 -7
@@ -0,0 +1,440 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * This example is not optimized for simplicity, but to show all the advanced use cases for matter.js.
9
+ * If you want to see a simple minimalistic and more standard example please look at DeviceNode.ts or the other examples.
10
+ *
11
+ * This example shows how to create a simple on-off Matter device as a light or as a socket.
12
+ * It can be used as CLI script and starting point for your own device node implementation.
13
+ * Additional to this it shows the following:
14
+ * * How to modify the existing clusters on Root and also Device Endpoints
15
+ * * How to add own Cluster implementations for Standard clusters
16
+ * * How to add a custom Cluster to an Endpoint
17
+ * * Which events are available to get status information from the Node aon commissioning and session/subscription changes
18
+ * * How to get cluster state values
19
+ * * How to set one or multiple state values in a transaction.
20
+ */
21
+
22
+ /**
23
+ * Import needed modules from @project-chip/matter-node.js
24
+ */
25
+ // Include this first to auto-register Crypto, Network and Time Node.js implementations
26
+ import "@project-chip/matter-node.js";
27
+
28
+ import { BleNode } from "@project-chip/matter-node-ble.js/ble";
29
+ import { createFileLogger } from "@project-chip/matter-node.js/log";
30
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
31
+ import { TestEventTriggerRequest } from "@project-chip/matter.js/behavior/definitions/general-diagnostics";
32
+ import { NetworkCommissioningServer } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
33
+ import { OnOffServer } from "@project-chip/matter.js/behavior/definitions/on-off";
34
+ import { Ble } from "@project-chip/matter.js/ble";
35
+ import { NetworkCommissioning } from "@project-chip/matter.js/cluster";
36
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
37
+ import { logEndpoint } from "@project-chip/matter.js/device";
38
+ import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
39
+ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
40
+ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
41
+ import { RootRequirements } from "@project-chip/matter.js/endpoint/definitions";
42
+ import { Environment, StorageService } from "@project-chip/matter.js/environment";
43
+ import { FabricAction } from "@project-chip/matter.js/fabric";
44
+ import { Level, Logger, levelFromString } from "@project-chip/matter.js/log";
45
+ import { ServerNode } from "@project-chip/matter.js/node";
46
+ import { QrCode } from "@project-chip/matter.js/schema";
47
+ import { Time } from "@project-chip/matter.js/time";
48
+ import { ByteArray, singleton } from "@project-chip/matter.js/util";
49
+ import { execSync } from "child_process";
50
+ import { DummyThreadNetworkCommissioningServer } from "./cluster/DummyThreadNetworkCommissioningServer.js";
51
+ import { DummyWifiNetworkCommissioningServer } from "./cluster/DummyWifiNetworkCommissioningServer.js";
52
+ import {
53
+ MyFancyCommandRequest,
54
+ MyFancyCommandResponse,
55
+ MyFancyOwnFunctionalityBehavior,
56
+ } from "./cluster/MyFancyOwnFunctionality.js";
57
+
58
+ /**
59
+ * The following code brings some convenience to the CLI script. It allows to set the log level and format via
60
+ * command line parameters. It also initializes the BLE stack if the `--ble` parameter is present.
61
+ * Some of these parameters can also be replaced by generically accepted parameters or even environment variables. See the comments in the relevant places for information.
62
+ * When using this code as basis for your own device node implementation, you can remove this part or hard code it.
63
+ */
64
+
65
+ requireMinNodeVersion(16);
66
+
67
+ // To configure Logging use
68
+ // * "--log-level" or environment variable "MATTER_LOG_LEVEL" or "environment.vars.set('log.level', Level.DEBUG)"
69
+ // Allowed values are: Level.FATAL, Level.ERROR, Level.WARN, Level.NOTICE, Level.INFO, Level.DEBUG
70
+ // * "--log-format" or environment variable "MATTER_LOG_FORMAT" or "environment.vars.set('log.format', Format.PLAIN)"
71
+ // Allowed values are: Format.PLAIN, Format.HTML, Format.ANSI,
72
+
73
+ const environment = Environment.default;
74
+
75
+ // Alternatively "--ble-enable" or environment variable "BLE_ENABLED"
76
+ // Alternatively "--ble-hciId" or environment variable "BLE_HCIID"
77
+ if (environment.vars.get("ble.enable")) {
78
+ // Initialize Ble
79
+ Ble.get = singleton(
80
+ () =>
81
+ new BleNode({
82
+ hciId: environment.vars.number("ble.hciId"),
83
+ }),
84
+ );
85
+ }
86
+
87
+ function executeCommand(scriptParamName: string) {
88
+ const script = environment.vars.string(scriptParamName);
89
+ if (script === undefined) return undefined;
90
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
91
+ }
92
+
93
+ /**
94
+ * Collect all needed data
95
+ *
96
+ * This block collects all needed data from cli or storage. Replace this with where ever your data come from.
97
+ *
98
+ * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
99
+ * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
100
+ * (so maybe better not do it ;-)).
101
+ */
102
+
103
+ const logFile = environment.vars.string("logfile.filename");
104
+ if (logFile !== undefined) {
105
+ Logger.addLogger("filelogger", await createFileLogger(logFile), {
106
+ defaultLogLevel: levelFromString(environment.vars.string("logfile.loglevel")) ?? Level.DEBUG,
107
+ });
108
+ }
109
+
110
+ const storageService = environment.get(StorageService);
111
+ console.log(`Storage location: ${storageService.location} (Directory)`);
112
+ console.log(
113
+ 'Use the parameter "--storage-path=NAME-OR-PATH" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',
114
+ );
115
+
116
+ const deviceStorage = (await storageService.open("device")).createContext("data");
117
+
118
+ if (deviceStorage.has("isSocket")) {
119
+ console.log("Device type found in storage. --type parameter is ignored.");
120
+ }
121
+ const isSocket = deviceStorage.get("isSocket", environment.vars.string("type") === "socket");
122
+ const deviceName = "Matter test device";
123
+ const vendorName = "matter-node.js";
124
+ const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
125
+ const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
126
+ // product name / id and vendor id should match what is in the device certificate
127
+ const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 0xfff1);
128
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
129
+ const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 0x8000);
130
+
131
+ const port = environment.vars.number("port") ?? 5540;
132
+
133
+ const uniqueId = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
134
+
135
+ deviceStorage.set("passcode", passcode);
136
+ deviceStorage.set("discriminator", discriminator);
137
+ deviceStorage.set("vendorid", vendorId);
138
+ deviceStorage.set("productid", productId);
139
+ deviceStorage.set("isSocket", isSocket);
140
+ deviceStorage.set("uniqueid", uniqueId);
141
+
142
+ // Matter exposes functionality in groups called "clusters". For this example device we override the matter.js "On/Off"
143
+ // cluster implementation to print status to the console.
144
+ class OnOffShellExecServer extends OnOffServer {
145
+ // Intercept the "on" command to the Matter On/Off cluster to print a log message.
146
+ override on() {
147
+ executeCommand("on");
148
+ super.on();
149
+ }
150
+
151
+ // This is the functional inverse of on() above.
152
+ //
153
+ // For demonstration purposes we update state ourselves rather than deferring to matter.js's default "off" handler
154
+ // via super.off().
155
+ override off() {
156
+ executeCommand("off");
157
+ this.state.onOff = false;
158
+ }
159
+
160
+ // Use event handlers to log on/off state reactively, after it changes.
161
+ override initialize() {
162
+ this.events.onOff$Change.on(value => {
163
+ console.log(`Light is now ${value ? "ON" : "OFF"}`);
164
+ });
165
+ }
166
+ }
167
+
168
+ class TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {
169
+ override initialize() {
170
+ this.state.testEventTriggersEnabled = true; // set to true if you support test triggers ...
171
+ super.initialize();
172
+ }
173
+
174
+ override testEventTrigger({ enableKey, eventTrigger }: TestEventTriggerRequest) {
175
+ console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);
176
+ }
177
+ }
178
+
179
+ class MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {
180
+ /** We return the incoming value and store the length of the string in our attribute and send it out as event */
181
+ override myFancyCommand(request: MyFancyCommandRequest): MyFancyCommandResponse {
182
+ const { value } = request;
183
+ this.state.myFancyValue = value.length;
184
+
185
+ this.events.myFancyEvent.emit({ eventValue: value }, this.context);
186
+
187
+ return { response: value };
188
+ }
189
+
190
+ override initialize() {
191
+ this.state.myFancyValue = -1; // Always initialize with -1
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Create Device instance and add needed Listener
197
+ *
198
+ * Create an instance of the matter device class you want to use.
199
+ * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.
200
+ * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the
201
+ * device specific API.
202
+ *
203
+ * The below logic also adds command handlers for commands of clusters that normally are handled device internally
204
+ * like identify that can be implemented with the logic when these commands are called.
205
+ */
206
+
207
+ // Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.
208
+ //
209
+ // In this case we are using with() to install our On/Off cluster behavior.
210
+ // .with("LevelControlForLighting") not needed because we always have it in by default because we have default implementation
211
+ const OnOffDevice = isSocket
212
+ ? vendorId === 0xfff4
213
+ ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)
214
+ : OnOffPlugInUnitDevice.with(OnOffShellExecServer)
215
+ : vendorId === 0xfff4
216
+ ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)
217
+ : OnOffLightDevice.with(OnOffShellExecServer);
218
+
219
+ /**
220
+ * Modify automatically added clusters of the Root endpoint if needed
221
+ * In this example we change the networkCommissioning cluster into one for "Wifi only" devices when BLE is used
222
+ * for commissioning, to demonstrate how to do this.
223
+ * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,
224
+ * then all this is not needed.
225
+ * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.
226
+ */
227
+
228
+ // We use the Basic Root Endpoint without a NetworkCommissioning cluster
229
+ let RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);
230
+
231
+ let wifiOrThreadAdded = false;
232
+ if (Ble.enabled) {
233
+ // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.
234
+ // To offer e.g. a "Wi-Fi only device" (or any other combination) we need to override the Network Commissioning
235
+ // cluster and implement all the need handling here. This is a "static implementation" for pure demonstration
236
+ // purposes and just "simulates" the actions to be done. In a real world implementation this would be done by
237
+ // the device implementor based on the relevant networking stack.
238
+ // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8
239
+ if (environment.vars.has("ble.wifi.fake")) {
240
+ RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);
241
+ wifiOrThreadAdded = true;
242
+ } else if (environment.vars.has("ble.thread.fake")) {
243
+ RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);
244
+ wifiOrThreadAdded = true;
245
+ }
246
+ } else {
247
+ RootEndpoint = RootEndpoint.with(
248
+ NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface),
249
+ );
250
+ }
251
+
252
+ const networkId = new ByteArray(32);
253
+ // Physical devices appear as "nodes" on a Matter network. As a device implementer you use a NodeServer to bring a
254
+ // device online.
255
+ //
256
+ // Note there are a large number of options to NodeServer that we are allowing to take default values here. See
257
+ // CompositeWindowCovering.ts for a more detailed example.
258
+ const server = await ServerNode.create(RootEndpoint, {
259
+ id: uniqueId,
260
+ network: {
261
+ port,
262
+ discoveryCapabilities: {
263
+ onIpNetwork: !environment.vars.has("ble.enable"),
264
+ ble: environment.vars.has("ble.enable"),
265
+ },
266
+ ble: environment.vars.has("ble.enable"), // TODO remove when state init is fixed
267
+ },
268
+ commissioning: {
269
+ passcode,
270
+ discriminator,
271
+ },
272
+ productDescription: {
273
+ name: deviceName,
274
+ deviceType: DeviceTypeId(OnOffDevice.deviceType),
275
+ },
276
+ basicInformation: {
277
+ vendorName,
278
+ vendorId: VendorId(vendorId),
279
+ nodeLabel: productName,
280
+ productName,
281
+ productLabel: productName,
282
+ productId,
283
+ serialNumber: `node-matter-${uniqueId}`,
284
+ uniqueId,
285
+ },
286
+
287
+ // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally
288
+ networkCommissioning: {
289
+ maxNetworks: 1,
290
+ interfaceEnabled: true,
291
+ lastConnectErrorValue: 0,
292
+ lastNetworkId: wifiOrThreadAdded ? null : networkId,
293
+ lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,
294
+ networks: [{ networkId: networkId, connected: !wifiOrThreadAdded }],
295
+ scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,
296
+ connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,
297
+ },
298
+ myFancyFunctionality: {
299
+ myFancyValue: 0,
300
+ },
301
+ });
302
+
303
+ // Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.
304
+ const endpoint = new Endpoint(OnOffDevice, { id: "onoff" });
305
+ await server.add(endpoint);
306
+
307
+ /**
308
+ * This event is triggered when the device is initially commissioned successfully.
309
+ * This means: It is added to the first fabric.
310
+ */
311
+ server.lifecycle.commissioned.on(() => console.log("Server was initially commissioned successfully!"));
312
+
313
+ /** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
314
+ server.lifecycle.decommissioned.on(() => console.log("Server was fully decommissioned successfully!"));
315
+
316
+ /** This event is triggered when the device went online. This means that it is discoverable in the network. */
317
+ server.lifecycle.online.on(() => console.log("Server is online"));
318
+
319
+ /** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
320
+ server.lifecycle.offline.on(() => console.log("Server is offline"));
321
+
322
+ /**
323
+ * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
324
+ * information is needed.
325
+ */
326
+ server.events.commissioning.commissionedFabricsChanged.on((fabricIndex, fabricAction) => {
327
+ let action = "";
328
+ switch (fabricAction) {
329
+ case FabricAction.Added:
330
+ action = "added";
331
+ break;
332
+ case FabricAction.Removed:
333
+ action = "removed";
334
+ break;
335
+ case FabricAction.Updated:
336
+ action = "updated";
337
+ break;
338
+ }
339
+ console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);
340
+ console.log(server.state.operationalCredentials.fabrics);
341
+ });
342
+
343
+ /**
344
+ * This event is triggered when an operative new session was opened by a Controller.
345
+ * It is not triggered for the initial commissioning process, just afterwards for real connections.
346
+ */
347
+ server.events.sessions.opened.on(session => console.log(`Session opened`, session));
348
+
349
+ /**
350
+ * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
351
+ */
352
+ server.events.sessions.closed.on(session => console.log(`Session closed`, session));
353
+
354
+ /** This event is triggered when a subscription gets added or removed on an operative session. */
355
+ server.events.sessions.subscriptionsChanged.on(session => {
356
+ console.log(`Session subscriptions changed`, session);
357
+ console.log(`Status of all sessions`, server.state.sessions.sessions);
358
+ });
359
+
360
+ // React on a change of identificationTime to do Identify stuff for the own device
361
+ let isIdentifying = false;
362
+ endpoint.events.identify.identifyTime$Change.on(value => {
363
+ if (value > 0 && !isIdentifying) {
364
+ isIdentifying = true;
365
+ console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
366
+ } else if (value === 0) {
367
+ isIdentifying = false;
368
+ console.log(`Stop identify logic ...`);
369
+ }
370
+ });
371
+
372
+ // Our device is now built and we can bring the node online.
373
+ //
374
+ // Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()
375
+ // method of the node.
376
+
377
+ logEndpoint(EndpointServer.forEndpoint(server));
378
+
379
+ /**
380
+ * In order to start the node and announce it into the network we start the node. This method resolves when the Matter
381
+ * node enters his online state. Alternatively, we could also use `await server.run()` which
382
+ * resolves when the node goes offline again, but we want to execute code afterwards, so we use start() here
383
+ */
384
+ await server.bringOnline();
385
+
386
+ console.log("Initial Fabrics", server.state.operationalCredentials.fabrics);
387
+
388
+ /**
389
+ * If the node is not commissioned already we display the QR code on console. The QR code is also logged
390
+ */
391
+ if (!server.lifecycle.isCommissioned) {
392
+ const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;
393
+
394
+ console.log(QrCode.get(qrPairingCode));
395
+ console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);
396
+ console.log(`Manual pairing code: ${manualPairingCode}`);
397
+ } else {
398
+ console.log("Device is already commissioned. Waiting for controllers to connect ...");
399
+
400
+ /**
401
+ * Sometimes reading or writing attributes is required. The following code shows how this works.
402
+ * For read it is basically `endpoint.state.clustername.attributename`.
403
+ * The set method allows to set one or multiple values via the structure of also clustername.attributename. When multiple values are set they are considered being one transaction which would be rolled back completely if one value fails to be set.
404
+ */
405
+
406
+ // Read onOff attribute from onOff cluster
407
+ const onOffValue = endpoint.state.onOff.onOff;
408
+ console.log(`current OnOff attribute: ${onOffValue}`);
409
+
410
+ if (vendorId === 0xfff4) {
411
+ // Set onOff attribute from OnOff cluster AND the myFancyValue of the MyFancyOwnFunctionality cluster together
412
+ await endpoint.set({
413
+ onOff: {
414
+ onOff: !onOffValue,
415
+ },
416
+ // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.
417
+ myFancyOwnFunctionality: {
418
+ myFancyValue: 36,
419
+ },
420
+ });
421
+ } else {
422
+ // Set onOff attribute from OnOff cluster only
423
+ await endpoint.set({
424
+ onOff: {
425
+ onOff: !onOffValue,
426
+ },
427
+ });
428
+ }
429
+ }
430
+
431
+ /**
432
+ * To correctly tear down the now we can use server[Symbol.asyncDispose]().
433
+ */
434
+ process.on("SIGINT", () => {
435
+ // Clean up on CTRL-C
436
+ server
437
+ .close()
438
+ .then(() => process.exit(0))
439
+ .catch(err => console.error(err));
440
+ });