@project-chip/matter-node.js-examples 0.7.5 → 0.8.0-alpha.0-20240309-64eaef67

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/README.md +44 -0
  2. package/dist/esm/examples/BridgedDeviceNode.js +147 -0
  3. package/dist/esm/examples/BridgedDeviceNode.js.map +7 -0
  4. package/dist/esm/examples/{BridgedDevicesNode.js → BridgedDevicesNodeLegacy.js} +2 -2
  5. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +7 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js +116 -127
  7. package/dist/esm/examples/ComposedDeviceNode.js.map +3 -3
  8. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +138 -0
  9. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +7 -0
  10. package/dist/esm/examples/ControllerNode.js +24 -20
  11. package/dist/esm/examples/ControllerNode.js.map +2 -2
  12. package/dist/esm/examples/ControllerNodeLegacy.js +227 -0
  13. package/dist/esm/examples/ControllerNodeLegacy.js.map +7 -0
  14. package/dist/esm/examples/DeviceNode.js +118 -159
  15. package/dist/esm/examples/DeviceNode.js.map +2 -2
  16. package/dist/esm/examples/DeviceNodeFull.js +253 -0
  17. package/dist/esm/examples/DeviceNodeFull.js.map +7 -0
  18. package/dist/esm/examples/DeviceNodeFullLegacy.js +171 -0
  19. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +7 -0
  20. package/dist/esm/examples/IlluminatedRollerShade.js +85 -0
  21. package/dist/esm/examples/IlluminatedRollerShade.js.map +7 -0
  22. package/dist/esm/examples/LightDevice.js +34 -0
  23. package/dist/esm/examples/LightDevice.js.map +7 -0
  24. package/dist/esm/examples/MultiDeviceNode.js +133 -134
  25. package/dist/esm/examples/MultiDeviceNode.js.map +3 -3
  26. package/dist/esm/examples/MultiDeviceNodeLegacy.js +146 -0
  27. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +7 -0
  28. package/dist/esm/examples/SensorDeviceNode.js +167 -0
  29. package/dist/esm/examples/SensorDeviceNode.js.map +7 -0
  30. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +115 -0
  31. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +7 -0
  32. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +115 -0
  33. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +7 -0
  34. package/dist/esm/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.js → DummyWifiNetworkCommissioningServerLegacy.js} +16 -14
  35. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +7 -0
  36. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +110 -0
  37. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +7 -0
  38. package/dist/esm/tutorial/example01.js +5 -0
  39. package/dist/esm/tutorial/example01.js.map +7 -0
  40. package/dist/esm/tutorial/example02.js +7 -0
  41. package/dist/esm/tutorial/example02.js.map +7 -0
  42. package/dist/esm/tutorial/example03.js +15 -0
  43. package/dist/esm/tutorial/example03.js.map +7 -0
  44. package/dist/esm/tutorial/example04.js +10 -0
  45. package/dist/esm/tutorial/example04.js.map +7 -0
  46. package/dist/esm/tutorial/example05.js +14 -0
  47. package/dist/esm/tutorial/example05.js.map +7 -0
  48. package/package.json +9 -6
  49. package/src/examples/BridgedDeviceNode.ts +260 -0
  50. package/src/examples/{BridgedDevicesNode.ts → BridgedDevicesNodeLegacy.ts} +6 -1
  51. package/src/examples/ComposedDeviceNode.ts +173 -223
  52. package/src/examples/ComposedDeviceNodeLegacy.ts +252 -0
  53. package/src/examples/ControllerNode.ts +28 -22
  54. package/src/examples/ControllerNodeLegacy.ts +354 -0
  55. package/src/examples/DeviceNode.ts +173 -273
  56. package/src/examples/DeviceNodeFull.ts +440 -0
  57. package/src/examples/DeviceNodeFullLegacy.ts +307 -0
  58. package/src/examples/IlluminatedRollerShade.ts +130 -0
  59. package/src/examples/LightDevice.ts +60 -0
  60. package/src/examples/MultiDeviceNode.ts +184 -236
  61. package/src/examples/MultiDeviceNodeLegacy.ts +267 -0
  62. package/src/examples/SensorDeviceNode.ts +236 -0
  63. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +156 -0
  64. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +153 -0
  65. package/src/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.ts → DummyWifiNetworkCommissioningServerLegacy.ts} +16 -13
  66. package/src/examples/cluster/MyFancyOwnFunctionality.ts +185 -0
  67. package/src/tsconfig.json +9 -1
  68. package/src/tutorial/example01.ts +6 -0
  69. package/src/tutorial/example02.ts +9 -0
  70. package/src/tutorial/example03.ts +19 -0
  71. package/src/tutorial/example04.ts +13 -0
  72. package/src/tutorial/example05.ts +19 -0
  73. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  74. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningClusterServer.js.map +0 -7
