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