@project-chip/matter-node.js-examples 0.11.0-alpha.0-20240909-b3b29745 → 0.11.0-alpha.0-20241006-eccb81ae1

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 (76) hide show
  1. package/README.md +3 -271
  2. package/dist/esm/examples/BridgedDevicesNodeLegacy.js +14 -14
  3. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +1 -2
  4. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +15 -15
  5. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +1 -2
  6. package/dist/esm/examples/ControllerNodeLegacy.js +22 -22
  7. package/dist/esm/examples/ControllerNodeLegacy.js.map +1 -2
  8. package/dist/esm/examples/DeviceNodeFullLegacy.js +16 -16
  9. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +1 -2
  10. package/dist/esm/examples/LegacyStorageConverter.js +1 -2
  11. package/dist/esm/examples/LegacyStorageConverter.js.map +1 -2
  12. package/dist/esm/examples/MultiDeviceNodeLegacy.js +14 -14
  13. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +1 -2
  14. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js +16 -13
  15. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +1 -2
  16. package/dist/esm/package.json +3 -0
  17. package/package.json +16 -36
  18. package/src/examples/BridgedDevicesNodeLegacy.ts +14 -14
  19. package/src/examples/ComposedDeviceNodeLegacy.ts +15 -15
  20. package/src/examples/ControllerNodeLegacy.ts +24 -24
  21. package/src/examples/DeviceNodeFullLegacy.ts +17 -17
  22. package/src/examples/LegacyStorageConverter.ts +2 -2
  23. package/src/examples/MultiDeviceNodeLegacy.ts +14 -14
  24. package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +16 -13
  25. package/src/tsconfig.json +13 -13
  26. package/dist/esm/examples/BridgedDevicesNode.js +0 -145
  27. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  28. package/dist/esm/examples/ComposedDeviceNode.js +0 -124
  29. package/dist/esm/examples/ComposedDeviceNode.js.map +0 -7
  30. package/dist/esm/examples/ControllerNode.js +0 -197
  31. package/dist/esm/examples/ControllerNode.js.map +0 -7
  32. package/dist/esm/examples/DeviceNode.js +0 -128
  33. package/dist/esm/examples/DeviceNode.js.map +0 -7
  34. package/dist/esm/examples/DeviceNodeFull.js +0 -257
  35. package/dist/esm/examples/DeviceNodeFull.js.map +0 -7
  36. package/dist/esm/examples/IlluminatedRollerShade.js +0 -60
  37. package/dist/esm/examples/IlluminatedRollerShade.js.map +0 -7
  38. package/dist/esm/examples/LightDevice.js +0 -35
  39. package/dist/esm/examples/LightDevice.js.map +0 -7
  40. package/dist/esm/examples/MultiDeviceNode.js +0 -141
  41. package/dist/esm/examples/MultiDeviceNode.js.map +0 -7
  42. package/dist/esm/examples/SensorDeviceNode.js +0 -176
  43. package/dist/esm/examples/SensorDeviceNode.js.map +0 -7
  44. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +0 -118
  45. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +0 -7
  46. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +0 -117
  47. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +0 -7
  48. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +0 -110
  49. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +0 -7
  50. package/dist/esm/tutorial/example01.js +0 -5
  51. package/dist/esm/tutorial/example01.js.map +0 -7
  52. package/dist/esm/tutorial/example02.js +0 -7
  53. package/dist/esm/tutorial/example02.js.map +0 -7
  54. package/dist/esm/tutorial/example03.js +0 -15
  55. package/dist/esm/tutorial/example03.js.map +0 -7
  56. package/dist/esm/tutorial/example04.js +0 -10
  57. package/dist/esm/tutorial/example04.js.map +0 -7
  58. package/dist/esm/tutorial/example05.js +0 -14
  59. package/dist/esm/tutorial/example05.js.map +0 -7
  60. package/src/examples/BridgedDevicesNode.ts +0 -260
  61. package/src/examples/ComposedDeviceNode.ts +0 -197
  62. package/src/examples/ControllerNode.ts +0 -318
  63. package/src/examples/DeviceNode.ts +0 -202
  64. package/src/examples/DeviceNodeFull.ts +0 -445
  65. package/src/examples/IlluminatedRollerShade.ts +0 -96
  66. package/src/examples/LightDevice.ts +0 -61
  67. package/src/examples/MultiDeviceNode.ts +0 -209
  68. package/src/examples/SensorDeviceNode.ts +0 -248
  69. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +0 -153
  70. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +0 -150
  71. package/src/examples/cluster/MyFancyOwnFunctionality.ts +0 -185
  72. package/src/tutorial/example01.ts +0 -6
  73. package/src/tutorial/example02.ts +0 -9
  74. package/src/tutorial/example03.ts +0 -19
  75. package/src/tutorial/example04.ts +0 -13
  76. package/src/tutorial/example05.ts +0 -19
