@project-chip/matter-node.js-examples 0.7.5 → 0.8.0-alpha.1-20240308-033110a3

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,146 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @license
4
+ * Copyright 2022-2024 Matter.js Authors
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
+ import { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter-node.js/device";
9
+ import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
10
+ import { QrCode } from "@project-chip/matter-node.js/schema";
11
+ import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
12
+ import { Time } from "@project-chip/matter-node.js/time";
13
+ import {
14
+ commandExecutor,
15
+ getIntParameter,
16
+ getParameter,
17
+ hasParameter,
18
+ requireMinNodeVersion
19
+ } from "@project-chip/matter-node.js/util";
20
+ import { VendorId } from "@project-chip/matter.js/datatype";
21
+ const logger = Logger.get("MultiDevice");
22
+ requireMinNodeVersion(16);
23
+ switch (getParameter("loglevel")) {
24
+ case "fatal":
25
+ Logger.defaultLogLevel = Level.FATAL;
26
+ break;
27
+ case "error":
28
+ Logger.defaultLogLevel = Level.ERROR;
29
+ break;
30
+ case "warn":
31
+ Logger.defaultLogLevel = Level.WARN;
32
+ break;
33
+ case "info":
34
+ Logger.defaultLogLevel = Level.INFO;
35
+ break;
36
+ }
37
+ switch (getParameter("logformat")) {
38
+ case "plain":
39
+ Logger.format = Format.PLAIN;
40
+ break;
41
+ case "html":
42
+ Logger.format = Format.HTML;
43
+ break;
44
+ default:
45
+ if (process.stdin?.isTTY)
46
+ Logger.format = Format.ANSI;
47
+ }
48
+ const storageLocation = getParameter("store") ?? ".device-node";
49
+ const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
50
+ logger.info(`Storage location: ${storageLocation} (Directory)`);
51
+ logger.info(
52
+ 'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
53
+ );
54
+ class Device {
55
+ async start() {
56
+ logger.info(`node-matter`);
57
+ const storageManager = new StorageManager(storage);
58
+ await storageManager.initialize();
59
+ const netInterface = getParameter("netinterface");
60
+ const deviceStorage = storageManager.createContext("Device");
61
+ this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });
62
+ const commissioningServers = new Array();
63
+ let defaultPasscode = 20202021;
64
+ let defaultDiscriminator = 3840;
65
+ let defaultPort = 5550;
66
+ const numDevices = getIntParameter("num") || 2;
67
+ for (let i = 1; i <= numDevices; i++) {
68
+ if (deviceStorage.has(`isSocket${i}`)) {
69
+ logger.info("Device type found in storage. -type parameter is ignored.");
70
+ }
71
+ const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === "socket");
72
+ const deviceName = `Matter ${getParameter(`type${i}`) ?? "light"} device ${i}`;
73
+ const deviceType = getParameter(`type${i}`) === "socket" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;
74
+ const vendorName = "matter-node.js";
75
+ const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);
76
+ const discriminator = getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);
77
+ const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 65521);
78
+ const productName = `node-matter OnOff-Device ${i}`;
79
+ const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 32768);
80
+ const port = getIntParameter(`port${i}`) ?? defaultPort++;
81
+ const uniqueId = getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);
82
+ deviceStorage.set(`passcode${i}`, passcode);
83
+ deviceStorage.set(`discriminator${i}`, discriminator);
84
+ deviceStorage.set(`vendorid${i}`, vendorId);
85
+ deviceStorage.set(`productid${i}`, productId);
86
+ deviceStorage.set(`isSocket${i}`, isSocket);
87
+ deviceStorage.set(`uniqueid${i}`, uniqueId);
88
+ const commissioningServer = new CommissioningServer({
89
+ port,
90
+ deviceName,
91
+ deviceType,
92
+ passcode,
93
+ discriminator,
94
+ basicInformation: {
95
+ vendorName,
96
+ vendorId: VendorId(vendorId),
97
+ nodeLabel: productName,
98
+ productName,
99
+ productLabel: productName,
100
+ productId,
101
+ serialNumber: `node-matter-${uniqueId}`
102
+ }
103
+ });
104
+ console.log(
105
+ `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`
106
+ );
107
+ const onOffDevice = getParameter(`type${i}`) === "socket" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();
108
+ onOffDevice.addFixedLabel("orientation", getParameter(`orientation${i}`) ?? `orientation ${i}`);
109
+ onOffDevice.addOnOffListener((on) => commandExecutor(on ? `on${i}` : `off${i}`)?.());
110
+ commissioningServer.addDevice(onOffDevice);
111
+ await this.matterServer.addCommissioningServer(commissioningServer);
112
+ commissioningServers.push(commissioningServer);
113
+ }
114
+ await this.matterServer.start();
115
+ logger.info("Listening");
116
+ console.log();
117
+ commissioningServers.forEach((commissioningServer, index) => {
118
+ console.log("----------------------------");
119
+ console.log(`Device ${index + 1}:`);
120
+ if (!commissioningServer.isCommissioned()) {
121
+ const pairingData = commissioningServer.getPairingCode();
122
+ const { qrPairingCode, manualPairingCode } = pairingData;
123
+ console.log(QrCode.get(qrPairingCode));
124
+ console.log(
125
+ `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`
126
+ );
127
+ console.log(`Manual pairing code: ${manualPairingCode}`);
128
+ } else {
129
+ console.log("Device is already commissioned. Waiting for controllers to connect ...");
130
+ }
131
+ console.log();
132
+ });
133
+ }
134
+ async stop() {
135
+ await this.matterServer?.close();
136
+ }
137
+ }
138
+ const device = new Device();
139
+ device.start().then(() => {
140
+ }).catch((err) => console.error(err));
141
+ process.on("SIGINT", () => {
142
+ device.stop().then(() => {
143
+ storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
144
+ }).catch((err) => console.error(err));
145
+ });
146
+ //# sourceMappingURL=MultiDeviceNodeLegacy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/MultiDeviceNodeLegacy.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. When you want to add a composed devices to a Aggregator you need to\n * add all endpoints of the composed device to an \"ComposedDevice\" instance! (not shown in this example).\n * It can be used as CLI script and starting point for your own device node implementation.\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 { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\n\nconst logger = Logger.get(\"MultiDevice\");\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\nconst storageLocation = getParameter(\"store\") ?? \".device-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 Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\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 const netInterface = getParameter(\"netinterface\");\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer 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 this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const commissioningServers = new Array<CommissioningServer>();\n\n let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n if (deviceStorage.has(`isSocket${i}`)) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === \"socket\");\n const deviceName = `Matter ${getParameter(`type${i}`) ?? \"light\"} device ${i}`;\n const deviceType =\n getParameter(`type${i}`) === \"socket\"\n ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code\n : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = getIntParameter(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n commissioningServer.addDevice(onOffDevice);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n commissioningServers.push(commissioningServer);\n }\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 this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n console.log();\n commissioningServers.forEach((commissioningServer, index) => {\n console.log(\"----------------------------\");\n console.log(`Device ${index + 1}:`);\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n console.log();\n });\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\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(err => console.error(err));\n })\n .catch(err => console.error(err));\n});\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,gBAAgB;AAEzB,MAAM,SAAS,OAAO,IAAI,aAAa;AAEvC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AACR;AAEA,QAAQ,aAAa,WAAW,GAAG;AAAA,EAC/B,KAAK;AACD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 /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import "@project-chip/matter-node.js";
7
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
8
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
9
+ import { logEndpoint } from "@project-chip/matter.js/device";
10
+ import { HumiditySensorDevice } from "@project-chip/matter.js/devices/HumiditySensorDevice";
11
+ import { TemperatureSensorDevice } from "@project-chip/matter.js/devices/TemperatureSensorDevice";
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";
17
+ requireMinNodeVersion(16);
18
+ async function main() {
19
+ const {
20
+ isTemperature,
21
+ interval,
22
+ deviceName,
23
+ vendorName,
24
+ passcode,
25
+ discriminator,
26
+ vendorId,
27
+ productName,
28
+ productId,
29
+ port,
30
+ uniqueId
31
+ } = await getConfiguration();
32
+ const server = await ServerNode.create({
33
+ // Required: Give the Node a unique ID which is used to store the state of this node
34
+ id: uniqueId,
35
+ // Provide Network relevant configuration like the port
36
+ // Optional when operating only one device on a host, Default port is 5540
37
+ network: {
38
+ port
39
+ },
40
+ // Provide Commissioning relevant settings
41
+ // Optional for development/testing purposes
42
+ commissioning: {
43
+ passcode,
44
+ discriminator
45
+ },
46
+ // Provide Node announcement settings
47
+ // Optional: If Ommitted some development defaults are used
48
+ productDescription: {
49
+ name: deviceName,
50
+ deviceType: DeviceTypeId(
51
+ isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType
52
+ )
53
+ },
54
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
55
+ // Optional: If Omitted some development defaults are used
56
+ basicInformation: {
57
+ vendorName,
58
+ vendorId: VendorId(vendorId),
59
+ nodeLabel: productName,
60
+ productName,
61
+ productLabel: productName,
62
+ productId,
63
+ serialNumber: `matterjs-${uniqueId}`,
64
+ uniqueId
65
+ }
66
+ });
67
+ let endpoint;
68
+ if (isTemperature) {
69
+ endpoint = new Endpoint(TemperatureSensorDevice, {
70
+ id: "tempsensor",
71
+ temperatureMeasurement: { measuredValue: getIntValueFromCommandOrRandom("value") }
72
+ });
73
+ } else {
74
+ endpoint = new Endpoint(HumiditySensorDevice, {
75
+ id: "humsensor",
76
+ relativeHumidityMeasurement: { measuredValue: getIntValueFromCommandOrRandom("value", false) }
77
+ });
78
+ }
79
+ await server.add(endpoint);
80
+ logEndpoint(EndpointServer.forEndpoint(server));
81
+ const updateInterval = setInterval(() => {
82
+ let setter;
83
+ if (isTemperature) {
84
+ setter = endpoint.set({
85
+ temperatureMeasurement: {
86
+ measuredValue: getIntValueFromCommandOrRandom("value")
87
+ }
88
+ });
89
+ } else {
90
+ setter = endpoint.set({
91
+ relativeHumidityMeasurement: {
92
+ measuredValue: getIntValueFromCommandOrRandom("value", false)
93
+ }
94
+ });
95
+ }
96
+ setter.catch((error) => console.error("Error updating measured value:", error));
97
+ }, interval * 1e3);
98
+ server.lifecycle.offline.on(() => clearTimeout(updateInterval));
99
+ await server.run();
100
+ }
101
+ main().catch((error) => console.error(error));
102
+ function getIntValueFromCommandOrRandom(scriptParamName, allowNegativeValues = true) {
103
+ const script = Environment.default.vars.string(scriptParamName);
104
+ if (script === void 0) {
105
+ if (!allowNegativeValues)
106
+ return Math.round(Math.random() * 100);
107
+ return (Math.round(Math.random() * 100) - 50) * 100;
108
+ }
109
+ let result = execSync(script).toString().trim();
110
+ if (result.startsWith("'") && result.endsWith("'") || result.startsWith('"') && result.endsWith('"'))
111
+ result = result.slice(1, -1);
112
+ console.log(`Command result: ${result}`);
113
+ let value = Math.round(parseFloat(result));
114
+ if (!allowNegativeValues && value < 0)
115
+ value = 0;
116
+ return value;
117
+ }
118
+ async function getConfiguration() {
119
+ const environment = Environment.default;
120
+ const storageService = environment.get(StorageService);
121
+ console.log(`Storage location: ${storageService.location} (Directory)`);
122
+ console.log(
123
+ '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.'
124
+ );
125
+ const deviceStorage = (await storageService.open("device")).createContext("data");
126
+ const isTemperature = deviceStorage.get("isTemperature", environment.vars.get("type") !== "humidity");
127
+ if (deviceStorage.has("isTemperature")) {
128
+ console.log(
129
+ `Device type ${isTemperature ? "temperature" : "humidity"} found in storage. --type parameter is ignored.`
130
+ );
131
+ }
132
+ let interval = environment.vars.number("interval") ?? deviceStorage.get("interval", 60);
133
+ if (interval < 1) {
134
+ console.log(`Invalid Interval ${interval}, set to 60s`);
135
+ interval = 60;
136
+ }
137
+ const deviceName = "Matter test device";
138
+ const vendorName = "matter-node.js";
139
+ const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
140
+ const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
141
+ const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
142
+ const productName = `node-matter OnOff ${isTemperature ? "Temperature" : "Humidity"}`;
143
+ const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
144
+ const port = environment.vars.number("port") ?? 5540;
145
+ const uniqueId = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
146
+ deviceStorage.set("passcode", passcode);
147
+ deviceStorage.set("discriminator", discriminator);
148
+ deviceStorage.set("vendorid", vendorId);
149
+ deviceStorage.set("productid", productId);
150
+ deviceStorage.set("interval", interval);
151
+ deviceStorage.set("isTemperature", isTemperature);
152
+ deviceStorage.set("uniqueid", uniqueId);
153
+ return {
154
+ isTemperature,
155
+ interval,
156
+ deviceName,
157
+ vendorName,
158
+ passcode,
159
+ discriminator,
160
+ vendorId,
161
+ productName,
162
+ productId,
163
+ port,
164
+ uniqueId
165
+ };
166
+ }
167
+ //# sourceMappingURL=SensorDeviceNode.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/SensorDeviceNode.ts"],
4
+ "sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple Sensor Matter device as temperature or humidity device.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\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 \"@project-chip/matter-node.js\";\n\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { HumiditySensorDevice } from \"@project-chip/matter.js/devices/HumiditySensorDevice\";\nimport { TemperatureSensorDevice } from \"@project-chip/matter.js/devices/TemperatureSensorDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(\n isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,\n ),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n let endpoint: Endpoint;\n if (isTemperature) {\n endpoint = new Endpoint(TemperatureSensorDevice, {\n id: \"tempsensor\",\n temperatureMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\") },\n });\n } else {\n endpoint = new Endpoint(HumiditySensorDevice, {\n id: \"humsensor\",\n relativeHumidityMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\", false) },\n });\n }\n\n await server.add(endpoint);\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n const updateInterval = setInterval(() => {\n let setter: Promise<void>;\n if (isTemperature) {\n setter = endpoint.set({\n temperatureMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n setter = endpoint.set({\n relativeHumidityMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n setter.catch(error => console.error(\"Error updating measured value:\", error));\n }, interval * 1000);\n\n // Cleanup our update interval when node goes offline\n server.lifecycle.offline.on(() => clearTimeout(updateInterval));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\n\nfunction getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) {\n if (!allowNegativeValues) return Math.round(Math.random() * 100);\n return (Math.round(Math.random() * 100) - 50) * 100;\n }\n let result = execSync(script).toString().trim();\n if ((result.startsWith(\"'\") && result.endsWith(\"'\")) || (result.startsWith('\"') && result.endsWith('\"')))\n result = result.slice(1, -1);\n console.log(`Command result: ${result}`);\n let value = Math.round(parseFloat(result));\n if (!allowNegativeValues && value < 0) value = 0;\n return value;\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process 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 storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n '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.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isTemperature = deviceStorage.get(\"isTemperature\", environment.vars.get(\"type\") !== \"humidity\");\n if (deviceStorage.has(\"isTemperature\")) {\n console.log(\n `Device type ${isTemperature ? \"temperature\" : \"humidity\"} found in storage. --type parameter is ignored.`,\n );\n }\n let interval = environment.vars.number(\"interval\") ?? deviceStorage.get(\"interval\", 60);\n if (interval < 1) {\n console.log(`Invalid Interval ${interval}, set to 60s`);\n interval = 60;\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = environment.vars.number(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff ${isTemperature ? \"Temperature\" : \"Humidity\"}`;\n const productId = environment.vars.number(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId = environment.vars.string(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs().toString());\n\n // Persist basic data to keep them also on restart\n deviceStorage.set(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"interval\", interval);\n deviceStorage.set(\"isTemperature\", isTemperature);\n deviceStorage.set(\"uniqueid\", uniqueId);\n\n return {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
+ "mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB,eAAe,OAAO;AAElB,QAAM;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,IAAI,MAAM,iBAAiB;AAK3B,QAAM,SAAS,MAAM,WAAW,OAAO;AAAA;AAAA,IAEnC,IAAI;AAAA;AAAA;AAAA,IAIJ,SAAS;AAAA,MACL;AAA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,IAAI,oBAAoB,QAAQ,cAAc;AACtD,eAAW;AAAA,EACf;AAEA,QAAM,aAAa;AACnB,QAAM,aAAa;AACnB,QAAM,WAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,QAAQ;AAC9F,QAAM,gBAAgB,YAAY,KAAK,OAAO,eAAe,KAAK,cAAc,IAAI,iBAAiB,IAAI;AAEzG,QAAM,WAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,KAAM;AAC5F,QAAM,cAAc,qBAAqB,gBAAgB,gBAAgB,UAAU;AACnF,QAAM,YAAY,YAAY,KAAK,OAAO,WAAW,KAAK,cAAc,IAAI,aAAa,KAAM;AAE/F,QAAM,OAAO,YAAY,KAAK,OAAO,MAAM,KAAK;AAEhD,QAAM,WAAW,YAAY,KAAK,OAAO,UAAU,KAAK,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAG7G,gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,iBAAiB,aAAa;AAChD,gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,aAAa,SAAS;AACxC,gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,iBAAiB,aAAa;AAChD,gBAAc,IAAI,YAAY,QAAQ;AAEtC,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { GeneralCommissioningBehavior } from "@project-chip/matter.js/behavior/definitions/general-commissioning";
7
+ import {
8
+ NetworkCommissioningBehavior
9
+ } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
10
+ import { NetworkCommissioning } from "@project-chip/matter.js/cluster";
11
+ import { Logger } from "@project-chip/matter.js/log";
12
+ import { ByteArray } from "@project-chip/matter.js/util";
13
+ const firstNetworkId = new ByteArray(32);
14
+ class DummyThreadNetworkCommissioningServer extends NetworkCommissioningBehavior.with(
15
+ NetworkCommissioning.Feature.ThreadNetworkInterface
16
+ ) {
17
+ scanNetworks({ breadcrumb }) {
18
+ console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${breadcrumb}`);
19
+ if (breadcrumb !== void 0) {
20
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
21
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
22
+ }
23
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
24
+ this.state.lastNetworkingStatus = networkingStatus;
25
+ const threadScanResults = [
26
+ {
27
+ panId: this.endpoint.env.vars.number("ble.thread.panId"),
28
+ extendedPanId: BigInt(this.endpoint.env.vars.string("ble.thread.extendedPanId")),
29
+ networkName: this.endpoint.env.vars.string("ble.thread.networkName"),
30
+ channel: this.endpoint.env.vars.number("ble.thread.channel"),
31
+ version: 130,
32
+ extendedAddress: ByteArray.fromString(
33
+ (this.endpoint.env.vars.string("ble.thread.address") ?? "000000000000").toLowerCase()
34
+ ),
35
+ rssi: -50,
36
+ lqi: 50
37
+ }
38
+ ];
39
+ console.log(Logger.toJSON(threadScanResults));
40
+ return {
41
+ networkingStatus,
42
+ threadScanResults
43
+ };
44
+ }
45
+ addOrUpdateThreadNetwork({ operationalDataset, breadcrumb }) {
46
+ console.log(
47
+ `---> addOrUpdateWiFiNetwork called on NetworkCommissioning cluster: ${operationalDataset.toHex()} ${breadcrumb}`
48
+ );
49
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
50
+ if (breadcrumb !== void 0) {
51
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
52
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
53
+ }
54
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
55
+ this.state.lastNetworkingStatus = networkingStatus;
56
+ this.state.lastNetworkId = firstNetworkId;
57
+ return {
58
+ networkingStatus,
59
+ networkIndex: 0
60
+ };
61
+ }
62
+ removeNetwork({ networkId, breadcrumb }) {
63
+ console.log(`---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
64
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
65
+ if (breadcrumb !== void 0) {
66
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
67
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
68
+ }
69
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
70
+ this.state.lastNetworkingStatus = networkingStatus;
71
+ this.state.lastNetworkId = firstNetworkId;
72
+ return {
73
+ networkingStatus,
74
+ networkIndex: 0
75
+ };
76
+ }
77
+ async connectNetwork({ networkId, breadcrumb }) {
78
+ console.log(`---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
79
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
80
+ if (breadcrumb !== void 0) {
81
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
82
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
83
+ }
84
+ this.state.networks[0].connected = true;
85
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
86
+ this.state.lastNetworkingStatus = networkingStatus;
87
+ this.state.lastNetworkId = firstNetworkId;
88
+ this.state.lastConnectErrorValue = null;
89
+ const device = this.session.context;
90
+ await device.startAnnouncement();
91
+ return {
92
+ networkingStatus,
93
+ errorValue: null
94
+ };
95
+ }
96
+ reorderNetwork({ networkId, networkIndex, breadcrumb }) {
97
+ console.log(
98
+ `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`
99
+ );
100
+ if (breadcrumb !== void 0) {
101
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
102
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
103
+ }
104
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
105
+ this.state.lastNetworkingStatus = networkingStatus;
106
+ return {
107
+ networkingStatus,
108
+ networkIndex: 0
109
+ };
110
+ }
111
+ }
112
+ export {
113
+ DummyThreadNetworkCommissioningServer
114
+ };
115
+ //# sourceMappingURL=DummyThreadNetworkCommissioningServer.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/examples/cluster/DummyThreadNetworkCommissioningServer.ts"],
4
+ "sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GeneralCommissioningBehavior } from \"@project-chip/matter.js/behavior/definitions/general-commissioning\";\nimport {\n AddOrUpdateThreadNetworkRequest,\n ConnectNetworkRequest,\n NetworkCommissioningBehavior,\n RemoveNetworkRequest,\n ReorderNetworkRequest,\n ScanNetworksRequest,\n ScanNetworksResponse,\n} from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { ByteArray } from \"@project-chip/matter.js/util\";\n\nconst firstNetworkId = new ByteArray(32);\n\n/**\n * This represents a Dummy version of a Wifi Network Commissioning Cluster Server without real Wifi related logic, beside\n * returning some values provided as CLI parameters. This dummy implementation is only there for tests/as showcase for BLE\n * commissioning of a device.\n */\nexport class DummyThreadNetworkCommissioningServer extends NetworkCommissioningBehavior.with(\n NetworkCommissioning.Feature.ThreadNetworkInterface,\n) {\n override scanNetworks({ breadcrumb }: ScanNetworksRequest): ScanNetworksResponse {\n console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${breadcrumb}`);\n\n // Simulate successful scan\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n\n const threadScanResults = [\n {\n panId: this.endpoint.env.vars.number(\"ble.thread.panId\"),\n extendedPanId: BigInt(this.endpoint.env.vars.string(\"ble.thread.extendedPanId\")),\n networkName: this.endpoint.env.vars.string(\"ble.thread.networkName\"),\n channel: this.endpoint.env.vars.number(\"ble.thread.channel\"),\n version: 130,\n extendedAddress: ByteArray.fromString(\n (this.endpoint.env.vars.string(\"ble.thread.address\") ?? \"000000000000\").toLowerCase(),\n ),\n rssi: -50,\n lqi: 50,\n },\n ];\n console.log(Logger.toJSON(threadScanResults));\n\n return {\n networkingStatus,\n threadScanResults,\n };\n }\n\n override addOrUpdateThreadNetwork({ operationalDataset, breadcrumb }: AddOrUpdateThreadNetworkRequest) {\n console.log(\n `---> addOrUpdateWiFiNetwork called on NetworkCommissioning cluster: ${operationalDataset.toHex()} ${breadcrumb}`,\n );\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n\n override removeNetwork({ networkId, breadcrumb }: RemoveNetworkRequest) {\n console.log(`---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n\n override async connectNetwork({ networkId, breadcrumb }: ConnectNetworkRequest) {\n console.log(`---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n this.state.networks[0].connected = true;\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n this.state.lastConnectErrorValue = null;\n\n // Announce operational in IP network\n const device = this.session.context;\n await device.startAnnouncement();\n\n return {\n networkingStatus,\n errorValue: null,\n };\n }\n\n override reorderNetwork({ networkId, networkIndex, breadcrumb }: ReorderNetworkRequest) {\n console.log(\n `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`,\n );\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n}\n"],
5
+ "mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,oCAAoC;AAC7C;AAAA,EAGI;AAAA,OAKG;AACP,SAAS,4BAA4B;AACrC,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAE1B,MAAM,iBAAiB,IAAI,UAAU,EAAE;A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AM,8BAA8B,KAAK,MAAM,IAAI,4BAA4B;AAC/E,kCAA4B,MAAM,aAAa;AAAA,IACnD;AAEA,UAAM,mBAAmB,qBAAqB,2BAA2B;AACzE,SAAK,MAAM,uBAAuB;AAElC,WAAO;AAAA,MACH;AAAA,MACA,cAAc;AAAA,IAClB;AAAA,EACJ;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { GeneralCommissioningBehavior } from "@project-chip/matter.js/behavior/definitions/general-commissioning";
7
+ import {
8
+ NetworkCommissioningBehavior
9
+ } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
10
+ import { NetworkCommissioning } from "@project-chip/matter.js/cluster";
11
+ import { ByteArray } from "@project-chip/matter.js/util";
12
+ const firstNetworkId = new ByteArray(32);
13
+ class DummyWifiNetworkCommissioningServer extends NetworkCommissioningBehavior.with(
14
+ NetworkCommissioning.Feature.WiFiNetworkInterface
15
+ ) {
16
+ scanNetworks({ ssid, breadcrumb }) {
17
+ console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${ssid?.toHex()} ${breadcrumb}`);
18
+ if (breadcrumb !== void 0) {
19
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
20
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
21
+ }
22
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
23
+ this.state.lastNetworkingStatus = networkingStatus;
24
+ return {
25
+ networkingStatus,
26
+ wiFiScanResults: [
27
+ {
28
+ security: {
29
+ unencrypted: false,
30
+ wep: false,
31
+ wpaPersonal: false,
32
+ wpa2Personal: true,
33
+ wpa3Personal: true
34
+ },
35
+ ssid: ssid || ByteArray.fromString(this.endpoint.env.vars.get("ble.wifi.scanSsid") ?? "TestSSID"),
36
+ // Set a valid existing local Wi-Fi SSID here
37
+ bssid: ByteArray.fromString(
38
+ this.endpoint.env.vars.get("ble.wifi.scanBssid") ?? "00:00:00:00:00:00"
39
+ ),
40
+ channel: 1
41
+ }
42
+ ]
43
+ };
44
+ }
45
+ addOrUpdateWiFiNetwork({ ssid, credentials, breadcrumb }) {
46
+ console.log(
47
+ `---> addOrUpdateWiFiNetwork called on NetworkCommissioning cluster: ${ssid.toHex()} ${credentials.toHex()} ${breadcrumb}`
48
+ );
49
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
50
+ if (breadcrumb !== void 0) {
51
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
52
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
53
+ }
54
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
55
+ this.state.lastNetworkingStatus = networkingStatus;
56
+ this.state.lastNetworkId = firstNetworkId;
57
+ return {
58
+ networkingStatus,
59
+ networkIndex: 0
60
+ };
61
+ }
62
+ removeNetwork({ networkId, breadcrumb }) {
63
+ console.log(`---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
64
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
65
+ if (breadcrumb !== void 0) {
66
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
67
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
68
+ }
69
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
70
+ this.state.lastNetworkingStatus = networkingStatus;
71
+ this.state.lastNetworkId = firstNetworkId;
72
+ return {
73
+ networkingStatus,
74
+ networkIndex: 0
75
+ };
76
+ }
77
+ async connectNetwork({ networkId, breadcrumb }) {
78
+ console.log(`---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);
79
+ this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
80
+ if (breadcrumb !== void 0) {
81
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
82
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
83
+ }
84
+ this.state.networks[0].connected = true;
85
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
86
+ this.state.lastNetworkingStatus = networkingStatus;
87
+ this.state.lastNetworkId = firstNetworkId;
88
+ this.state.lastConnectErrorValue = null;
89
+ const device = this.session.context;
90
+ await device.startAnnouncement();
91
+ return {
92
+ networkingStatus,
93
+ errorValue: null
94
+ };
95
+ }
96
+ reorderNetwork({ networkId, networkIndex, breadcrumb }) {
97
+ console.log(
98
+ `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`
99
+ );
100
+ if (breadcrumb !== void 0) {
101
+ const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);
102
+ generalCommissioningCluster.state.breadcrumb = breadcrumb;
103
+ }
104
+ const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;
105
+ this.state.lastNetworkingStatus = networkingStatus;
106
+ return {
107
+ networkingStatus,
108
+ networkIndex: 0
109
+ };
110
+ }
111
+ }
112
+ export {
113
+ DummyWifiNetworkCommissioningServer
114
+ };
115
+ //# sourceMappingURL=DummyWifiNetworkCommissioningServer.js.map