@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,318 +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 Matter controller to pair with a device and interfact with it.
10
- * It can be used as CLI script, but is more thought as a starting point for your own controller implementation
11
- * because you need to adjust the code in any way depending on your use case.
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
- // Include this first to auto-register Crypto, Network and Time Node.js implementations
19
- import "@project-chip/matter-node.js";
20
-
21
- import { BleNode } from "@project-chip/matter-node-ble.js/ble";
22
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
23
- import { CommissioningController, NodeCommissioningOptions } from "@project-chip/matter.js";
24
- import { Ble } from "@project-chip/matter.js/ble";
25
- import {
26
- BasicInformationCluster,
27
- ClusterClientObj,
28
- DescriptorCluster,
29
- GeneralCommissioning,
30
- OnOff,
31
- } from "@project-chip/matter.js/cluster";
32
- import { NodeId } from "@project-chip/matter.js/datatype";
33
- import { NodeStateInformation } from "@project-chip/matter.js/device";
34
- import { Environment, StorageService } from "@project-chip/matter.js/environment";
35
- import { Logger } from "@project-chip/matter.js/log";
36
- import { CommissioningOptions } from "@project-chip/matter.js/protocol";
37
- import { ManualPairingCodeCodec } from "@project-chip/matter.js/schema";
38
- import { Time } from "@project-chip/matter.js/time";
39
- import { singleton } from "@project-chip/matter.js/util";
40
-
41
- const logger = Logger.get("Controller");
42
-
43
- requireMinNodeVersion(16);
44
-
45
- const environment = Environment.default;
46
-
47
- if (environment.vars.get("ble")) {
48
- // Initialize Ble
49
- Ble.get = singleton(
50
- () =>
51
- new BleNode({
52
- hciId: environment.vars.number("ble-hci-id"),
53
- }),
54
- );
55
- }
56
-
57
- const storageService = environment.get(StorageService);
58
-
59
- console.log(`Storage location: ${storageService.location} (Directory)`);
60
- logger.info(
61
- '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.',
62
- );
63
-
64
- class ControllerNode {
65
- async start() {
66
- logger.info(`node-matter Controller started`);
67
-
68
- /**
69
- * Collect all needed data
70
- *
71
- * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data
72
- * come from.
73
- *
74
- * Note: This example also uses the initialized storage system to store the device parameter data for convenience
75
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts
76
- * (so maybe better not ;-)).
77
- */
78
-
79
- const controllerStorage = (await storageService.open("controller")).createContext("data");
80
- const ip = (await controllerStorage.has("ip"))
81
- ? await controllerStorage.get<string>("ip")
82
- : environment.vars.string("ip");
83
- const port = (await controllerStorage.has("port"))
84
- ? await controllerStorage.get<number>("port")
85
- : environment.vars.number("port");
86
- const uniqueId = (await controllerStorage.has("uniqueid"))
87
- ? await controllerStorage.get<string>("uniqueid")
88
- : (environment.vars.string("uniqueid") ?? Time.nowMs().toString());
89
- await controllerStorage.set("uniqueid", uniqueId);
90
-
91
- const pairingCode = environment.vars.string("pairingcode");
92
- let longDiscriminator, setupPin, shortDiscriminator;
93
- if (pairingCode !== undefined) {
94
- const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
95
- shortDiscriminator = pairingCodeCodec.shortDiscriminator;
96
- longDiscriminator = undefined;
97
- setupPin = pairingCodeCodec.passcode;
98
- logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
99
- } else {
100
- longDiscriminator =
101
- environment.vars.number("longDiscriminator") ??
102
- (await controllerStorage.get("longDiscriminator", 3840));
103
- if (longDiscriminator > 4095) throw new Error("Discriminator value must be less than 4096");
104
- setupPin = environment.vars.number("pin") ?? (await controllerStorage.get("pin", 20202021));
105
- }
106
- if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {
107
- throw new Error(
108
- "Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode",
109
- );
110
- }
111
-
112
- // Collect commissioning options from commandline parameters
113
- const commissioningOptions: CommissioningOptions = {
114
- regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
115
- regulatoryCountryCode: "XX",
116
- };
117
-
118
- let ble = false;
119
- if (environment.vars.get("ble")) {
120
- ble = true;
121
- const wifiSsid = environment.vars.string("ble-wifi-ssid");
122
- const wifiCredentials = environment.vars.string("ble-wifi-credentials");
123
- const threadNetworkName = environment.vars.string("ble-thread-networkname");
124
- const threadOperationalDataset = environment.vars.string("ble-thread-operationaldataset");
125
- if (wifiSsid !== undefined && wifiCredentials !== undefined) {
126
- logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);
127
- commissioningOptions.wifiNetwork = {
128
- wifiSsid: wifiSsid,
129
- wifiCredentials: wifiCredentials,
130
- };
131
- }
132
- if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {
133
- logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);
134
- commissioningOptions.threadNetwork = {
135
- networkName: threadNetworkName,
136
- operationalDataset: threadOperationalDataset,
137
- };
138
- }
139
- }
140
-
141
- /**
142
- * Create Matter Server and Controller Node
143
- *
144
- * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a
145
- * CommissioningController to it and add the just created device instance to it.
146
- * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol
147
- * and initializes deice specific certificates and such.
148
- *
149
- * The below logic also adds command handlers for commands of clusters that normally are handled internally
150
- * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands
151
- * are called.
152
- */
153
-
154
- const commissioningController = new CommissioningController({
155
- environment: {
156
- environment,
157
- id: uniqueId,
158
- },
159
- autoConnect: false,
160
- });
161
-
162
- /**
163
- * Start the Matter Server
164
- *
165
- * After everything was plugged together we can start the server. When not delayed announcement is set for the
166
- * CommissioningServer node then this command also starts the announcement of the device into the network.
167
- */
168
- await commissioningController.start();
169
-
170
- if (!commissioningController.isCommissioned()) {
171
- const options = {
172
- commissioning: commissioningOptions,
173
- discovery: {
174
- knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: "udp" } : undefined,
175
- identifierData:
176
- longDiscriminator !== undefined
177
- ? { longDiscriminator }
178
- : shortDiscriminator !== undefined
179
- ? { shortDiscriminator }
180
- : {},
181
- discoveryCapabilities: {
182
- ble,
183
- },
184
- },
185
- passcode: setupPin,
186
- } as NodeCommissioningOptions;
187
- logger.info(`Commissioning ... ${Logger.toJSON(options)}`);
188
- const nodeId = await commissioningController.commissionNode(options);
189
-
190
- console.log(`Commissioning successfully done with nodeId ${nodeId}`);
191
- }
192
-
193
- /**
194
- * TBD
195
- */
196
- try {
197
- const nodes = commissioningController.getCommissionedNodes();
198
- console.log("Found commissioned nodes:", Logger.toJSON(nodes));
199
-
200
- const nodeId = NodeId(environment.vars.number("nodeid") ?? nodes[0]);
201
- if (!nodes.includes(nodeId)) {
202
- throw new Error(`Node ${nodeId} not found in commissioned nodes`);
203
- }
204
-
205
- const node = await commissioningController.connectNode(nodeId, {
206
- attributeChangedCallback: (
207
- peerNodeId,
208
- { path: { nodeId, clusterId, endpointId, attributeName }, value },
209
- ) =>
210
- console.log(
211
- `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(
212
- value,
213
- )}`,
214
- ),
215
- eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>
216
- console.log(
217
- `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(
218
- events,
219
- )}`,
220
- ),
221
- stateInformationCallback: (peerNodeId, info) => {
222
- switch (info) {
223
- case NodeStateInformation.Connected:
224
- console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
225
- break;
226
- case NodeStateInformation.Disconnected:
227
- console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
228
- break;
229
- case NodeStateInformation.Reconnecting:
230
- console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
231
- break;
232
- case NodeStateInformation.WaitingForDeviceDiscovery:
233
- console.log(
234
- `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,
235
- );
236
- break;
237
- case NodeStateInformation.StructureChanged:
238
- console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
239
- break;
240
- case NodeStateInformation.Decommissioned:
241
- console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
242
- break;
243
- }
244
- },
245
- });
246
-
247
- // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!
248
- // It is provided to proof the concept
249
-
250
- node.logStructure();
251
-
252
- // Example to initialize a ClusterClient and access concrete fields as API methods
253
- const descriptor = node.getRootClusterClient(DescriptorCluster);
254
- if (descriptor !== undefined) {
255
- console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way
256
- console.log(await descriptor.getServerListAttribute()); // or more convenient that way
257
- } else {
258
- console.log("No Descriptor Cluster found. This should never happen!");
259
- }
260
-
261
- // Example to subscribe to a field and get the value
262
- const info = node.getRootClusterClient(BasicInformationCluster);
263
- if (info !== undefined) {
264
- console.log(await info.getProductNameAttribute()); // This call is executed remotely
265
- //console.log(await info.subscribeProductNameAttribute(value => console.log("productName", value), 5, 30));
266
- //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!
267
- } else {
268
- console.log("No BasicInformation Cluster found. This should never happen!");
269
- }
270
-
271
- // Example to get all Attributes of the commissioned node: */*/*
272
- //const attributesAll = await interactionClient.getAllAttributes();
273
- //console.log("Attributes-All:", Logger.toJSON(attributesAll));
274
-
275
- // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*
276
- //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);
277
- //console.log("Attributes-Descriptor:", JSON.stringify(attributesAllDescriptor, null, 2));
278
-
279
- // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*
280
- //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);
281
- //console.log("Attributes-BasicInformation:", JSON.stringify(attributesBasicInformation, null, 2));
282
-
283
- const devices = node.getDevices();
284
- if (devices[0] && devices[0].number === 1) {
285
- // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*
286
- //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {
287
- // console.log("Subscribe-All Data:", Logger.toJSON(data));
288
- //});
289
-
290
- const onOff: ClusterClientObj<OnOff.Complete> | undefined = devices[0].getClusterClient(OnOff.Complete);
291
- if (onOff !== undefined) {
292
- let onOffStatus = await onOff.getOnOffAttribute();
293
- console.log("initial onOffStatus", onOffStatus);
294
-
295
- onOff.addOnOffAttributeListener(value => {
296
- console.log("subscription onOffStatus", value);
297
- onOffStatus = value;
298
- });
299
- // read data every minute to keep up the connection to show the subscription is working
300
- setInterval(() => {
301
- onOff
302
- .toggle()
303
- .then(() => {
304
- onOffStatus = !onOffStatus;
305
- console.log("onOffStatus", onOffStatus);
306
- })
307
- .catch(error => logger.error(error));
308
- }, 60000);
309
- }
310
- }
311
- } finally {
312
- //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed
313
- setTimeout(() => process.exit(0), 1000000);
314
- }
315
- }
316
- }
317
-
318
- new ControllerNode().start().catch(error => logger.error(error));
@@ -1,202 +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 on-off Matter device as a light or as a socket.
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 { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
24
- import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
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
- isSocket,
37
- deviceName,
38
- vendorName,
39
- passcode,
40
- discriminator,
41
- vendorId,
42
- productName,
43
- productId,
44
- port,
45
- uniqueId,
46
- } = await getConfiguration();
47
-
48
- /**
49
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
50
- */
51
- const server = await ServerNode.create({
52
- // Required: Give the Node a unique ID which is used to store the state of this node
53
- id: uniqueId,
54
-
55
- // Provide Network relevant configuration like the port
56
- // Optional when operating only one device on a host, Default port is 5540
57
- network: {
58
- port,
59
- },
60
-
61
- // Provide Commissioning relevant settings
62
- // Optional for development/testing purposes
63
- commissioning: {
64
- passcode,
65
- discriminator,
66
- },
67
-
68
- // Provide Node announcement settings
69
- // Optional: If Ommitted some development defaults are used
70
- productDescription: {
71
- name: deviceName,
72
- deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),
73
- },
74
-
75
- // Provide defaults for the BasicInformation cluster on the Root endpoint
76
- // Optional: If Omitted some development defaults are used
77
- basicInformation: {
78
- vendorName,
79
- vendorId: VendorId(vendorId),
80
- nodeLabel: productName,
81
- productName,
82
- productLabel: productName,
83
- productId,
84
- serialNumber: `matterjs-${uniqueId}`,
85
- uniqueId,
86
- },
87
- });
88
-
89
- /**
90
- * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the
91
- * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a
92
- * unique ID to store the endpoint number for it in the storage to restore the device on restart.
93
- * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
94
- * to see how to customize the command handlers.
95
- */
96
- const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: "onoff" });
97
- await server.add(endpoint);
98
-
99
- /**
100
- * Register state change handlers and events of the node for identify and onoff states to react to the commands.
101
- * If the code in these change handlers fail then the change is also rolled back and not executed and an error is
102
- * reported back to the controller.
103
- */
104
- endpoint.events.identify.startIdentifying.on(() => {
105
- console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
106
- });
107
-
108
- endpoint.events.identify.stopIdentifying.on(() => {
109
- console.log(`Stop identify logic ...`);
110
- });
111
-
112
- endpoint.events.onOff.onOff$Changed.on(value => {
113
- executeCommand(value ? "on" : "off");
114
- console.log(`OnOff is now ${value ? "ON" : "OFF"}`);
115
- });
116
-
117
- /**
118
- * Log the endpoint structure for debugging reasons and to allow to verify anything is correct
119
- */
120
- logEndpoint(EndpointServer.forEndpoint(server));
121
-
122
- /**
123
- * In order to start the node and announce it into the network we use the run method which resolves when the node goes
124
- * offline again because we do not need anything more here. See the Full example for other starting options.
125
- * The QR Code is printed automatically.
126
- */
127
- await server.run();
128
- }
129
-
130
- main().catch(error => console.error(error));
131
-
132
- /*********************************************************************************************************
133
- * Convenience Methods
134
- *********************************************************************************************************/
135
-
136
- /** Defined a shell command from an environment variable and execute it and log the response. */
137
- function executeCommand(scriptParamName: string) {
138
- const script = Environment.default.vars.string(scriptParamName);
139
- if (script === undefined) return undefined;
140
- console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
141
- }
142
-
143
- async function getConfiguration() {
144
- /**
145
- * Collect all needed data
146
- *
147
- * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.
148
- *
149
- * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
150
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
151
- * (so maybe better not do it ;-)).
152
- */
153
- const environment = Environment.default;
154
-
155
- const storageService = environment.get(StorageService);
156
- console.log(`Storage location: ${storageService.location} (Directory)`);
157
- console.log(
158
- '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.',
159
- );
160
- const deviceStorage = (await storageService.open("device")).createContext("data");
161
-
162
- const isSocket = await deviceStorage.get("isSocket", environment.vars.get("type") === "socket");
163
- if (await deviceStorage.has("isSocket")) {
164
- console.log(`Device type ${isSocket ? "socket" : "light"} found in storage. --type parameter is ignored.`);
165
- }
166
- const deviceName = "Matter test device";
167
- const vendorName = "matter-node.js";
168
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
169
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
170
- // product name / id and vendor id should match what is in the device certificate
171
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
172
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
173
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
174
-
175
- const port = environment.vars.number("port") ?? 5540;
176
-
177
- const uniqueId =
178
- environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs())).toString();
179
-
180
- // Persist basic data to keep them also on restart
181
- await deviceStorage.set({
182
- passcode,
183
- discriminator,
184
- vendorid: vendorId,
185
- productid: productId,
186
- isSocket,
187
- uniqueid: uniqueId,
188
- });
189
-
190
- return {
191
- isSocket,
192
- deviceName,
193
- vendorName,
194
- passcode,
195
- discriminator,
196
- vendorId,
197
- productName,
198
- productId,
199
- port,
200
- uniqueId,
201
- };
202
- }