@@ -1,7 +0,0 @@
1
- import "@project-chip/matter-node.js";
2
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
3
- import { ServerNode } from "@project-chip/matter.js/node";
4
- const node = await ServerNode.create();
5
- await node.add(OnOffLightDevice);
6
- await node.run();
7
- //# sourceMappingURL=example02.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/tutorial/example02.ts"],
4
- "sourcesContent": ["import \"@project-chip/matter-node.js\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\nconst node = await ServerNode.create();\n\nawait node.add(OnOffLightDevice);\n\nawait node.run();\n"],
5
- "mappings": "AAAA,OAAO;AACP,SAAS,wBAAwB;AACjC,SAAS,kBAAkB;AAE3B,MAAM,OAAO,MAAM,WAAW,OAAO;AAErC,MAAM,KAAK,IAAI,gBAAgB;AAE/B,MAAM,KAAK,IAAI;",
6
- "names": []
7
- }
@@ -1,15 +0,0 @@
1
- import "@project-chip/matter-node.js";
2
- import { OnOffLightDevice, OnOffLightRequirements } from "@project-chip/matter.js/devices/OnOffLightDevice";
3
- import { ServerNode } from "@project-chip/matter.js/node";
4
- class MyOnOffServer extends OnOffLightRequirements.OnOffServer {
5
- on() {
6
- console.log("Turning on");
7
- }
8
- off() {
9
- console.log("Turning off");
10
- }
11
- }
12
- const node = await ServerNode.create();
13
- await node.add(OnOffLightDevice.with(MyOnOffServer));
14
- await node.run();
15
- //# sourceMappingURL=example03.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/tutorial/example03.ts"],
4
- "sourcesContent": ["import \"@project-chip/matter-node.js\";\nimport { OnOffLightDevice, OnOffLightRequirements } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\nclass MyOnOffServer extends OnOffLightRequirements.OnOffServer {\n override on() {\n console.log(\"Turning on\");\n }\n\n override off() {\n console.log(\"Turning off\");\n }\n}\n\nconst node = await ServerNode.create();\n\nawait node.add(OnOffLightDevice.with(MyOnOffServer));\n\nawait node.run();\n"],
5
- "mappings": "AAAA,OAAO;AACP,SAAS,kBAAkB,8BAA8B;AACzD,SAAS,kBAAkB;AAE3B,MAAM,sBAAsB,uBAAuB,YAAY;AAAA,EAClD,KAAK;AACV,YAAQ,IAAI,YAAY;AAAA,EAC5B;AAAA,EAES,MAAM;AACX,YAAQ,IAAI,aAAa;AAAA,EAC7B;AACJ;AAEA,MAAM,OAAO,MAAM,WAAW,OAAO;AAErC,MAAM,KAAK,IAAI,iBAAiB,KAAK,aAAa,CAAC;AAEnD,MAAM,KAAK,IAAI;",
6
- "names": []
7
- }
@@ -1,10 +0,0 @@
1
- import "@project-chip/matter-node.js";
2
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
3
- import { ServerNode } from "@project-chip/matter.js/node";
4
- const node = await ServerNode.create();
5
- const light = await node.add(OnOffLightDevice);
6
- light.events.onOff.onOff$Changed.on((newValue) => {
7
- console.log(`Light is ${newValue ? "on" : "off"}`);
8
- });
9
- await node.run();
10
- //# sourceMappingURL=example04.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/tutorial/example04.ts"],
4
- "sourcesContent": ["import \"@project-chip/matter-node.js\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\nconst node = await ServerNode.create();\n\nconst light = await node.add(OnOffLightDevice);\n\nlight.events.onOff.onOff$Changed.on(newValue => {\n console.log(`Light is ${newValue ? \"on\" : \"off\"}`);\n});\n\nawait node.run();\n"],
5
- "mappings": "AAAA,OAAO;AACP,SAAS,wBAAwB;AACjC,SAAS,kBAAkB;AAE3B,MAAM,OAAO,MAAM,WAAW,OAAO;AAErC,MAAM,QAAQ,MAAM,KAAK,IAAI,gBAAgB;AAE7C,MAAM,OAAO,MAAM,cAAc,GAAG,cAAY;AAC5C,UAAQ,IAAI,YAAY,WAAW,OAAO,KAAK,EAAE;AACrD,CAAC;AAED,MAAM,KAAK,IAAI;",
6
- "names": []
7
- }
@@ -1,14 +0,0 @@
1
- import "@project-chip/matter-node.js";
2
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
3
- import { ServerNode } from "@project-chip/matter.js/node";
4
- const node = await ServerNode.create();
5
- const light = await node.add(OnOffLightDevice);
6
- await node.start();
7
- await light.act(async (agent) => {
8
- await agent.onOff.toggle();
9
- console.log("On/off state after first toggle", agent.onOff.state);
10
- await agent.onOff.toggle();
11
- console.log("On/off state after second toggle", agent.onOff.state);
12
- });
13
- await node.close();
14
- //# sourceMappingURL=example05.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/tutorial/example05.ts"],
4
- "sourcesContent": ["import \"@project-chip/matter-node.js\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\nconst node = await ServerNode.create();\n\nconst light = await node.add(OnOffLightDevice);\n\nawait node.start();\n\nawait light.act(async agent => {\n await agent.onOff.toggle();\n console.log(\"On/off state after first toggle\", agent.onOff.state);\n\n await agent.onOff.toggle();\n console.log(\"On/off state after second toggle\", agent.onOff.state);\n});\n\nawait node.close();\n"],
5
- "mappings": "AAAA,OAAO;AACP,SAAS,wBAAwB;AACjC,SAAS,kBAAkB;AAE3B,MAAM,OAAO,MAAM,WAAW,OAAO;AAErC,MAAM,QAAQ,MAAM,KAAK,IAAI,gBAAgB;AAE7C,MAAM,KAAK,MAAM;AAEjB,MAAM,MAAM,IAAI,OAAM,UAAS;AAC3B,QAAM,MAAM,MAAM,OAAO;AACzB,UAAQ,IAAI,mCAAmC,MAAM,MAAM,KAAK;AAEhE,QAAM,MAAM,MAAM,OAAO;AACzB,UAAQ,IAAI,oCAAoC,MAAM,MAAM,KAAK;AACrE,CAAC;AAED,MAAM,KAAK,MAAM;",
6
- "names": []
7
- }
@@ -1,260 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @license
4
- * Copyright 2022-2024 Matter.js Authors
5
- * SPDX-License-Identifier: Apache-2.0
6
- */
7
-
8
- /**
9
- * This example shows how to create a new device node that is composed of multiple devices.
10
- * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please
11
- * refer to the bridge example!
12
- * It can be used as CLI script and starting point for your own device node implementation.
13
- */
14
-
15
- /**
16
- * Import needed modules from @project-chip/matter-node.js
17
- */
18
- // Include this first to auto-register Crypto, Network and Time Node.js implementations
19
- import "@project-chip/matter-node.js";
20
-
21
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
22
- import { BridgedDeviceBasicInformationServer } from "@project-chip/matter.js/behavior/definitions/bridged-device-basic-information";
23
- import { VendorId } from "@project-chip/matter.js/datatype";
24
- import { logEndpoint } from "@project-chip/matter.js/device";
25
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
26
- import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
27
- import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
28
- import { AggregatorEndpoint } from "@project-chip/matter.js/endpoints/AggregatorEndpoint";
29
- import { Environment, StorageService } from "@project-chip/matter.js/environment";
30
- import { ServerNode } from "@project-chip/matter.js/node";
31
- import { Time } from "@project-chip/matter.js/time";
32
- import { execSync } from "child_process";
33
-
34
- requireMinNodeVersion(16);
35
-
36
- /** Initialize configuration values */
37
- const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =
38
- await getConfiguration();
39
-
40
- /**
41
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
42
- */
43
- const server = await ServerNode.create({
44
- // Required: Give the Node a unique ID which is used to store the state of this node
45
- id: uniqueId,
46
-
47
- // Provide Network relevant configuration like the port
48
- // Optional when operating only one device on a host, Default port is 5540
49
- network: {
50
- port,
51
- },
52
-
53
- // Provide Commissioning relevant settings
54
- // Optional for development/testing purposes
55
- commissioning: {
56
- passcode,
57
- discriminator,
58
- },
59
-
60
- // Provide Node announcement settings
61
- // Optional: If Ommitted some development defaults are used
62
- productDescription: {
63
- name: deviceName,
64
- deviceType: AggregatorEndpoint.deviceType,
65
- },
66
-
67
- // Provide defaults for the BasicInformation cluster on the Root endpoint
68
- // Optional: If Omitted some development defaults are used
69
- basicInformation: {
70
- vendorName,
71
- vendorId: VendorId(vendorId),
72
- nodeLabel: productName,
73
- productName,
74
- productLabel: productName,
75
- productId,
76
- serialNumber: `matterjs-${uniqueId}`,
77
- uniqueId,
78
- },
79
- });
80
-
81
- /**
82
- * Matter Nodes are a composition of endpoints. Create and add a single multiple endpoint to the node to make it a
83
- * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type
84
- * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore
85
- * the device on restart.
86
- *
87
- * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
88
- * to see how to customize the command handlers.
89
- */
90
-
91
- const aggregator = new Endpoint(AggregatorEndpoint, { id: "aggregator" });
92
- await server.add(aggregator);
93
-
94
- for (let idx = 0; idx < isSocket.length; idx++) {
95
- const i = idx + 1;
96
- const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?
97
-
98
- const name = `OnOff ${isASocket ? "Socket" : "Light"} ${i}`;
99
-
100
- const endpoint = new Endpoint(
101
- isASocket
102
- ? // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server
103
- OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)
104
- : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),
105
- {
106
- id: `onoff-${i}`,
107
- bridgedDeviceBasicInformation: {
108
- nodeLabel: name, // Main end user name for the device
109
- productName: name,
110
- productLabel: name,
111
- serialNumber: `node-matter-${uniqueId}-${i}`,
112
- reachable: true,
113
- },
114
- },
115
- );
116
- await aggregator.add(endpoint);
117
-
118
- /**
119
- * Register state change handlers and events of the endpoint for identify and onoff states to react to the commands.
120
- *
121
- * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
122
- * reported back to the controller.
123
- */
124
- endpoint.events.identify.startIdentifying.on(() => {
125
- console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);
126
- });
127
-
128
- endpoint.events.identify.stopIdentifying.on(() => {
129
- console.log(`Stop identify logic for ${name} ...`);
130
- });
131
-
132
- endpoint.events.onOff.onOff$Changed.on(value => {
133
- executeCommand(value ? `on${i}` : `off${i}`);
134
- console.log(`${name} is now ${value ? "ON" : "OFF"}`);
135
- });
136
- }
137
-
138
- /**
139
- * In order to start the node and announce it into the network we use the run method which resolves when the node goes
140
- * offline again because we do not need anything more here. See the Full example for other starting options.
141
- * The QR Code is printed automatically.
142
- */
143
- await server.start();
144
-
145
- /**
146
- * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
147
- */
148
- logEndpoint(EndpointServer.forEndpoint(server));
149
-
150
- /*
151
- If you want to dynamically add another device during runtime you can do so by doing the following:
152
-
153
- const name = `OnOff Light 3`;
154
-
155
- const endpoint = new Endpoint(OnOffLightDevice.with(BridgedDeviceBasicInformationServer), {
156
- id: `onoff-3`,
157
- bridgedDeviceBasicInformation: {
158
- nodeLabel: name,
159
- productName: name,
160
- productLabel: name,
161
- serialNumber: `node-matter-${uniqueId}-3`,
162
- reachable: true,
163
- },
164
- });
165
- await aggregator.add(endpoint);
166
-
167
- endpoint.events.onOff.onOff$Changed.on(value => {
168
- executeCommand(value ? `on3` : `off3`);
169
- console.log(`${name} is now ${value ? "ON" : "OFF"}`);
170
- });
171
-
172
- */
173
-
174
- /*
175
- To remove a device during runtime you can do so by doing the following:
176
- console.log("Removing Light 3 now!!");
177
-
178
- await endpoint.close();
179
-
180
- This will automatically remove the endpoint from the bridge.
181
- */
182
-
183
- /*********************************************************************************************************
184
- * Convenience Methods
185
- *********************************************************************************************************/
186
-
187
- /** Defined a shell command from an environment variable and execute it and log the response. */
188
- function executeCommand(scriptParamName: string) {
189
- const script = Environment.default.vars.string(scriptParamName);
190
- if (script === undefined) return undefined;
191
- console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
192
- }
193
-
194
- async function getConfiguration() {
195
- /**
196
- * Collect all needed data
197
- *
198
- * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.
199
- *
200
- * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
201
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
202
- * (so maybe better not do it ;-)).
203
- */
204
- const environment = Environment.default;
205
-
206
- const storageService = environment.get(StorageService);
207
- console.log(`Storage location: ${storageService.location} (Directory)`);
208
- console.log(
209
- '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.',
210
- );
211
- const deviceStorage = (await storageService.open("device")).createContext("data");
212
-
213
- const isSocket = Array<boolean>();
214
- const numDevices = environment.vars.number("num") || 2;
215
- if (await deviceStorage.has("isSocket")) {
216
- console.log(`Device types found in storage. --type parameter is ignored.`);
217
- (await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
218
- }
219
- for (let i = 1; i <= numDevices; i++) {
220
- if (isSocket[i - 1] !== undefined) continue;
221
- isSocket.push(environment.vars.string(`type${i}`) === "socket");
222
- }
223
-
224
- const deviceName = "Matter test device";
225
- const vendorName = "matter-node.js";
226
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
227
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
228
- // product name / id and vendor id should match what is in the device certificate
229
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
230
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
231
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
232
-
233
- const port = environment.vars.number("port") ?? 5540;
234
-
235
- const uniqueId =
236
- environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
237
-
238
- // Persist basic data to keep them also on restart
239
- await deviceStorage.set({
240
- passcode,
241
- discriminator,
242
- vendorid: vendorId,
243
- productid: productId,
244
- isSocket,
245
- uniqueid: uniqueId,
246
- });
247
-
248
- return {
249
- isSocket,
250
- deviceName,
251
- vendorName,
252
- passcode,
253
- discriminator,
254
- vendorId,
255
- productName,
256
- productId,
257
- port,
258
- uniqueId,
259
- };
260
- }
@@ -1,197 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @license
4
- * Copyright 2022-2024 Matter.js Authors
5
- * SPDX-License-Identifier: Apache-2.0
6
- */
7
-
8
- /**
9
- * This example shows how to create a new device node that is composed of multiple devices.
10
- * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please
11
- * refer to the bridge example!
12
- * It can be used as CLI script and starting point for your own device node implementation.
13
- */
14
-
15
- /**
16
- * Import needed modules from @project-chip/matter-node.js
17
- */
18
- // Include this first to auto-register Crypto, Network and Time Node.js implementations
19
- import "@project-chip/matter-node.js";
20
-
21
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
22
- import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
23
- import { logEndpoint } from "@project-chip/matter.js/device";
24
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
25
- import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
26
- import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
27
- import { Environment, StorageService } from "@project-chip/matter.js/environment";
28
- import { ServerNode } from "@project-chip/matter.js/node";
29
- import { Time } from "@project-chip/matter.js/time";
30
- import { execSync } from "child_process";
31
-
32
- requireMinNodeVersion(16);
33
-
34
- /** Initialize configuration values */
35
- const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =
36
- await getConfiguration();
37
-
38
- /**
39
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
40
- */
41
- const server = await ServerNode.create({
42
- // Required: Give the Node a unique ID which is used to store the state of this node
43
- id: uniqueId,
44
-
45
- // Provide Network relevant configuration like the port
46
- // Optional when operating only one device on a host, Default port is 5540
47
- network: {
48
- port,
49
- },
50
-
51
- // Provide Commissioning relevant settings
52
- // Optional for development/testing purposes
53
- commissioning: {
54
- passcode,
55
- discriminator,
56
- },
57
-
58
- // Provide Node announcement settings
59
- // Optional: If Ommitted some development defaults are used
60
- productDescription: {
61
- name: deviceName,
62
- deviceType: DeviceTypeId(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),
63
- },
64
-
65
- // Provide defaults for the BasicInformation cluster on the Root endpoint
66
- // Optional: If Omitted some development defaults are used
67
- basicInformation: {
68
- vendorName,
69
- vendorId: VendorId(vendorId),
70
- nodeLabel: productName,
71
- productName,
72
- productLabel: productName,
73
- productId,
74
- serialNumber: `matterjs-${uniqueId}`,
75
- uniqueId,
76
- },
77
- });
78
-
79
- /**
80
- * Matter Nodes are a composition of endpoints. Create and add a single multiple endpoint to the node to make it a
81
- * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type
82
- * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore
83
- * the device on restart.
84
- *
85
- * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
86
- * to see how to customize the command handlers.
87
- */
88
-
89
- for (let idx = 0; idx < isSocket.length; idx++) {
90
- const i = idx + 1;
91
- const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?
92
- const endpoint = new Endpoint(isASocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: `onoff-${i}` });
93
- await server.add(endpoint);
94
-
95
- /**
96
- * Register state change handlers of the endpoint for identify and onoff states to react to the commands.
97
- *
98
- * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
99
- * reported back to the controller.
100
- */
101
- endpoint.events.identify.startIdentifying.on(() => {
102
- console.log(`Run identify logic for sub device ${i}, ideally blink a light every 0.5s ...`);
103
- });
104
-
105
- endpoint.events.identify.stopIdentifying.on(() => {
106
- console.log(`Stop identify logic for sub device ${i}...`);
107
- });
108
-
109
- endpoint.events.onOff.onOff$Changed.on(value => {
110
- executeCommand(value ? `on${i}` : `off${i}`);
111
- console.log(`OnOff ${i} is now ${value ? "ON" : "OFF"}`);
112
- });
113
- }
114
-
115
- /**
116
- * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
117
- */
118
- logEndpoint(EndpointServer.forEndpoint(server));
119
-
120
- /**
121
- * In order to start the node and announce it into the network we use the run method which resolves when the node goes
122
- * offline again because we do not need anything more here. See the Full example for other starting options.
123
- * The QR Code is printed automatically.
124
- */
125
- await server.run();
126
-
127
- /*********************************************************************************************************
128
- * Convenience Methods
129
- *********************************************************************************************************/
130
-
131
- /**
132
- * Defines a shell command from an environment variable and execute it and log the response
133
- */
134
- function executeCommand(scriptParamName: string) {
135
- const script = Environment.default.vars.string(scriptParamName);
136
- if (script === undefined) return undefined;
137
- console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
138
- }
139
-
140
- async function getConfiguration() {
141
- const environment = Environment.default;
142
-
143
- const storageService = environment.get(StorageService);
144
- console.log(`Storage location: ${storageService.location} (Directory)`);
145
- console.log(
146
- '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.',
147
- );
148
- const deviceStorage = (await storageService.open("device")).createContext("data");
149
-
150
- const isSocket = Array<boolean>();
151
- const numDevices = environment.vars.number("num") || 2;
152
- if (await deviceStorage.has("isSocket")) {
153
- console.log(`Device types found in storage. --type parameter is ignored.`);
154
- (await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
155
- }
156
- for (let i = 1; i < numDevices; i++) {
157
- if (isSocket[i - 1] !== undefined) continue;
158
- isSocket.push(environment.vars.string(`type${i}`) === "socket");
159
- }
160
-
161
- const deviceName = "Matter test device";
162
- const vendorName = "matter-node.js";
163
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
164
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
165
- // product name / id and vendor id should match what is in the device certificate
166
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
167
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
168
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
169
-
170
- const port = environment.vars.number("port") ?? 5540;
171
-
172
- const uniqueId =
173
- environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
174
-
175
- // Persist basic data to keep them also on restart
176
- await deviceStorage.set({
177
- passcode,
178
- discriminator,
179
- vendorid: vendorId,
180
- productid: productId,
181
- isSocket,
182
- uniqueid: uniqueId,
183
- });
184
-
185
- return {
186
- isSocket,
187
- deviceName,
188
- vendorName,
189
- passcode,
190
- discriminator,
191
- vendorId,
192
- productName,
193
- productId,
194
- port,
195
- uniqueId,
196
- };
197
- }