@project-chip/matter-node.js-examples 0.11.0-alpha.0-20240911-db8f7c80 → 0.11.0-alpha.0-20241007-547af42a8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (76) hide show
  1. package/README.md +3 -271
  2. package/dist/esm/examples/BridgedDevicesNodeLegacy.js +5 -4
  3. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +1 -2
  4. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +4 -3
  5. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +1 -2
  6. package/dist/esm/examples/ControllerNodeLegacy.js +7 -6
  7. package/dist/esm/examples/ControllerNodeLegacy.js.map +1 -2
  8. package/dist/esm/examples/DeviceNodeFullLegacy.js +8 -6
  9. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +1 -2
  10. package/dist/esm/examples/LegacyStorageConverter.js +2 -2
  11. package/dist/esm/examples/LegacyStorageConverter.js.map +0 -1
  12. package/dist/esm/examples/MultiDeviceNodeLegacy.js +5 -4
  13. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +1 -2
  14. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js +7 -6
  15. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +1 -2
  16. package/dist/esm/package.json +3 -0
  17. package/package.json +16 -37
  18. package/src/examples/BridgedDevicesNodeLegacy.ts +4 -3
  19. package/src/examples/ComposedDeviceNodeLegacy.ts +4 -3
  20. package/src/examples/ControllerNodeLegacy.ts +6 -5
  21. package/src/examples/DeviceNodeFullLegacy.ts +7 -5
  22. package/src/examples/LegacyStorageConverter.ts +2 -2
  23. package/src/examples/MultiDeviceNodeLegacy.ts +4 -4
  24. package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +7 -6
  25. package/src/tsconfig.json +13 -13
  26. package/dist/esm/examples/BridgedDevicesNode.js +0 -144
  27. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  28. package/dist/esm/examples/ComposedDeviceNode.js +0 -123
  29. package/dist/esm/examples/ComposedDeviceNode.js.map +0 -7
  30. package/dist/esm/examples/ControllerNode.js +0 -194
  31. package/dist/esm/examples/ControllerNode.js.map +0 -7
  32. package/dist/esm/examples/DeviceNode.js +0 -127
  33. package/dist/esm/examples/DeviceNode.js.map +0 -7
  34. package/dist/esm/examples/DeviceNodeFull.js +0 -253
  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 -140
  41. package/dist/esm/examples/MultiDeviceNode.js.map +0 -7
  42. package/dist/esm/examples/SensorDeviceNode.js +0 -175
  43. package/dist/esm/examples/SensorDeviceNode.js.map +0 -7
  44. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +0 -121
  45. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +0 -7
  46. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +0 -121
  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 -259
  61. package/src/examples/ComposedDeviceNode.ts +0 -196
  62. package/src/examples/ControllerNode.ts +0 -314
  63. package/src/examples/DeviceNode.ts +0 -201
  64. package/src/examples/DeviceNodeFull.ts +0 -440
  65. package/src/examples/IlluminatedRollerShade.ts +0 -96
  66. package/src/examples/LightDevice.ts +0 -61
  67. package/src/examples/MultiDeviceNode.ts +0 -208
  68. package/src/examples/SensorDeviceNode.ts +0 -247
  69. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +0 -156
  70. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +0 -154
  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,201 +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 { requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
19
-
20
- import { Time } from "@project-chip/matter.js-general";
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 { execSync } from "child_process";
29
-
30
- requireMinNodeVersion(16);
31
-
32
- async function main() {
33
- /** Initialize configuration values */
34
- const {
35
- isSocket,
36
- deviceName,
37
- vendorName,
38
- passcode,
39
- discriminator,
40
- vendorId,
41
- productName,
42
- productId,
43
- port,
44
- uniqueId,
45
- } = await getConfiguration();
46
-
47
- /**
48
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
49
- */
50
- const server = await ServerNode.create({
51
- // Required: Give the Node a unique ID which is used to store the state of this node
52
- id: uniqueId,
53
-
54
- // Provide Network relevant configuration like the port
55
- // Optional when operating only one device on a host, Default port is 5540
56
- network: {
57
- port,
58
- },
59
-
60
- // Provide Commissioning relevant settings
61
- // Optional for development/testing purposes
62
- commissioning: {
63
- passcode,
64
- discriminator,
65
- },
66
-
67
- // Provide Node announcement settings
68
- // Optional: If Ommitted some development defaults are used
69
- productDescription: {
70
- name: deviceName,
71
- deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),
72
- },
73
-
74
- // Provide defaults for the BasicInformation cluster on the Root endpoint
75
- // Optional: If Omitted some development defaults are used
76
- basicInformation: {
77
- vendorName,
78
- vendorId: VendorId(vendorId),
79
- nodeLabel: productName,
80
- productName,
81
- productLabel: productName,
82
- productId,
83
- serialNumber: `matterjs-${uniqueId}`,
84
- uniqueId,
85
- },
86
- });
87
-
88
- /**
89
- * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the
90
- * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a
91
- * unique ID to store the endpoint number for it in the storage to restore the device on restart.
92
- * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example
93
- * to see how to customize the command handlers.
94
- */
95
- const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: "onoff" });
96
- await server.add(endpoint);
97
-
98
- /**
99
- * Register state change handlers and events 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, ideally blink a light every 0.5s ...`);
105
- });
106
-
107
- endpoint.events.identify.stopIdentifying.on(() => {
108
- console.log(`Stop identify logic ...`);
109
- });
110
-
111
- endpoint.events.onOff.onOff$Changed.on(value => {
112
- executeCommand(value ? "on" : "off");
113
- console.log(`OnOff 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
- /**
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.run();
127
- }
128
-
129
- main().catch(error => console.error(error));
130
-
131
- /*********************************************************************************************************
132
- * Convenience Methods
133
- *********************************************************************************************************/
134
-
135
- /** Defined a shell command from an environment variable and execute it and log the response. */
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
- /**
144
- * Collect all needed data
145
- *
146
- * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.
147
- *
148
- * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
149
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
150
- * (so maybe better not do it ;-)).
151
- */
152
- const environment = Environment.default;
153
-
154
- const storageService = environment.get(StorageService);
155
- console.log(`Storage location: ${storageService.location} (Directory)`);
156
- console.log(
157
- '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.',
158
- );
159
- const deviceStorage = (await storageService.open("device")).createContext("data");
160
-
161
- const isSocket = await deviceStorage.get("isSocket", environment.vars.get("type") === "socket");
162
- if (await deviceStorage.has("isSocket")) {
163
- console.log(`Device type ${isSocket ? "socket" : "light"} found in storage. --type parameter is ignored.`);
164
- }
165
- const deviceName = "Matter test device";
166
- const vendorName = "matter-node.js";
167
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
168
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
169
- // product name / id and vendor id should match what is in the device certificate
170
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
171
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
172
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
173
-
174
- const port = environment.vars.number("port") ?? 5540;
175
-
176
- const uniqueId =
177
- environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs())).toString();
178
-
179
- // Persist basic data to keep them also on restart
180
- await deviceStorage.set({
181
- passcode,
182
- discriminator,
183
- vendorid: vendorId,
184
- productid: productId,
185
- isSocket,
186
- uniqueid: uniqueId,
187
- });
188
-
189
- return {
190
- isSocket,
191
- deviceName,
192
- vendorName,
193
- passcode,
194
- discriminator,
195
- vendorId,
196
- productName,
197
- productId,
198
- port,
199
- uniqueId,
200
- };
201
- }
@@ -1,440 +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 is not optimized for simplicity, but to show all the advanced use cases for matter.js.
10
- * If you want to see a simple minimalistic and more standard example please look at DeviceNode.ts or the other examples.
11
- *
12
- * This example shows how to create a simple on-off Matter device as a light or as a socket.
13
- * It can be used as CLI script and starting point for your own device node implementation.
14
- * Additional to this it shows the following:
15
- * * How to modify the existing clusters on Root and also Device Endpoints
16
- * * How to add own Cluster implementations for Standard clusters
17
- * * How to add a custom Cluster to an Endpoint
18
- * * Which events are available to get status information from the Node aon commissioning and session/subscription changes
19
- * * How to get cluster state values
20
- * * How to set one or multiple state values in a transaction.
21
- */
22
-
23
- /**
24
- * Import needed modules from @project-chip/matter-node.js
25
- */
26
- // Include this first to auto-register Crypto, Network and Time Node.js implementations
27
- import { createFileLogger, requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
28
-
29
- import { BleNode } from "@project-chip/matter-node-ble.js/ble";
30
- import { LogLevel, Logger, Time, logLevelFromString, singleton } from "@project-chip/matter.js-general";
31
- import { NetworkCommissioningServer } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
32
- import { OnOffServer } from "@project-chip/matter.js/behavior/definitions/on-off";
33
- import { Ble } from "@project-chip/matter.js/ble";
34
- import { GeneralDiagnostics, NetworkCommissioning } from "@project-chip/matter.js/cluster";
35
- import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
36
- import { logEndpoint } from "@project-chip/matter.js/device";
37
- import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
38
- import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
39
- import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
40
- import { RootRequirements } from "@project-chip/matter.js/endpoint/definitions";
41
- import { Environment, StorageService } from "@project-chip/matter.js/environment";
42
- import { FabricAction } from "@project-chip/matter.js/fabric";
43
- import { ServerNode } from "@project-chip/matter.js/node";
44
- import { QrCode } from "@project-chip/matter.js/schema";
45
- import { execSync } from "child_process";
46
- import { DummyThreadNetworkCommissioningServer } from "./cluster/DummyThreadNetworkCommissioningServer.js";
47
- import { DummyWifiNetworkCommissioningServer } from "./cluster/DummyWifiNetworkCommissioningServer.js";
48
- import {
49
- MyFancyCommandRequest,
50
- MyFancyCommandResponse,
51
- MyFancyOwnFunctionalityBehavior,
52
- } from "./cluster/MyFancyOwnFunctionality.js";
53
-
54
- /**
55
- * The following code brings some convenience to the CLI script. It allows to set the log level and format via
56
- * command line parameters. It also initializes the BLE stack if the `--ble` parameter is present.
57
- * Some of these parameters can also be replaced by generically accepted parameters or even environment variables. See the comments in the relevant places for information.
58
- * When using this code as basis for your own device node implementation, you can remove this part or hard code it.
59
- */
60
-
61
- requireMinNodeVersion(16);
62
-
63
- // To configure Logging use
64
- // * "--log-level" or environment variable "MATTER_LOG_LEVEL" or "environment.vars.set('log.level', Level.DEBUG)"
65
- // Allowed values are: Level.FATAL, Level.ERROR, Level.WARN, Level.NOTICE, Level.INFO, Level.DEBUG
66
- // * "--log-format" or environment variable "MATTER_LOG_FORMAT" or "environment.vars.set('log.format', Format.PLAIN)"
67
- // Allowed values are: Format.PLAIN, Format.HTML, Format.ANSI,
68
-
69
- const environment = Environment.default;
70
-
71
- // Alternatively "--ble-enable" or environment variable "BLE_ENABLED"
72
- // Alternatively "--ble-hciId" or environment variable "BLE_HCIID"
73
- if (environment.vars.get("ble.enable")) {
74
- // Initialize Ble
75
- Ble.get = singleton(
76
- () =>
77
- new BleNode({
78
- hciId: environment.vars.number("ble.hciId"),
79
- }),
80
- );
81
- }
82
-
83
- function executeCommand(scriptParamName: string) {
84
- const script = environment.vars.string(scriptParamName);
85
- if (script === undefined) return undefined;
86
- console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
87
- }
88
-
89
- /**
90
- * Collect all needed data
91
- *
92
- * This block collects all needed data from cli or storage. Replace this with where ever your data come from.
93
- *
94
- * Note: This example uses the matter.js process storage system to store the device parameter data for convenience
95
- * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts
96
- * (so maybe better not do it ;-)).
97
- */
98
-
99
- const logFile = environment.vars.string("logfile.filename");
100
- if (logFile !== undefined) {
101
- Logger.addLogger("filelogger", await createFileLogger(logFile), {
102
- defaultLogLevel: logLevelFromString(environment.vars.string("logfile.loglevel")) ?? LogLevel.DEBUG,
103
- });
104
- }
105
-
106
- const storageService = environment.get(StorageService);
107
- console.log(`Storage location: ${storageService.location} (Directory)`);
108
- console.log(
109
- '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.',
110
- );
111
-
112
- const deviceStorage = (await storageService.open("device")).createContext("data");
113
-
114
- if (await deviceStorage.has("isSocket")) {
115
- console.log("Device type found in storage. --type parameter is ignored.");
116
- }
117
- const isSocket = await deviceStorage.get("isSocket", environment.vars.string("type") === "socket");
118
- const deviceName = "Matter test device";
119
- const vendorName = "matter-node.js";
120
- const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
121
- const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
122
- // product name / id and vendor id should match what is in the device certificate
123
- const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
124
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
125
- const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
126
-
127
- const port = environment.vars.number("port") ?? 5540;
128
-
129
- const uniqueId = environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
130
-
131
- await deviceStorage.set({
132
- passcode,
133
- discriminator,
134
- vendorid: vendorId,
135
- productid: productId,
136
- isSocket,
137
- uniqueid: uniqueId,
138
- });
139
-
140
- // Matter exposes functionality in groups called "clusters". For this example device we override the matter.js "On/Off"
141
- // cluster implementation to print status to the console.
142
- class OnOffShellExecServer extends OnOffServer {
143
- // Intercept the "on" command to the Matter On/Off cluster to print a log message.
144
- override async on() {
145
- executeCommand("on");
146
- await super.on();
147
- }
148
-
149
- // This is the functional inverse of on() above.
150
- //
151
- // For demonstration purposes we update state ourselves rather than deferring to matter.js's default "off" handler
152
- // via super.off().
153
- override async off() {
154
- executeCommand("off");
155
- this.state.onOff = false;
156
- }
157
-
158
- // Use event handlers to log on/off state reactively, after it changes.
159
- override initialize() {
160
- this.events.onOff$Changed.on(value => {
161
- console.log(`Light is now ${value ? "ON" : "OFF"}`);
162
- });
163
- }
164
- }
165
-
166
- class TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {
167
- override initialize() {
168
- this.state.testEventTriggersEnabled = true; // set to true if you support test triggers ...
169
- super.initialize();
170
- }
171
-
172
- override testEventTrigger({ enableKey, eventTrigger }: GeneralDiagnostics.TestEventTriggerRequest) {
173
- console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);
174
- }
175
- }
176
-
177
- class MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {
178
- /** We return the incoming value and store the length of the string in our attribute and send it out as event */
179
- override myFancyCommand(request: MyFancyCommandRequest): MyFancyCommandResponse {
180
- const { value } = request;
181
- this.state.myFancyValue = value.length;
182
-
183
- this.events.myFancyEvent.emit({ eventValue: value }, this.context);
184
-
185
- return { response: value };
186
- }
187
-
188
- override initialize() {
189
- this.state.myFancyValue = -1; // Always initialize with -1
190
- }
191
- }
192
-
193
- /**
194
- * Create Device instance and add needed Listener
195
- *
196
- * Create an instance of the matter device class you want to use.
197
- * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.
198
- * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the
199
- * device specific API.
200
- *
201
- * The below logic also adds command handlers for commands of clusters that normally are handled device internally
202
- * like identify that can be implemented with the logic when these commands are called.
203
- */
204
-
205
- // Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.
206
- //
207
- // In this case we are using with() to install our On/Off cluster behavior.
208
- // .with("Lighting") not needed because we always have it in by default because we have default implementation
209
- const OnOffDevice = isSocket
210
- ? vendorId === 0xfff4
211
- ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)
212
- : OnOffPlugInUnitDevice.with(OnOffShellExecServer)
213
- : vendorId === 0xfff4
214
- ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)
215
- : OnOffLightDevice.with(OnOffShellExecServer);
216
-
217
- /**
218
- * Modify automatically added clusters of the Root endpoint if needed
219
- * In this example we change the networkCommissioning cluster into one for "Wifi only" devices when BLE is used
220
- * for commissioning, to demonstrate how to do this.
221
- * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,
222
- * then all this is not needed.
223
- * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.
224
- */
225
-
226
- // We use the Basic Root Endpoint without a NetworkCommissioning cluster
227
- let RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);
228
-
229
- let wifiOrThreadAdded = false;
230
- let threadAdded = false;
231
- if (Ble.enabled) {
232
- // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.
233
- // To offer e.g. a "Wi-Fi only device" (or any other combination) we need to override the Network Commissioning
234
- // cluster and implement all the need handling here. This is a "static implementation" for pure demonstration
235
- // purposes and just "simulates" the actions to be done. In a real world implementation this would be done by
236
- // the device implementor based on the relevant networking stack.
237
- // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8
238
- if (environment.vars.has("ble.wifi.fake")) {
239
- RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);
240
- wifiOrThreadAdded = true;
241
- } else if (environment.vars.has("ble.thread.fake")) {
242
- RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);
243
- wifiOrThreadAdded = true;
244
- threadAdded = true;
245
- }
246
- } else {
247
- RootEndpoint = RootEndpoint.with(
248
- NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface),
249
- );
250
- }
251
-
252
- const networkId = new Uint8Array(32);
253
- // Physical devices appear as "nodes" on a Matter network. As a device implementer you use a NodeServer to bring a
254
- // device online.
255
- //
256
- // Note there are a large number of options to NodeServer that we are allowing to take default values here. See
257
- // CompositeWindowCovering.ts for a more detailed example.
258
- const server = await ServerNode.create(RootEndpoint, {
259
- id: uniqueId,
260
- network: {
261
- port,
262
- discoveryCapabilities: {
263
- onIpNetwork: !environment.vars.has("ble.enable"),
264
- ble: environment.vars.has("ble.enable"),
265
- },
266
- ble: environment.vars.has("ble.enable"), // TODO remove when state init is fixed
267
- },
268
- commissioning: {
269
- passcode,
270
- discriminator,
271
- },
272
- productDescription: {
273
- name: deviceName,
274
- deviceType: DeviceTypeId(OnOffDevice.deviceType),
275
- },
276
- basicInformation: {
277
- vendorName,
278
- vendorId: VendorId(vendorId),
279
- nodeLabel: productName,
280
- productName,
281
- productLabel: productName,
282
- productId,
283
- serialNumber: `node-matter-${uniqueId}`,
284
- uniqueId,
285
- },
286
-
287
- // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally
288
- networkCommissioning: {
289
- maxNetworks: 1,
290
- interfaceEnabled: true,
291
- lastConnectErrorValue: 0,
292
- lastNetworkId: wifiOrThreadAdded ? null : networkId,
293
- lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,
294
- networks: [{ networkId: networkId, connected: !wifiOrThreadAdded }],
295
- scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,
296
- connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,
297
- supportedWifiBands: wifiOrThreadAdded && !threadAdded ? [NetworkCommissioning.WiFiBand["2G4"]] : undefined,
298
- supportedThreadFeatures: wifiOrThreadAdded && threadAdded ? { isFullThreadDevice: true } : undefined,
299
- threadVersion: wifiOrThreadAdded && threadAdded ? 4 : undefined, // means: Thread 1.3
300
- },
301
- myFancyFunctionality: {
302
- myFancyValue: 0,
303
- },
304
- });
305
-
306
- // Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.
307
- const endpoint = new Endpoint(OnOffDevice, { id: "onoff" });
308
- await server.add(endpoint);
309
-
310
- /**
311
- * This event is triggered when the device is initially commissioned successfully.
312
- * This means: It is added to the first fabric.
313
- */
314
- server.lifecycle.commissioned.on(() => console.log("Server was initially commissioned successfully!"));
315
-
316
- /** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
317
- server.lifecycle.decommissioned.on(() => console.log("Server was fully decommissioned successfully!"));
318
-
319
- /** This event is triggered when the device went online. This means that it is discoverable in the network. */
320
- server.lifecycle.online.on(() => console.log("Server is online"));
321
-
322
- /** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
323
- server.lifecycle.offline.on(() => console.log("Server is offline"));
324
-
325
- /**
326
- * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
327
- * information is needed.
328
- */
329
- server.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {
330
- let action = "";
331
- switch (fabricAction) {
332
- case FabricAction.Added:
333
- action = "added";
334
- break;
335
- case FabricAction.Removed:
336
- action = "removed";
337
- break;
338
- case FabricAction.Updated:
339
- action = "updated";
340
- break;
341
- }
342
- console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);
343
- console.log(server.state.commissioning.fabrics[fabricIndex]);
344
- });
345
-
346
- /**
347
- * This event is triggered when an operative new session was opened by a Controller.
348
- * It is not triggered for the initial commissioning process, just afterwards for real connections.
349
- */
350
- server.events.sessions.opened.on(session => console.log(`Session opened`, session));
351
-
352
- /**
353
- * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
354
- */
355
- server.events.sessions.closed.on(session => console.log(`Session closed`, session));
356
-
357
- /** This event is triggered when a subscription gets added or removed on an operative session. */
358
- server.events.sessions.subscriptionsChanged.on(session => {
359
- console.log(`Session subscriptions changed`, session);
360
- console.log(`Status of all sessions`, server.state.sessions.sessions);
361
- });
362
-
363
- // React on a change of identificationTime to do Identify stuff for the own device
364
- endpoint.events.identify.startIdentifying.on(() => {
365
- console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
366
- });
367
-
368
- endpoint.events.identify.stopIdentifying.on(() => {
369
- console.log(`Stop identify logic ...`);
370
- });
371
-
372
- // Our device is now built and we can bring the node online.
373
- //
374
- // Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()
375
- // method of the node.
376
-
377
- logEndpoint(EndpointServer.forEndpoint(server));
378
-
379
- /**
380
- * In order to start the node and announce it into the network we start the node. This method resolves when the Matter
381
- * node enters his online state. Alternatively, we could also use `await server.run()` which
382
- * resolves when the node goes offline again, but we want to execute code afterwards, so we use start() here
383
- */
384
- await server.start();
385
-
386
- console.log("Initial Fabrics", server.state.operationalCredentials.fabrics);
387
-
388
- /**
389
- * If the node is not commissioned already we display the QR code on console. The QR code is also logged
390
- */
391
- if (!server.lifecycle.isCommissioned) {
392
- const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;
393
-
394
- console.log(QrCode.get(qrPairingCode));
395
- console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);
396
- console.log(`Manual pairing code: ${manualPairingCode}`);
397
- } else {
398
- console.log("Device is already commissioned. Waiting for controllers to connect ...");
399
-
400
- /**
401
- * Sometimes reading or writing attributes is required. The following code shows how this works.
402
- * For read it is basically `endpoint.state.clustername.attributename`.
403
- * The set method allows to set one or multiple values via the structure of also clustername.attributename. When multiple values are set they are considered being one transaction which would be rolled back completely if one value fails to be set.
404
- */
405
-
406
- // Read onOff attribute from onOff cluster
407
- const onOffValue = endpoint.state.onOff.onOff;
408
- console.log(`current OnOff attribute: ${onOffValue}`);
409
-
410
- if (vendorId === 0xfff4) {
411
- // Set onOff attribute from OnOff cluster AND the myFancyValue of the MyFancyOwnFunctionality cluster together
412
- await endpoint.set({
413
- onOff: {
414
- onOff: !onOffValue,
415
- },
416
- // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.
417
- myFancyOwnFunctionality: {
418
- myFancyValue: 36,
419
- },
420
- });
421
- } else {
422
- // Set onOff attribute from OnOff cluster only
423
- await endpoint.set({
424
- onOff: {
425
- onOff: !onOffValue,
426
- },
427
- });
428
- }
429
- }
430
-
431
- /**
432
- * To correctly tear down the server we can use server.close().
433
- */
434
- process.on("SIGINT", () => {
435
- // Clean up on CTRL-C
436
- server
437
- .close()
438
- .then(() => process.exit(0))
439
- .catch(err => console.error(err));
440
- });