@@ -0,0 +1,227 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @license
4
+ * Copyright 2022-2023 Project CHIP Authors
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ import { CommissioningController, MatterServer } from "@project-chip/matter-node.js";
8
+ import { BleNode } from "@project-chip/matter-node-ble.js/ble";
9
+ import { Ble } from "@project-chip/matter-node.js/ble";
10
+ import {
11
+ BasicInformationCluster,
12
+ DescriptorCluster,
13
+ GeneralCommissioning,
14
+ OnOffCluster
15
+ } from "@project-chip/matter-node.js/cluster";
16
+ import { NodeId } from "@project-chip/matter-node.js/datatype";
17
+ import { NodeStateInformation } from "@project-chip/matter-node.js/device";
18
+ import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
19
+ import { ManualPairingCodeCodec } from "@project-chip/matter-node.js/schema";
20
+ import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
21
+ import {
22
+ getIntParameter,
23
+ getParameter,
24
+ hasParameter,
25
+ requireMinNodeVersion,
26
+ singleton
27
+ } from "@project-chip/matter-node.js/util";
28
+ const logger = Logger.get("Controller");
29
+ requireMinNodeVersion(16);
30
+ switch (getParameter("loglevel")) {
31
+ case "fatal":
32
+ Logger.defaultLogLevel = Level.FATAL;
33
+ break;
34
+ case "error":
35
+ Logger.defaultLogLevel = Level.ERROR;
36
+ break;
37
+ case "warn":
38
+ Logger.defaultLogLevel = Level.WARN;
39
+ break;
40
+ case "info":
41
+ Logger.defaultLogLevel = Level.INFO;
42
+ break;
43
+ }
44
+ switch (getParameter("logformat")) {
45
+ case "plain":
46
+ Logger.format = Format.PLAIN;
47
+ break;
48
+ case "html":
49
+ Logger.format = Format.HTML;
50
+ break;
51
+ default:
52
+ if (process.stdin?.isTTY)
53
+ Logger.format = Format.ANSI;
54
+ }
55
+ if (hasParameter("ble")) {
56
+ Ble.get = singleton(
57
+ () => new BleNode({
58
+ hciId: getIntParameter("ble-hci-id")
59
+ })
60
+ );
61
+ }
62
+ const storageLocation = getParameter("store") ?? ".controller-node";
63
+ const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
64
+ logger.info(`Storage location: ${storageLocation} (Directory)`);
65
+ logger.info(
66
+ 'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
67
+ );
68
+ class ControllerNode {
69
+ async start() {
70
+ logger.info(`node-matter Controller started`);
71
+ const storageManager = new StorageManager(storage);
72
+ await storageManager.initialize();
73
+ const controllerStorage = storageManager.createContext("Controller");
74
+ const ip = controllerStorage.has("ip") ? controllerStorage.get("ip") : getParameter("ip");
75
+ const port = controllerStorage.has("port") ? controllerStorage.get("port") : getIntParameter("port");
76
+ const pairingCode = getParameter("pairingcode");
77
+ let longDiscriminator, setupPin, shortDiscriminator;
78
+ if (pairingCode !== void 0) {
79
+ const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
80
+ shortDiscriminator = pairingCodeCodec.shortDiscriminator;
81
+ longDiscriminator = void 0;
82
+ setupPin = pairingCodeCodec.passcode;
83
+ logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
84
+ } else {
85
+ longDiscriminator = getIntParameter("longDiscriminator") ?? controllerStorage.get("longDiscriminator", 3840);
86
+ if (longDiscriminator > 4095)
87
+ throw new Error("Discriminator value must be less than 4096");
88
+ setupPin = getIntParameter("pin") ?? controllerStorage.get("pin", 20202021);
89
+ }
90
+ if (shortDiscriminator === void 0 && longDiscriminator === void 0 || setupPin === void 0) {
91
+ throw new Error(
92
+ "Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode"
93
+ );
94
+ }
95
+ const commissioningOptions = {
96
+ regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
97
+ regulatoryCountryCode: "XX"
98
+ };
99
+ let ble = false;
100
+ if (hasParameter("ble")) {
101
+ ble = true;
102
+ const wifiSsid = getParameter("ble-wifi-ssid");
103
+ const wifiCredentials = getParameter("ble-wifi-credentials");
104
+ const threadNetworkName = getParameter("ble-thread-networkname");
105
+ const threadOperationalDataset = getParameter("ble-thread-operationaldataset");
106
+ if (wifiSsid !== void 0 && wifiCredentials !== void 0) {
107
+ logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);
108
+ commissioningOptions.wifiNetwork = {
109
+ wifiSsid,
110
+ wifiCredentials
111
+ };
112
+ }
113
+ if (threadNetworkName !== void 0 && threadOperationalDataset !== void 0) {
114
+ logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);
115
+ commissioningOptions.threadNetwork = {
116
+ networkName: threadNetworkName,
117
+ operationalDataset: threadOperationalDataset
118
+ };
119
+ }
120
+ }
121
+ const matterServer = new MatterServer(storageManager);
122
+ const commissioningController = new CommissioningController({
123
+ autoConnect: false
124
+ });
125
+ await matterServer.addCommissioningController(commissioningController);
126
+ await matterServer.start();
127
+ if (!commissioningController.isCommissioned()) {
128
+ const options = {
129
+ commissioning: commissioningOptions,
130
+ discovery: {
131
+ knownAddress: ip !== void 0 && port !== void 0 ? { ip, port, type: "udp" } : void 0,
132
+ identifierData: longDiscriminator !== void 0 ? { longDiscriminator } : shortDiscriminator !== void 0 ? { shortDiscriminator } : {},
133
+ discoveryCapabilities: {
134
+ ble
135
+ }
136
+ },
137
+ passcode: setupPin
138
+ };
139
+ logger.info(`Commissioning ... ${JSON.stringify(options)}`);
140
+ const nodeId = await commissioningController.commissionNode(options);
141
+ console.log(`Commissioning successfully done with nodeId ${nodeId}`);
142
+ }
143
+ try {
144
+ const nodes = commissioningController.getCommissionedNodes();
145
+ console.log("Found commissioned nodes:", Logger.toJSON(nodes));
146
+ const nodeId = NodeId(getIntParameter("nodeid") ?? nodes[0]);
147
+ if (!nodes.includes(nodeId)) {
148
+ throw new Error(`Node ${nodeId} not found in commissioned nodes`);
149
+ }
150
+ const node = await commissioningController.connectNode(nodeId, {
151
+ attributeChangedCallback: (peerNodeId, { path: { nodeId: nodeId2, clusterId, endpointId, attributeName }, value }) => console.log(
152
+ `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId2}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(
153
+ value
154
+ )}`
155
+ ),
156
+ eventTriggeredCallback: (peerNodeId, { path: { nodeId: nodeId2, clusterId, endpointId, eventName }, events }) => console.log(
157
+ `eventTriggeredCallback ${peerNodeId}: Event ${nodeId2}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(
158
+ events
159
+ )}`
160
+ ),
161
+ stateInformationCallback: (peerNodeId, info2) => {
162
+ switch (info2) {
163
+ case NodeStateInformation.Connected:
164
+ console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
165
+ break;
166
+ case NodeStateInformation.Disconnected:
167
+ console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
168
+ break;
169
+ case NodeStateInformation.Reconnecting:
170
+ console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
171
+ break;
172
+ case NodeStateInformation.WaitingForDeviceDiscovery:
173
+ console.log(
174
+ `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`
175
+ );
176
+ break;
177
+ case NodeStateInformation.StructureChanged:
178
+ console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
179
+ break;
180
+ case NodeStateInformation.Decommissioned:
181
+ console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
182
+ break;
183
+ }
184
+ }
185
+ });
186
+ node.logStructure();
187
+ const descriptor = node.getRootClusterClient(DescriptorCluster);
188
+ if (descriptor !== void 0) {
189
+ console.log(await descriptor.attributes.deviceTypeList.get());
190
+ console.log(await descriptor.getServerListAttribute());
191
+ } else {
192
+ console.log("No Descriptor Cluster found. This should never happen!");
193
+ }
194
+ const info = node.getRootClusterClient(BasicInformationCluster);
195
+ if (info !== void 0) {
196
+ console.log(await info.getProductNameAttribute());
197
+ } else {
198
+ console.log("No BasicInformation Cluster found. This should never happen!");
199
+ }
200
+ const devices = node.getDevices();
201
+ if (devices[0] && devices[0].number === 1) {
202
+ const onOff = devices[0].getClusterClient(OnOffCluster);
203
+ if (onOff !== void 0) {
204
+ let onOffStatus = await onOff.getOnOffAttribute();
205
+ console.log("initial onOffStatus", onOffStatus);
206
+ onOff.addOnOffAttributeListener((value) => {
207
+ console.log("subscription onOffStatus", value);
208
+ onOffStatus = value;
209
+ });
210
+ setInterval(() => {
211
+ onOff.toggle().then(() => {
212
+ onOffStatus = !onOffStatus;
213
+ console.log("onOffStatus", onOffStatus);
214
+ }).catch((error) => logger.error(error));
215
+ }, 6e4);
216
+ }
217
+ }
218
+ } finally {
219
+ setTimeout(() => process.exit(0), 1e6);
220
+ }
221
+ }
222
+ }
223
+ new ControllerNode().start().catch((error) => logger.error(error));
224
+ process.on("SIGINT", () => {
225
+ storage.close().then(() => process.exit(0)).catch(() => process.exit(1));
226
+ });
227
+ //# sourceMappingURL=ControllerNodeLegacy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/ControllerNodeLegacy.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\n\n/**\n * @license\n * Copyright 2022-2023 Project CHIP Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a Matter controller to pair with a device and interfact with it.\n * It can be used as CLI script, but is more thought as a starting point for your own controller implementation\n * because you need to adjust the code in any way depending on your use case.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningController, MatterServer, NodeCommissioningOptions } from \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { Ble } from \"@project-chip/matter-node.js/ble\";\nimport {\n BasicInformationCluster,\n DescriptorCluster,\n GeneralCommissioning,\n OnOffCluster,\n} from \"@project-chip/matter-node.js/cluster\";\nimport { NodeId } from \"@project-chip/matter-node.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { CommissioningOptions } from \"@project-chip/matter-node.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport {\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n singleton,\n} from \"@project-chip/matter-node.js/util\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".controller-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const controllerStorage = storageManager.createContext(\"Controller\");\n const ip = controllerStorage.has(\"ip\") ? controllerStorage.get<string>(\"ip\") : getParameter(\"ip\");\n const port = controllerStorage.has(\"port\") ? controllerStorage.get<number>(\"port\") : getIntParameter(\"port\");\n\n const pairingCode = getParameter(\"pairingcode\");\n let longDiscriminator, setupPin, shortDiscriminator;\n if (pairingCode !== undefined) {\n const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);\n shortDiscriminator = pairingCodeCodec.shortDiscriminator;\n longDiscriminator = undefined;\n setupPin = pairingCodeCodec.passcode;\n logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);\n } else {\n longDiscriminator =\n getIntParameter(\"longDiscriminator\") ?? controllerStorage.get(\"longDiscriminator\", 3840);\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = getIntParameter(\"pin\") ?? controllerStorage.get(\"pin\", 20202021);\n }\n if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {\n throw new Error(\n \"Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode\",\n );\n }\n\n // Collect commissioning options from commandline parameters\n const commissioningOptions: CommissioningOptions = {\n regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,\n regulatoryCountryCode: \"XX\",\n };\n\n let ble = false;\n if (hasParameter(\"ble\")) {\n ble = true;\n const wifiSsid = getParameter(\"ble-wifi-ssid\");\n const wifiCredentials = getParameter(\"ble-wifi-credentials\");\n const threadNetworkName = getParameter(\"ble-thread-networkname\");\n const threadOperationalDataset = getParameter(\"ble-thread-operationaldataset\");\n if (wifiSsid !== undefined && wifiCredentials !== undefined) {\n logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);\n commissioningOptions.wifiNetwork = {\n wifiSsid: wifiSsid,\n wifiCredentials: wifiCredentials,\n };\n }\n if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {\n logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);\n commissioningOptions.threadNetwork = {\n networkName: threadNetworkName,\n operationalDataset: threadOperationalDataset,\n };\n }\n }\n\n /**\n * Create Matter Server and Controller Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * CommissioningController to it and add the just created device instance to it.\n * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n const matterServer = new MatterServer(storageManager);\n const commissioningController = new CommissioningController({\n autoConnect: false,\n });\n await matterServer.addCommissioningController(commissioningController);\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await matterServer.start();\n\n if (!commissioningController.isCommissioned()) {\n const options = {\n commissioning: commissioningOptions,\n discovery: {\n knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: \"udp\" } : undefined,\n identifierData:\n longDiscriminator !== undefined\n ? { longDiscriminator }\n : shortDiscriminator !== undefined\n ? { shortDiscriminator }\n : {},\n discoveryCapabilities: {\n ble,\n },\n },\n passcode: setupPin,\n } as NodeCommissioningOptions;\n logger.info(`Commissioning ... ${JSON.stringify(options)}`);\n const nodeId = await commissioningController.commissionNode(options);\n\n console.log(`Commissioning successfully done with nodeId ${nodeId}`);\n }\n\n /**\n * TBD\n */\n try {\n const nodes = commissioningController.getCommissionedNodes();\n console.log(\"Found commissioned nodes:\", Logger.toJSON(nodes));\n\n const nodeId = NodeId(getIntParameter(\"nodeid\") ?? nodes[0]);\n if (!nodes.includes(nodeId)) {\n throw new Error(`Node ${nodeId} not found in commissioned nodes`);\n }\n\n const node = await commissioningController.connectNode(nodeId, {\n attributeChangedCallback: (\n peerNodeId,\n { path: { nodeId, clusterId, endpointId, attributeName }, value },\n ) =>\n console.log(\n `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(\n value,\n )}`,\n ),\n eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>\n console.log(\n `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(\n events,\n )}`,\n ),\n stateInformationCallback: (peerNodeId, info) => {\n switch (info) {\n case NodeStateInformation.Connected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);\n break;\n case NodeStateInformation.Disconnected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);\n break;\n case NodeStateInformation.Reconnecting:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);\n break;\n case NodeStateInformation.WaitingForDeviceDiscovery:\n console.log(\n `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,\n );\n break;\n case NodeStateInformation.StructureChanged:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);\n break;\n case NodeStateInformation.Decommissioned:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);\n break;\n }\n },\n });\n\n // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!\n // It is provided to proof the concept\n\n node.logStructure();\n\n // Example to initialize a ClusterClient and access concrete fields as API methods\n const descriptor = node.getRootClusterClient(DescriptorCluster);\n if (descriptor !== undefined) {\n console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way\n console.log(await descriptor.getServerListAttribute()); // or more convenient that way\n } else {\n console.log(\"No Descriptor Cluster found. This should never happen!\");\n }\n\n // Example to subscribe to a field and get the value\n const info = node.getRootClusterClient(BasicInformationCluster);\n if (info !== undefined) {\n console.log(await info.getProductNameAttribute()); // This call is executed remotely\n //console.log(await info.subscribeProductNameAttribute(value => console.log(\"productName\", value), 5, 30));\n //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!\n } else {\n console.log(\"No BasicInformation Cluster found. This should never happen!\");\n }\n\n // Example to get all Attributes of the commissioned node: */*/*\n //const attributesAll = await interactionClient.getAllAttributes();\n //console.log(\"Attributes-All:\", Logger.toJSON(attributesAll));\n\n // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*\n //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);\n //console.log(\"Attributes-Descriptor:\", JSON.stringify(attributesAllDescriptor, null, 2));\n\n // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*\n //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);\n //console.log(\"Attributes-BasicInformation:\", JSON.stringify(attributesBasicInformation, null, 2));\n\n const devices = node.getDevices();\n if (devices[0] && devices[0].number === 1) {\n // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*\n //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {\n // console.log(\"Subscribe-All Data:\", Logger.toJSON(data));\n //});\n\n const onOff = devices[0].getClusterClient(OnOffCluster);\n if (onOff !== undefined) {\n let onOffStatus = await onOff.getOnOffAttribute();\n console.log(\"initial onOffStatus\", onOffStatus);\n\n onOff.addOnOffAttributeListener(value => {\n console.log(\"subscription onOffStatus\", value);\n onOffStatus = value;\n });\n // read data every minute to keep up the connection to show the subscription is working\n setInterval(() => {\n onOff\n .toggle()\n .then(() => {\n onOffStatus = !onOffStatus;\n console.log(\"onOffStatus\", onOffStatus);\n })\n .catch(error => logger.error(error));\n }, 60000);\n }\n }\n } finally {\n //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed\n setTimeout(() => process.exit(0), 1000000);\n }\n }\n}\n\nnew ControllerNode().start().catch(error => logger.error(error));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage\n .close()\n .then(() => process.exit(0))\n .catch(() => process.exit(1));\n});\n"],
5
+ "mappings": ";AAEA;AAAA;AAAA;AAAA;AAAA;AAgBA,SAAS,yBAAyB,oBAA8C;AAEhF,SAAS,eAAe;AACxB,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,QAAQ,OAAO,cAAc;AAEtC,SAAS,8BAA8B;AACvC,SAAS,oBAAoB,sBAAsB;AACnD;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,MAAM,SAAS,OAAO,IAAI,YAAY;AAEtC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD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D,kBAAQ,IAAI,uBAAuB,WAAW;AAE9C,gBAAM,0BAA0B,WAAS;AACrC,oBAAQ,IAAI,4BAA4B,KAAK;AAC7C,0BAAc;AAAA,UAClB,CAAC;AAED,sBAAY,MAAM;AACd,kBACK,OAAO,EACP,KAAK,MAAM;AACR,4BAAc,CAAC;AACf,sBAAQ,IAAI,eAAe,WAAW;AAAA,YAC1C,CAAC,EACA,MAAM,WAAS,OAAO,MAAM,KAAK,CAAC;AAAA,UAC3C,GAAG,GAAK;AAAA,QACZ;AAAA,MACJ;AAAA,IACJ,UAAE;AAEE,iBAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,GAAO;AAAA,IAC7C;AAAA,EACJ;AACJ;AAEA,IAAI,eAAe,EAAE,MAAM,EAAE,MAAM,WAAS,OAAO,MAAM,KAAK,CAAC;AAE/D,QAAQ,GAAG,UAAU,MAAM;AAGvB,UACK,MAAM,EACN,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,EAC1B,MAAM,MAAM,QAAQ,KAAK,CAAC,CAAC;AACpC,CAAC;",
6
+ "names": ["nodeId", "info"]
7
+ }
@@ -1,171 +1,130 @@
1
- #!/usr/bin/env node
2
1
  /**
3
2
  * @license
4
- * Copyright 2022 The node-matter Authors
3
+ * Copyright 2022-2024 Matter.js Authors
5
4
  * SPDX-License-Identifier: Apache-2.0
6
5
  */
