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