@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,209 +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
- const devices = await getConfiguration();
35
- for (let idx = 1; idx < devices.length; idx++) {
36
- const {
37
- isSocket,
38
- deviceName,
39
- vendorName,
40
- passcode,
41
- discriminator,
42
- vendorId,
43
- productName,
44
- productId,
45
- port,
46
- uniqueId,
47
- } = devices[idx];
48
- const i = idx + 1;
49
-
50
- /**
51
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
52
- */
53
- const server = await ServerNode.create({
54
- // Required: Give the Node a unique ID which is used to store the state of this node
55
- id: uniqueId,
56
-
57
- // Provide Network relevant configuration like the port
58
- // Optional when operating only one device on a host, Default port is 5540
59
- network: {
60
- port,
61
- },
62
-
63
- // Provide Commissioning relevant settings
64
- // Optional for development/testing purposes
65
- commissioning: {
66
- passcode,
67
- discriminator,
68
- },
69
-
70
- // Provide Node announcement settings
71
- // Optional: If Ommitted some development defaults are used
72
- productDescription: {
73
- name: deviceName,
74
- deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),
75
- },
76
-
77
- // Provide defaults for the BasicInformation cluster on the Root endpoint
78
- // Optional: If Omitted some development defaults are used
79
- basicInformation: {
80
- vendorName,
81
- vendorId: VendorId(vendorId),
82
- nodeLabel: productName,
83
- productName,
84
- productLabel: productName,
85
- productId,
86
- serialNumber: `matterjs-${uniqueId}`,
87
- uniqueId,
88
- },
89
- });
90
-
91
- console.log(
92
- `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,
93
- );
94
-
95
- const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: "onoff" });
96
- await server.add(endpoint);
97
-
98
- /**
99
- * Register state change handlers of the node for identify and onoff states to react to the commands.
100
- * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
101
- * reported back to the controller.
102
- */
103
- endpoint.events.identify.startIdentifying.on(() => {
104
- console.log(`Run identify logic for device ${i}, ideally blink a light every 0.5s ...`);
105
- });
106
-
107
- endpoint.events.identify.stopIdentifying.on(() => {
108
- console.log(`Stop identify logic for device ${i}...`);
109
- });
110
-
111
- endpoint.events.onOff.onOff$Changed.on(value => {
112
- executeCommand(value ? `on${i}` : `off${i}`);
113
- console.log(`OnOff ${i} is now ${value ? "ON" : "OFF"}`);
114
- });
115
-
116
- /**
117
- * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
118
- */
119
- logEndpoint(EndpointServer.forEndpoint(server));
120
-
121
- console.log("----------------------------");
122
- console.log(`QR Code for Device ${i} on port ${port}:`);
123
- console.log("----------------------------");
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
- /*********************************************************************************************************
134
- * Convenience Methods
135
- *********************************************************************************************************/
136
-
137
- /**
138
- * Defines a shell command from an environment variable and execute it and log the response
139
- */
140
- function executeCommand(scriptParamName: string) {
141
- const script = Environment.default.vars.string(scriptParamName);
142
- if (script === undefined) return undefined;
143
- console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
144
- }
145
-
146
- async function getConfiguration() {
147
- const environment = Environment.default;
148
-
149
- const storageService = environment.get(StorageService);
150
- console.log(`Storage location: ${storageService.location} (Directory)`);
151
- console.log(
152
- '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.',
153
- );
154
- const deviceStorage = (await storageService.open("device")).createContext("data");
155
-
156
- let defaultPasscode = 20202021;
157
- let defaultDiscriminator = 3840;
158
- let defaultPort = 5550;
159
-
160
- const devices = [];
161
- const numDevices = environment.vars.number("num") ?? 2;
162
- for (let i = 1; i <= numDevices; i++) {
163
- const isSocket = await deviceStorage.get(`isSocket${i}`, environment.vars.string(`type${i}`) === "socket");
164
- if (await deviceStorage.has(`isSocket${i}`)) {
165
- console.log(`Device type ${isSocket ? "socket" : "light"} found in storage. --type parameter is ignored.`);
166
- }
167
- const deviceName = `Matter ${environment.vars.string(`type${i}`) ?? "light"} device ${i}`;
168
- const vendorName = "matter-node.js";
169
- const passcode =
170
- environment.vars.number(`passcode${i}`) ?? (await deviceStorage.get(`passcode${i}`, defaultPasscode++));
171
- const discriminator =
172
- environment.vars.number(`discriminator${i}`) ??
173
- (await deviceStorage.get(`discriminator${i}`, defaultDiscriminator++));
174
- // product name / id and vendor id should match what is in the device certificate
175
- const vendorId = environment.vars.number(`vendorid${i}`) ?? (await deviceStorage.get(`vendorid${i}`, 0xfff1));
176
- const productName = `node-matter OnOff-Device ${i}`;
177
- const productId =
178
- environment.vars.number(`productid${i}`) ?? (await deviceStorage.get(`productid${i}`, 0x8000));
179
-
180
- const port = environment.vars.number(`port${i}`) ?? defaultPort++;
181
-
182
- const uniqueId =
183
- environment.vars.string(`uniqueid${i}`) ??
184
- (await deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`));
185
-
186
- // Persist basic data to keep them also on restart
187
- await deviceStorage.set(`passcode${i}`, passcode);
188
- await deviceStorage.set(`discriminator${i}`, discriminator);
189
- await deviceStorage.set(`vendorid${i}`, vendorId);
190
- await deviceStorage.set(`productid${i}`, productId);
191
- await deviceStorage.set(`isSocket${i}`, isSocket);
192
- await deviceStorage.set(`uniqueid${i}`, uniqueId);
193
-
194
- devices.push({
195
- isSocket,
196
- deviceName,
197
- vendorName,
198
- passcode,
199
- discriminator,
200
- vendorId,
201
- productName,
202
- productId,
203
- port,
204
- uniqueId,
205
- });
206
- }
207
-
208
- return devices;
209
- }
@@ -1,248 +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 simple Sensor Matter device as temperature or humidity device.
10
- * It can be used as CLI script and starting point for your own device node implementation.
11
- * This example is CJS conform and do not use top level await's.
12
- */
13
-
14
- /**
15
- * Import needed modules from @project-chip/matter-node.js
16
- */
17
- // Include this first to auto-register Crypto, Network and Time Node.js implementations
18
- import "@project-chip/matter-node.js";
19
-
20
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
21
- import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
22
- import { logEndpoint } from "@project-chip/matter.js/device";
23
- import { HumiditySensorDevice } from "@project-chip/matter.js/devices/HumiditySensorDevice";
24
- import { TemperatureSensorDevice } from "@project-chip/matter.js/devices/TemperatureSensorDevice";
25
- import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
26
- import { Environment, StorageService } from "@project-chip/matter.js/environment";
27
- import { ServerNode } from "@project-chip/matter.js/node";
28
- import { Time } from "@project-chip/matter.js/time";
29
- import { execSync } from "child_process";
30
-
31
- requireMinNodeVersion(16);
32
-
33
- async function main() {
34
- /** Initialize configuration values */
35
- const {
36
- isTemperature,
37
- interval,
38
- deviceName,
39
- vendorName,
40
- passcode,
41
- discriminator,
42
- vendorId,
43
- productName,
44
- productId,
45
- port,
46
- uniqueId,
47
- } = await getConfiguration();
48
-
49
- /**
50
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
51
- */
52
- const server = await ServerNode.create({
53
- // Required: Give the Node a unique ID which is used to store the state of this node
54
- id: uniqueId,
55
-
56
- // Provide Network relevant configuration like the port
57
- // Optional when operating only one device on a host, Default port is 5540
58
- network: {
59
- port,
60
- },
61
-
62
- // Provide Commissioning relevant settings
63
- // Optional for development/testing purposes
64
- commissioning: {
65
- passcode,
66
- discriminator,
67
- },
68
-
69
- // Provide Node announcement settings
70
- // Optional: If Ommitted some development defaults are used
71
- productDescription: {
72
- name: deviceName,
73
- deviceType: DeviceTypeId(
74
- isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,
75
- ),
76
- },
77
-
78
- // Provide defaults for the BasicInformation cluster on the Root endpoint
79
- // Optional: If Omitted some development defaults are used
80
- basicInformation: {
81
- vendorName,
82
- vendorId: VendorId(vendorId),
83
- nodeLabel: productName,
84
- productName,
85
- productLabel: productName,
86
- productId,
87
- serialNumber: `matterjs-${uniqueId}`,
88
- uniqueId,
89
- },
90
- });
91
-
92
- /**
93
- * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the
94
- * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a
95
- * unique ID to store the endpoint number for it in the storage to restore the device on restart.
96
- * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
97
- * to see how to customize the command handlers.
98
- */
99
- let endpoint: Endpoint<TemperatureSensorDevice | HumiditySensorDevice>;
100
- if (isTemperature) {
101
- endpoint = new Endpoint(TemperatureSensorDevice, {
102
- id: "tempsensor",
103
- temperatureMeasurement: {
104
- // Use this to initialize the measuredValue with the most uptodate value.
105
- // If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
106
- measuredValue: getIntValueFromCommandOrRandom("value"),
107
- },
108
- });
109
- } else {
110
- endpoint = new Endpoint(HumiditySensorDevice, {
111
- id: "humsensor",
112
- relativeHumidityMeasurement: {
113
- // Use this to initialize the measuredValue with the most uptodate value.
114
- // If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
115
- measuredValue: getIntValueFromCommandOrRandom("value", false),
116
- },
117
- });
118
- }
119
-
120
- await server.add(endpoint);
121
-
122
- /**
123
- * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
124
- */
125
- logEndpoint(EndpointServer.forEndpoint(server));
126
-
127
- const updateInterval = setInterval(() => {
128
- let setter: Promise<void>;
129
- if (isTemperature) {
130
- setter = endpoint.set({
131
- temperatureMeasurement: {
132
- measuredValue: getIntValueFromCommandOrRandom("value"),
133
- },
134
- });
135
- } else {
136
- setter = endpoint.set({
137
- relativeHumidityMeasurement: {
138
- measuredValue: getIntValueFromCommandOrRandom("value", false),
139
- },
140
- });
141
- }
142
- setter.catch(error => console.error("Error updating measured value:", error));
143
- }, interval * 1000);
144
-
145
- // Cleanup our update interval when node goes offline
146
- server.lifecycle.offline.on(() => clearTimeout(updateInterval));
147
-
148
- /**
149
- * In order to start the node and announce it into the network we use the run method which resolves when the node goes
150
- * offline again because we do not need anything more here. See the Full example for other starting options.
151
- * The QR Code is printed automatically.
152
- */
153
- await server.run();
154
- }
155
-
156
- main().catch(error => console.error(error));
157
-
158
- /*********************************************************************************************************
159
- * Convenience Methods
160
- *********************************************************************************************************/
161
-
162
- /** Defined a shell command from an environment variable and execute it and log the response. */
163
-
164
- function getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {
165
- const script = Environment.default.vars.string(scriptParamName);
166
- if (script === undefined) {
167
- if (!allowNegativeValues) return Math.round(Math.random() * 100);
168
- return (Math.round(Math.random() * 100) - 50) * 100;
169
- }
170
- let result = execSync(script).toString().trim();
171
- if ((result.startsWith("'") && result.endsWith("'")) || (result.startsWith('"') && result.endsWith('"')))
172
- result = result.slice(1, -1);
173
- console.log(`Command result: ${result}`);
174
- let value = Math.round(parseFloat(result));
175
- if (!allowNegativeValues && value < 0) value = 0;
176
- return value;
177
- }
178
-
179
- async function getConfiguration() {
180
- /**
181
- * Collect all needed data
182
- *
183
- * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.
184
- *
185
- * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
186
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
187
- * (so maybe better not do it ;-)).
188
- */
189
- const environment = Environment.default;
190
-
191
- const storageService = environment.get(StorageService);
192
- console.log(`Storage location: ${storageService.location} (Directory)`);
193
- console.log(
194
- '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.',
195
- );
196
- const deviceStorage = (await storageService.open("device")).createContext("data");
197
-
198
- const isTemperature = await deviceStorage.get("isTemperature", environment.vars.get("type") !== "humidity");
199
- if (await deviceStorage.has("isTemperature")) {
200
- console.log(
201
- `Device type ${isTemperature ? "temperature" : "humidity"} found in storage. --type parameter is ignored.`,
202
- );
203
- }
204
- let interval = environment.vars.number("interval") ?? (await deviceStorage.get("interval", 60));
205
- if (interval < 1) {
206
- console.log(`Invalid Interval ${interval}, set to 60s`);
207
- interval = 60;
208
- }
209
-
210
- const deviceName = "Matter test device";
211
- const vendorName = "matter-node.js";
212
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
213
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
214
- // product name / id and vendor id should match what is in the device certificate
215
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
216
- const productName = `node-matter OnOff ${isTemperature ? "Temperature" : "Humidity"}`;
217
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
218
-
219
- const port = environment.vars.number("port") ?? 5540;
220
-
221
- const uniqueId =
222
- environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
223
-
224
- // Persist basic data to keep them also on restart
225
- await deviceStorage.set({
226
- passcode,
227
- discriminator,
228
- vendorid: vendorId,
229
- productid: productId,
230
- interval,
231
- isTemperature,
232
- uniqueid: uniqueId,
233
- });
234
-
235
- return {
236
- isTemperature,
237
- interval,
238
- deviceName,
239
- vendorName,
240
- passcode,
241
- discriminator,
242
- vendorId,
243
- productName,
244
- productId,
245
- port,
246
- uniqueId,
247
- };
248
- }
@@ -1,153 +0,0 @@
1
- /**
2
- * @license
3
- * Copyright 2022-2024 Matter.js Authors
4
- * SPDX-License-Identifier: Apache-2.0
5
- */
6
-
7
- import { GeneralCommissioningBehavior } from "@project-chip/matter.js/behavior/definitions/general-commissioning";
8
- import { NetworkCommissioningBehavior } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
9
- import { NetworkCommissioning } from "@project-chip/matter.js/cluster";
10
- import { Logger } from "@project-chip/matter.js/log";
11
- import { ByteArray } from "@project-chip/matter.js/util";
12
-
13
- const firstNetworkId = new ByteArray(32);
14
-
15
- /**
16
- * This represents a Dummy version of a Thread Network Commissioning Cluster Server without real thread related logic, beside
17
- * returning some values provided as CLI parameters. This dummy implementation is only there for tests/as showcase for BLE
18
- * commissioning of a device.
19
- */
20
- export class DummyThreadNetworkCommissioningServer extends NetworkCommissioningBehavior.with(
21
- NetworkCommissioning.Feature.ThreadNetworkInterface,
22
- ) {
23
- override scanNetworks({
24
- breadcrumb,
25
- }: NetworkCommissioning.ScanNetworksRequest): NetworkCommissioning.ScanNetworksResponse {
26
- console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${breadcrumb}`);
27
-
28
- // Simulate successful scan
29
- if (breadcrumb !== undefined) {
30
- const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
31
- generalCommissioningCluster.state.breadcrumb = breadcrumb;
32
- }
33
-
34
- const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
35
- this.state.lastNetworkingStatus = networkingStatus;
36
-
37
- const threadScanResults = [
38
- {
39
- panId: this.endpoint.env.vars.number("ble.thread.panId"),
40
- extendedPanId: BigInt(this.endpoint.env.vars.string("ble.thread.extendedPanId")),
41
- networkName: this.endpoint.env.vars.string("ble.thread.networkName"),
42
- channel: this.endpoint.env.vars.number("ble.thread.channel"),
43
- version: 130,
44
- extendedAddress: ByteArray.fromString(
45
- (this.endpoint.env.vars.string("ble.thread.address") ?? "000000000000").toLowerCase(),
46
- ),
47
- rssi: -50,
48
- lqi: 50,
49
- },
50
- ];
51
- console.log(Logger.toJSON(threadScanResults));
52
-
53
- return {
54
- networkingStatus,
55
- threadScanResults,
56
- };
57
- }
58
-
59
- override addOrUpdateThreadNetwork({
60
- operationalDataset,
61
- breadcrumb,
62
- }: NetworkCommissioning.AddOrUpdateThreadNetworkRequest) {
63
- console.log(
64
- `---> addOrUpdateThreadNetwork called on NetworkCommissioning cluster: ${operationalDataset.toHex()} ${breadcrumb}`,
65
- );
66
-
67
- this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
68
-
69
- // Simulate successful add or update
70
- if (breadcrumb !== undefined) {
71
- const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
72
- generalCommissioningCluster.state.breadcrumb = breadcrumb;
73
- }
74
-
75
- const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
76
- this.state.lastNetworkingStatus = networkingStatus;
77
- this.state.lastNetworkId = firstNetworkId;
78
-
79
- return {
80
- networkingStatus,
81
- networkIndex: 0,
82
- };
83
- }
84
-
85
- override removeNetwork({ networkId, breadcrumb }: NetworkCommissioning.RemoveNetworkRequest) {
86
- console.log(`---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
87
-
88
- this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
89
-
90
- // Simulate successful add or update
91
- if (breadcrumb !== undefined) {
92
- const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
93
- generalCommissioningCluster.state.breadcrumb = breadcrumb;
94
- }
95
-
96
- const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
97
- this.state.lastNetworkingStatus = networkingStatus;
98
- this.state.lastNetworkId = firstNetworkId;
99
-
100
- return {
101
- networkingStatus,
102
- networkIndex: 0,
103
- };
104
- }
105
-
106
- override async connectNetwork({ networkId, breadcrumb }: NetworkCommissioning.ConnectNetworkRequest) {
107
- console.log(`---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
108
-
109
- this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
110
-
111
- // Simulate successful connection
112
- if (breadcrumb !== undefined) {
113
- const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
114
- generalCommissioningCluster.state.breadcrumb = breadcrumb;
115
- }
116
-
117
- this.state.networks[0].connected = true;
118
-
119
- const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
120
- this.state.lastNetworkingStatus = networkingStatus;
121
- this.state.lastNetworkId = firstNetworkId;
122
- this.state.lastConnectErrorValue = null;
123
-
124
- // Announce operational in IP network
125
- const device = this.session.context;
126
- await device.startAnnouncement();
127
-
128
- return {
129
- networkingStatus,
130
- errorValue: null,
131
- };
132
- }
133
-
134
- override reorderNetwork({ networkId, networkIndex, breadcrumb }: NetworkCommissioning.ReorderNetworkRequest) {
135
- console.log(
136
- `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`,
137
- );
138
-
139
- // Simulate successful connection
140
- if (breadcrumb !== undefined) {
141
- const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
142
- generalCommissioningCluster.state.breadcrumb = breadcrumb;
143
- }
144
-
145
- const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
146
- this.state.lastNetworkingStatus = networkingStatus;
147
-
148
- return {
149
- networkingStatus,
150
- networkIndex: 0,
151
- };
152
- }
153
- }