7
- import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
- import { BleNode } from "@project-chip/matter-node-ble.js/ble";
9
- import { Ble } from "@project-chip/matter-node.js/ble";
10
- import { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from "@project-chip/matter-node.js/device";
11
- import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
12
- import { QrCode } from "@project-chip/matter-node.js/schema";
13
- import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
14
- import { Time } from "@project-chip/matter-node.js/time";
15
- import {
16
- commandExecutor,
17
- getIntParameter,
18
- getParameter,
19
- hasParameter,
20
- requireMinNodeVersion,
21
- singleton
22
- } from "@project-chip/matter-node.js/util";
6
+ import "@project-chip/matter-node.js";
7
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
23
8
  import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
24
- import DummyWifiNetworkCommissioningClusterServer from "./cluster/DummyWifiNetworkCommissioningClusterServer.js";
25
- const logger = Logger.get("Device");
9
+ import { logEndpoint } from "@project-chip/matter.js/device";
10
+ import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
11
+ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
12
+ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
13
+ import { Environment, StorageService } from "@project-chip/matter.js/environment";
14
+ import { ServerNode } from "@project-chip/matter.js/node";
15
+ import { Time } from "@project-chip/matter.js/time";
16
+ import { execSync } from "child_process";
26
17
  requireMinNodeVersion(16);
27
- switch (getParameter("loglevel")) {
28
- case "fatal":
29
- Logger.defaultLogLevel = Level.FATAL;
30
- break;
31
- case "error":
32
- Logger.defaultLogLevel = Level.ERROR;
33
- break;
34
- case "warn":
35
- Logger.defaultLogLevel = Level.WARN;
36
- break;
37
- case "info":
38
- Logger.defaultLogLevel = Level.INFO;
39
- break;
40
- }
41
- switch (getParameter("logformat")) {
42
- case "plain":
43
- Logger.format = Format.PLAIN;
44
- break;
45
- case "html":
46
- Logger.format = Format.HTML;
47
- break;
48
- default:
49
- if (process.stdin?.isTTY)
50
- Logger.format = Format.ANSI;
51
- }
52
- if (hasParameter("ble")) {
53
- Ble.get = singleton(
54
- () => new BleNode({
55
- hciId: getIntParameter("ble-hci-id")
56
- })
57
- );
58
- }
59
- const storageLocation = getParameter("store") ?? ".device-node";
60
- const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
61
- logger.info(`Storage location: ${storageLocation} (Directory)`);
62
- logger.info(
63
- 'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
64
- );
65
- class Device {
66
- async start() {
67
- logger.info(`node-matter`);
68
- const storageManager = new StorageManager(storage);
69
- await storageManager.initialize();
70
- const deviceStorage = storageManager.createContext("Device");
71
- if (deviceStorage.has("isSocket")) {
72
- logger.info("Device type found in storage. -type parameter is ignored.");
73
- }
74
- const isSocket = deviceStorage.get("isSocket", getParameter("type") === "socket");
75
- const deviceName = "Matter test device";
76
- const vendorName = "matter-node.js";
77
- const passcode = getIntParameter("passcode") ?? deviceStorage.get("passcode", 20202021);
78
- const discriminator = getIntParameter("discriminator") ?? deviceStorage.get("discriminator", 3840);
79
- const vendorId = getIntParameter("vendorid") ?? deviceStorage.get("vendorid", 65521);
80
- const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
81
- const productId = getIntParameter("productid") ?? deviceStorage.get("productid", 32768);
82
- const netInterface = getParameter("netinterface");
83
- const port = getIntParameter("port") ?? 5540;
84
- const uniqueId = getIntParameter("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs());
85
- deviceStorage.set("passcode", passcode);
86
- deviceStorage.set("discriminator", discriminator);
87
- deviceStorage.set("vendorid", vendorId);
88
- deviceStorage.set("productid", productId);
89
- deviceStorage.set("isSocket", isSocket);
90
- deviceStorage.set("uniqueid", uniqueId);
91
- const onOffDevice = isSocket ? new OnOffPluginUnitDevice() : new OnOffLightDevice();
92
- onOffDevice.addOnOffListener((on) => commandExecutor(on ? "on" : "off")?.());
93
- onOffDevice.addCommandHandler(
94
- "identify",
95
- async ({ request: { identifyTime } }) => logger.info(`Identify called for OnOffDevice: ${identifyTime}`)
96
- );
97
- this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });
98
- const commissioningServer = new CommissioningServer({
99
- port,
100
- deviceName,
101
- deviceType: DeviceTypeId(onOffDevice.deviceType),
18
+ async function main() {
19
+ const {
20
+ isSocket,
21
+ deviceName,
22
+ vendorName,
23
+ passcode,
24
+ discriminator,
25
+ vendorId,
26
+ productName,
27
+ productId,
28
+ port,
29
+ uniqueId
30
+ } = await getConfiguration();
31
+ const server = await ServerNode.create({
32
+ // Required: Give the Node a unique ID which is used to store the state of this node
33
+ id: uniqueId,
34
+ // Provide Network relevant configuration like the port
35
+ // Optional when operating only one device on a host, Default port is 5540
36
+ network: {
37
+ port
38
+ },
39
+ // Provide Commissioning relevant settings
40
+ // Optional for development/testing purposes
41
+ commissioning: {
102
42
  passcode,
103
- discriminator,
104
- basicInformation: {
105
- vendorName,
106
- vendorId: VendorId(vendorId),
107
- nodeLabel: productName,
108
- productName,
109
- productLabel: productName,
110
- productId,
111
- serialNumber: `node-matter-${uniqueId}`
112
- },
113
- delayedAnnouncement: hasParameter("ble"),
114
- // Delay announcement when BLE is used to show how limited advertisement works
115
- activeSessionsChangedCallback: (fabricIndex) => {
116
- console.log(
117
- `activeSessionsChangedCallback: Active sessions changed on Fabric ${fabricIndex}`,
118
- commissioningServer.getActiveSessionInformation(fabricIndex)
119
- );
120
- },
121
- commissioningChangedCallback: (fabricIndex) => {
122
- console.log(
123
- `commissioningChangedCallback: Commissioning changed on Fabric ${fabricIndex}`,
124
- commissioningServer.getCommissionedFabricInformation(fabricIndex)[0]
125
- );
126
- }
127
- });
128
- commissioningServer.addCommandHandler(
129
- "testEventTrigger",
130
- async ({ request: { enableKey, eventTrigger } }) => logger.info(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`)
131
- );
132
- if (hasParameter("ble")) {
133
- commissioningServer.addRootClusterServer(DummyWifiNetworkCommissioningClusterServer);
43
+ discriminator
44
+ },
45
+ // Provide Node announcement settings
46
+ // Optional: If Ommitted some development defaults are used
47
+ productDescription: {
48
+ name: deviceName,
49
+ deviceType: DeviceTypeId(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType)
50
+ },
51
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
52
+ // Optional: If Omitted some development defaults are used
53
+ basicInformation: {
54
+ vendorName,
55
+ vendorId: VendorId(vendorId),
56
+ nodeLabel: productName,
57
+ productName,
58
+ productLabel: productName,
59
+ productId,
60
+ serialNumber: `matterjs-${uniqueId}`,
61
+ uniqueId
134
62
  }
135
- commissioningServer.addDevice(onOffDevice);
136
- await this.matterServer.addCommissioningServer(commissioningServer);
137
- await this.matterServer.start();
138
- logEndpoint(commissioningServer.getRootEndpoint());
139
- if (hasParameter("ble")) {
140
- await commissioningServer.advertise({ ble: true });
63
+ });
64
+ const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: "onoff" });
65
+ await server.add(endpoint);
66
+ let isIdentifying = false;
67
+ endpoint.events.identify.identifyTime$Change.on((value) => {
68
+ if (value > 0 && !isIdentifying) {
69
+ isIdentifying = true;
70
+ console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
71
+ } else if (value === 0) {
72
+ isIdentifying = false;
73
+ console.log(`Stop identify logic ...`);
141
74
  }
142
- logger.info("Listening");
143
- if (!commissioningServer.isCommissioned()) {
144
- const pairingData = commissioningServer.getPairingCode({
145
- ble: hasParameter("ble"),
146
- softAccessPoint: false,
147
- onIpNetwork: false
148
- });
149
- const { qrPairingCode, manualPairingCode } = pairingData;
150
- console.log(QrCode.get(qrPairingCode));
151
- logger.info(
152
- `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`
153
- );
154
- logger.info(`Manual pairing code: ${manualPairingCode}`);
155
- } else {
156
- logger.info("Device is already commissioned. Waiting for controllers to connect ...");
157
- }
158
- }
159
- async stop() {
160
- await this.matterServer?.close();
75
+ });
76
+ endpoint.events.onOff.onOff$Change.on((value) => {
77
+ executeCommand(value ? "on" : "off");
78
+ console.log(`OnOff is now ${value ? "ON" : "OFF"}`);
79
+ });
80
+ logEndpoint(EndpointServer.forEndpoint(server));
81
+ await server.run();
82
+ }
83
+ main().catch((error) => console.error(error));
84
+ function executeCommand(scriptParamName) {
85
+ const script = Environment.default.vars.string(scriptParamName);
86
+ if (script === void 0)
87
+ return void 0;
88
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
89
+ }
90
+ async function getConfiguration() {
91
+ const environment = Environment.default;
92
+ const storageService = environment.get(StorageService);
93
+ console.log(`Storage location: ${storageService.location} (Directory)`);
94
+ console.log(
95
+ '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.'
96
+ );
97
+ const deviceStorage = (await storageService.open("device")).createContext("data");
98
+ const isSocket = deviceStorage.get("isSocket", environment.vars.get("type") === "socket");
99
+ if (deviceStorage.has("isSocket")) {
100
+ console.log(`Device type ${isSocket ? "socket" : "light"} found in storage. --type parameter is ignored.`);
161
101
  }
102
+ const deviceName = "Matter test device";
103
+ const vendorName = "matter-node.js";
104
+ const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
105
+ const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
106
+ const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
107
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
108
+ const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
109
+ const port = environment.vars.number("port") ?? 5540;
110
+ const uniqueId = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
111
+ deviceStorage.set("passcode", passcode);
112
+ deviceStorage.set("discriminator", discriminator);
113
+ deviceStorage.set("vendorid", vendorId);
114
+ deviceStorage.set("productid", productId);
115
+ deviceStorage.set("isSocket", isSocket);
116
+ deviceStorage.set("uniqueid", uniqueId);
117
+ return {
118
+ isSocket,
119
+ deviceName,
120
+ vendorName,
121
+ passcode,
122
+ discriminator,
123
+ vendorId,
124
+ productName,
125
+ productId,
126
+ port,
127
+ uniqueId
128
+ };
162
129
  }
163
- const device = new Device();
164
- device.start().then(() => {
165
- }).catch((err) => console.error(err));
166
- process.on("SIGINT", () => {
167
- device.stop().then(() => {
168
- storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
169
- }).catch((err) => console.error(err));
170
- });
171
130
  //# sourceMappingURL=DeviceNode.js.map