@matter/examples 0.11.0-alpha.0-20241005-e3e4e4a7a

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 (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +274 -0
  3. package/dist/esm/examples/BridgedDevicesNode.js +138 -0
  4. package/dist/esm/examples/BridgedDevicesNode.js.map +6 -0
  5. package/dist/esm/examples/ComposedDeviceNode.js +118 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js.map +6 -0
  7. package/dist/esm/examples/ControllerNode.js +191 -0
  8. package/dist/esm/examples/ControllerNode.js.map +6 -0
  9. package/dist/esm/examples/DeviceNode.js +130 -0
  10. package/dist/esm/examples/DeviceNode.js.map +6 -0
  11. package/dist/esm/examples/DeviceNodeFull.js +259 -0
  12. package/dist/esm/examples/DeviceNodeFull.js.map +6 -0
  13. package/dist/esm/examples/IlluminatedRollerShade.js +56 -0
  14. package/dist/esm/examples/IlluminatedRollerShade.js.map +6 -0
  15. package/dist/esm/examples/LightDevice.js +34 -0
  16. package/dist/esm/examples/LightDevice.js.map +6 -0
  17. package/dist/esm/examples/MultiDeviceNode.js +143 -0
  18. package/dist/esm/examples/MultiDeviceNode.js.map +6 -0
  19. package/dist/esm/examples/SensorDeviceNode.js +170 -0
  20. package/dist/esm/examples/SensorDeviceNode.js.map +6 -0
  21. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +121 -0
  22. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +6 -0
  23. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +121 -0
  24. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +6 -0
  25. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +113 -0
  26. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +6 -0
  27. package/dist/esm/package.json +3 -0
  28. package/dist/esm/tutorial/example01.js +4 -0
  29. package/dist/esm/tutorial/example01.js.map +6 -0
  30. package/dist/esm/tutorial/example02.js +6 -0
  31. package/dist/esm/tutorial/example02.js.map +6 -0
  32. package/dist/esm/tutorial/example03.js +14 -0
  33. package/dist/esm/tutorial/example03.js.map +6 -0
  34. package/dist/esm/tutorial/example04.js +9 -0
  35. package/dist/esm/tutorial/example04.js.map +6 -0
  36. package/dist/esm/tutorial/example05.js +13 -0
  37. package/dist/esm/tutorial/example05.js.map +6 -0
  38. package/package.json +70 -0
  39. package/src/examples/BridgedDevicesNode.ts +247 -0
  40. package/src/examples/ComposedDeviceNode.ts +185 -0
  41. package/src/examples/ControllerNode.ts +305 -0
  42. package/src/examples/DeviceNode.ts +198 -0
  43. package/src/examples/DeviceNodeFull.ts +440 -0
  44. package/src/examples/IlluminatedRollerShade.ts +89 -0
  45. package/src/examples/LightDevice.ts +58 -0
  46. package/src/examples/MultiDeviceNode.ts +205 -0
  47. package/src/examples/SensorDeviceNode.ts +236 -0
  48. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +162 -0
  49. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +160 -0
  50. package/src/examples/cluster/MyFancyOwnFunctionality.ts +188 -0
  51. package/src/tsconfig.json +13 -0
  52. package/src/tsconfig.tsbuildinfo +1 -0
  53. package/src/tutorial/example01.ts +5 -0
  54. package/src/tutorial/example02.ts +8 -0
  55. package/src/tutorial/example03.ts +18 -0
  56. package/src/tutorial/example04.ts +12 -0
  57. package/src/tutorial/example05.ts +18 -0
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/tutorial/example05.ts"],
4
+ "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,wBAAwB;AAEjC,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;",
5
+ "names": []
6
+ }
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@matter/examples",
3
+ "version": "0.11.0-alpha.0-20241005-e3e4e4a7a",
4
+ "description": "Matter.js examples and reference implementations",
5
+ "keywords": [
6
+ "iot",
7
+ "home automation",
8
+ "matter",
9
+ "smart device"
10
+ ],
11
+ "license": "Apache-2.0",
12
+ "author": "matter.js authors",
13
+ "contributors": [
14
+ "Ingo Fischer <github@fischer-ka.de>",
15
+ "Martin Turon <mturon@google.com>",
16
+ "Marco Fucci di Napoli <mfucci@gmail.com>",
17
+ "Greg Lauckhart <greg@lauckhart.com>"
18
+ ],
19
+ "bugs": {
20
+ "url": "https://github.com/project-chip/matter.js/issues"
21
+ },
22
+ "homepage": "https://github.com/project-chip/matter.js",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/project-chip/matter.js.git"
26
+ },
27
+ "scripts": {
28
+ "clean": "matter-build clean",
29
+ "build": "matter-build",
30
+ "build-clean": "matter-build --clean",
31
+ "matter-light": "matter-run src/examples/LightDevice.ts",
32
+ "matter-sensor": "matter-run src/examples/SensorDeviceNode.ts",
33
+ "matter-excelsior1000": "matter-run src/examples/IlluminatedRollerShade.ts",
34
+ "matter-device": "matter-run src/examples/DeviceNode.ts",
35
+ "matter-bridge": "matter-run src/examples/BridgedDevicesNode.ts",
36
+ "matter-composeddevice": "matter-run src/examples/ComposedDeviceNode.ts",
37
+ "matter-multidevice": "matter-run src/examples/MultiDeviceNode.ts",
38
+ "matter-controller": "matter-run src/examples/ControllerNode.ts",
39
+ "bundle-device": "esbuild src/examples/DeviceNode.ts --bundle --platform=node --conditions=esbuild --external:@stoprocent/bleno --external:@stoprocent/bluetooth-hci-socket --sourcemap --minify --outfile=build/bundle/DeviceNode.cjs",
40
+ "matter-device-bundled": "node --enable-source-maps build/bundle/DeviceNode.cjs"
41
+ },
42
+ "bin": {
43
+ "matter-light": "dist/esm/examples/LightDevice.ts",
44
+ "matter-excelsior1000": "dist/esm/examples/IlluminatedRollerShade.ts",
45
+ "matter-sensor": "dist/esm/examples/SensorDeviceNode.js",
46
+ "matter-device": "dist/esm/examples/DeviceNode.js",
47
+ "matter-bridge": "dist/esm/examples/BridgedDevicesNode.js",
48
+ "matter-composeddevice": "dist/esm/examples/ComposedDeviceNode.js",
49
+ "matter-multidevice": "dist/esm/examples/MultiDeviceNode.js",
50
+ "matter-controller": "dist/esm/examples/ControllerNode.js"
51
+ },
52
+ "dependencies": {
53
+ "@matter/main": "0.11.0-alpha.0-20241005-e3e4e4a7a",
54
+ "@matter/tools": "0.11.0-alpha.0-20241005-e3e4e4a7a",
55
+ "esbuild": "^0.24.0"
56
+ },
57
+ "engines": {
58
+ "node": ">=18.0.0"
59
+ },
60
+ "files": [
61
+ "dist/**/*",
62
+ "src/**/*",
63
+ "LICENSE",
64
+ "README.md"
65
+ ],
66
+ "type": "module",
67
+ "publishConfig": {
68
+ "access": "public"
69
+ }
70
+ }
@@ -0,0 +1,247 @@
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
+ import { Endpoint, EndpointServer, Environment, ServerNode, StorageService, Time, VendorId } from "@matter/main";
16
+ import { BridgedDeviceBasicInformationServer } from "@matter/main/behaviors/bridged-device-basic-information";
17
+ import { OnOffLightDevice } from "@matter/main/devices/on-off-light";
18
+ import { OnOffPlugInUnitDevice } from "@matter/main/devices/on-off-plug-in-unit";
19
+ import { AggregatorEndpoint } from "@matter/main/endpoints/aggregator";
20
+ import { logEndpoint } from "@matter/protocol";
21
+ import { execSync } from "child_process";
22
+
23
+ /** Initialize configuration values */
24
+ const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =
25
+ await getConfiguration();
26
+
27
+ /**
28
+ * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
29
+ */
30
+ const server = await ServerNode.create({
31
+ // Required: Give the Node a unique ID which is used to store the state of this node
32
+ id: uniqueId,
33
+
34
+ // Provide Network relevant configuration like the port
35
+ // Optional when operating only one device on a host, Default port is 5540
36
+ network: {
37
+ port,
38
+ },
39
+
40
+ // Provide Commissioning relevant settings
41
+ // Optional for development/testing purposes
42
+ commissioning: {
43
+ passcode,
44
+ discriminator,
45
+ },
46
+
47
+ // Provide Node announcement settings
48
+ // Optional: If Ommitted some development defaults are used
49
+ productDescription: {
50
+ name: deviceName,
51
+ deviceType: AggregatorEndpoint.deviceType,
52
+ },
53
+
54
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
55
+ // Optional: If Omitted some development defaults are used
56
+ basicInformation: {
57
+ vendorName,
58
+ vendorId: VendorId(vendorId),
59
+ nodeLabel: productName,
60
+ productName,
61
+ productLabel: productName,
62
+ productId,
63
+ serialNumber: `matterjs-${uniqueId}`,
64
+ uniqueId,
65
+ },
66
+ });
67
+
68
+ /**
69
+ * Matter Nodes are a composition of endpoints. Create and add a single multiple endpoint to the node to make it a
70
+ * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type
71
+ * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore
72
+ * the device on restart.
73
+ *
74
+ * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
75
+ * to see how to customize the command handlers.
76
+ */
77
+
78
+ const aggregator = new Endpoint(AggregatorEndpoint, { id: "aggregator" });
79
+ await server.add(aggregator);
80
+
81
+ for (let idx = 0; idx < isSocket.length; idx++) {
82
+ const i = idx + 1;
83
+ const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?
84
+
85
+ const name = `OnOff ${isASocket ? "Socket" : "Light"} ${i}`;
86
+
87
+ const endpoint = new Endpoint(
88
+ isASocket
89
+ ? // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server
90
+ OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)
91
+ : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),
92
+ {
93
+ id: `onoff-${i}`,
94
+ bridgedDeviceBasicInformation: {
95
+ nodeLabel: name, // Main end user name for the device
96
+ productName: name,
97
+ productLabel: name,
98
+ serialNumber: `node-matter-${uniqueId}-${i}`,
99
+ reachable: true,
100
+ },
101
+ },
102
+ );
103
+ await aggregator.add(endpoint);
104
+
105
+ /**
106
+ * Register state change handlers and events of the endpoint for identify and onoff states to react to the commands.
107
+ *
108
+ * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
109
+ * reported back to the controller.
110
+ */
111
+ endpoint.events.identify.startIdentifying.on(() => {
112
+ console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);
113
+ });
114
+
115
+ endpoint.events.identify.stopIdentifying.on(() => {
116
+ console.log(`Stop identify logic for ${name} ...`);
117
+ });
118
+
119
+ endpoint.events.onOff.onOff$Changed.on(value => {
120
+ executeCommand(value ? `on${i}` : `off${i}`);
121
+ console.log(`${name} is now ${value ? "ON" : "OFF"}`);
122
+ });
123
+ }
124
+
125
+ /**
126
+ * In order to start the node and announce it into the network we use the run method which resolves when the node goes
127
+ * offline again because we do not need anything more here. See the Full example for other starting options.
128
+ * The QR Code is printed automatically.
129
+ */
130
+ await server.start();
131
+
132
+ /**
133
+ * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
134
+ */
135
+ logEndpoint(EndpointServer.forEndpoint(server));
136
+
137
+ /*
138
+ If you want to dynamically add another device during runtime you can do so by doing the following:
139
+
140
+ const name = `OnOff Light 3`;
141
+
142
+ const endpoint = new Endpoint(OnOffLightDevice.with(BridgedDeviceBasicInformationServer), {
143
+ id: `onoff-3`,
144
+ bridgedDeviceBasicInformation: {
145
+ nodeLabel: name,
146
+ productName: name,
147
+ productLabel: name,
148
+ serialNumber: `node-matter-${uniqueId}-3`,
149
+ reachable: true,
150
+ },
151
+ });
152
+ await aggregator.add(endpoint);
153
+
154
+ endpoint.events.onOff.onOff$Changed.on(value => {
155
+ executeCommand(value ? `on3` : `off3`);
156
+ console.log(`${name} is now ${value ? "ON" : "OFF"}`);
157
+ });
158
+
159
+ */
160
+
161
+ /*
162
+ To remove a device during runtime you can do so by doing the following:
163
+ console.log("Removing Light 3 now!!");
164
+
165
+ await endpoint.close();
166
+
167
+ This will automatically remove the endpoint from the bridge.
168
+ */
169
+
170
+ /*********************************************************************************************************
171
+ * Convenience Methods
172
+ *********************************************************************************************************/
173
+
174
+ /** Defined a shell command from an environment variable and execute it and log the response. */
175
+ function executeCommand(scriptParamName: string) {
176
+ const script = Environment.default.vars.string(scriptParamName);
177
+ if (script === undefined) return undefined;
178
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
179
+ }
180
+
181
+ async function getConfiguration() {
182
+ /**
183
+ * Collect all needed data
184
+ *
185
+ * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.
186
+ *
187
+ * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
188
+ * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
189
+ * (so maybe better not do it ;-)).
190
+ */
191
+ const environment = Environment.default;
192
+
193
+ const storageService = environment.get(StorageService);
194
+ console.log(`Storage location: ${storageService.location} (Directory)`);
195
+ console.log(
196
+ '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.',
197
+ );
198
+ const deviceStorage = (await storageService.open("device")).createContext("data");
199
+
200
+ const isSocket = Array<boolean>();
201
+ const numDevices = environment.vars.number("num") || 2;
202
+ if (await deviceStorage.has("isSocket")) {
203
+ console.log(`Device types found in storage. --type parameter is ignored.`);
204
+ (await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
205
+ }
206
+ for (let i = 1; i <= numDevices; i++) {
207
+ if (isSocket[i - 1] !== undefined) continue;
208
+ isSocket.push(environment.vars.string(`type${i}`) === "socket");
209
+ }
210
+
211
+ const deviceName = "Matter test device";
212
+ const vendorName = "matter-node.js";
213
+ const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
214
+ const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
215
+ // product name / id and vendor id should match what is in the device certificate
216
+ const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
217
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
218
+ const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
219
+
220
+ const port = environment.vars.number("port") ?? 5540;
221
+
222
+ const uniqueId =
223
+ environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
224
+
225
+ // Persist basic data to keep them also on restart
226
+ await deviceStorage.set({
227
+ passcode,
228
+ discriminator,
229
+ vendorid: vendorId,
230
+ productid: productId,
231
+ isSocket,
232
+ uniqueid: uniqueId,
233
+ });
234
+
235
+ return {
236
+ isSocket,
237
+ deviceName,
238
+ vendorName,
239
+ passcode,
240
+ discriminator,
241
+ vendorId,
242
+ productName,
243
+ productId,
244
+ port,
245
+ uniqueId,
246
+ };
247
+ }
@@ -0,0 +1,185 @@
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
+ import { Endpoint, EndpointServer, Environment, ServerNode, StorageService, Time } from "@matter/main";
16
+ import { OnOffLightDevice } from "@matter/main/devices/on-off-light";
17
+ import { OnOffPlugInUnitDevice } from "@matter/main/devices/on-off-plug-in-unit";
18
+ import { logEndpoint } from "@matter/protocol";
19
+ import { DeviceTypeId, VendorId } from "@matter/types";
20
+ import { execSync } from "child_process";
21
+
22
+ /** Initialize configuration values */
23
+ const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =
24
+ await getConfiguration();
25
+
26
+ /**
27
+ * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
28
+ */
29
+ const server = await ServerNode.create({
30
+ // Required: Give the Node a unique ID which is used to store the state of this node
31
+ id: uniqueId,
32
+
33
+ // Provide Network relevant configuration like the port
34
+ // Optional when operating only one device on a host, Default port is 5540
35
+ network: {
36
+ port,
37
+ },
38
+
39
+ // Provide Commissioning relevant settings
40
+ // Optional for development/testing purposes
41
+ commissioning: {
42
+ passcode,
43
+ discriminator,
44
+ },
45
+
46
+ // Provide Node announcement settings
47
+ // Optional: If Ommitted some development defaults are used
48
+ productDescription: {
49
+ name: deviceName,
50
+ deviceType: DeviceTypeId(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),
51
+ },
52
+
53
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
54
+ // Optional: If Omitted some development defaults are used
55
+ basicInformation: {
56
+ vendorName,
57
+ vendorId: VendorId(vendorId),
58
+ nodeLabel: productName,
59
+ productName,
60
+ productLabel: productName,
61
+ productId,
62
+ serialNumber: `matterjs-${uniqueId}`,
63
+ uniqueId,
64
+ },
65
+ });
66
+
67
+ /**
68
+ * Matter Nodes are a composition of endpoints. Create and add a single multiple endpoint to the node to make it a
69
+ * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type
70
+ * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore
71
+ * the device on restart.
72
+ *
73
+ * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
74
+ * to see how to customize the command handlers.
75
+ */
76
+
77
+ for (let idx = 0; idx < isSocket.length; idx++) {
78
+ const i = idx + 1;
79
+ const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?
80
+ const endpoint = new Endpoint(isASocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: `onoff-${i}` });
81
+ await server.add(endpoint);
82
+
83
+ /**
84
+ * Register state change handlers of the endpoint for identify and onoff states to react to the commands.
85
+ *
86
+ * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
87
+ * reported back to the controller.
88
+ */
89
+ endpoint.events.identify.startIdentifying.on(() => {
90
+ console.log(`Run identify logic for sub device ${i}, ideally blink a light every 0.5s ...`);
91
+ });
92
+
93
+ endpoint.events.identify.stopIdentifying.on(() => {
94
+ console.log(`Stop identify logic for sub device ${i}...`);
95
+ });
96
+
97
+ endpoint.events.onOff.onOff$Changed.on(value => {
98
+ executeCommand(value ? `on${i}` : `off${i}`);
99
+ console.log(`OnOff ${i} is now ${value ? "ON" : "OFF"}`);
100
+ });
101
+ }
102
+
103
+ /**
104
+ * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
105
+ */
106
+ logEndpoint(EndpointServer.forEndpoint(server));
107
+
108
+ /**
109
+ * In order to start the node and announce it into the network we use the run method which resolves when the node goes
110
+ * offline again because we do not need anything more here. See the Full example for other starting options.
111
+ * The QR Code is printed automatically.
112
+ */
113
+ await server.run();
114
+
115
+ /*********************************************************************************************************
116
+ * Convenience Methods
117
+ *********************************************************************************************************/
118
+
119
+ /**
120
+ * Defines a shell command from an environment variable and execute it and log the response
121
+ */
122
+ function executeCommand(scriptParamName: string) {
123
+ const script = Environment.default.vars.string(scriptParamName);
124
+ if (script === undefined) return undefined;
125
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
126
+ }
127
+
128
+ async function getConfiguration() {
129
+ const environment = Environment.default;
130
+
131
+ const storageService = environment.get(StorageService);
132
+ console.log(`Storage location: ${storageService.location} (Directory)`);
133
+ console.log(
134
+ '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.',
135
+ );
136
+ const deviceStorage = (await storageService.open("device")).createContext("data");
137
+
138
+ const isSocket = Array<boolean>();
139
+ const numDevices = environment.vars.number("num") || 2;
140
+ if (await deviceStorage.has("isSocket")) {
141
+ console.log(`Device types found in storage. --type parameter is ignored.`);
142
+ (await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
143
+ }
144
+ for (let i = 1; i < numDevices; i++) {
145
+ if (isSocket[i - 1] !== undefined) continue;
146
+ isSocket.push(environment.vars.string(`type${i}`) === "socket");
147
+ }
148
+
149
+ const deviceName = "Matter test device";
150
+ const vendorName = "matter-node.js";
151
+ const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
152
+ const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
153
+ // product name / id and vendor id should match what is in the device certificate
154
+ const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
155
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
156
+ const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
157
+
158
+ const port = environment.vars.number("port") ?? 5540;
159
+
160
+ const uniqueId =
161
+ environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
162
+
163
+ // Persist basic data to keep them also on restart
164
+ await deviceStorage.set({
165
+ passcode,
166
+ discriminator,
167
+ vendorid: vendorId,
168
+ productid: productId,
169
+ isSocket,
170
+ uniqueid: uniqueId,
171
+ });
172
+
173
+ return {
174
+ isSocket,
175
+ deviceName,
176
+ vendorName,
177
+ passcode,
178
+ discriminator,
179
+ vendorId,
180
+ productName,
181
+ productId,
182
+ port,
183
+ uniqueId,
184
+ };
185
+ }