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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/dist/esm/examples/BridgedDevicesNode.js +2 -3
  2. package/dist/esm/examples/BridgedDevicesNode.js.map +2 -2
  3. package/dist/esm/examples/BridgedDevicesNodeLegacy.js +14 -15
  4. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +2 -2
  5. package/dist/esm/examples/ComposedDeviceNode.js +2 -3
  6. package/dist/esm/examples/ComposedDeviceNode.js.map +2 -2
  7. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +15 -16
  8. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +2 -2
  9. package/dist/esm/examples/ControllerNode.js +2 -5
  10. package/dist/esm/examples/ControllerNode.js.map +2 -2
  11. package/dist/esm/examples/ControllerNodeLegacy.js +21 -22
  12. package/dist/esm/examples/ControllerNodeLegacy.js.map +2 -2
  13. package/dist/esm/examples/DeviceNode.js +2 -3
  14. package/dist/esm/examples/DeviceNode.js.map +2 -2
  15. package/dist/esm/examples/DeviceNodeFull.js +4 -8
  16. package/dist/esm/examples/DeviceNodeFull.js.map +2 -2
  17. package/dist/esm/examples/DeviceNodeFullLegacy.js +16 -18
  18. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +2 -2
  19. package/dist/esm/examples/IlluminatedRollerShade.js +1 -1
  20. package/dist/esm/examples/IlluminatedRollerShade.js.map +1 -1
  21. package/dist/esm/examples/LegacyStorageConverter.js +2 -3
  22. package/dist/esm/examples/LegacyStorageConverter.js.map +2 -2
  23. package/dist/esm/examples/LightDevice.js +1 -1
  24. package/dist/esm/examples/LightDevice.js.map +1 -1
  25. package/dist/esm/examples/MultiDeviceNode.js +2 -3
  26. package/dist/esm/examples/MultiDeviceNode.js.map +2 -2
  27. package/dist/esm/examples/MultiDeviceNodeLegacy.js +13 -14
  28. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +2 -2
  29. package/dist/esm/examples/SensorDeviceNode.js +2 -3
  30. package/dist/esm/examples/SensorDeviceNode.js.map +2 -2
  31. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +11 -8
  32. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +2 -2
  33. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +15 -11
  34. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +2 -2
  35. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js +12 -10
  36. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +2 -2
  37. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +8 -8
  38. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +2 -2
  39. package/dist/esm/tutorial/example01.js +1 -1
  40. package/dist/esm/tutorial/example01.js.map +1 -1
  41. package/dist/esm/tutorial/example02.js +1 -1
  42. package/dist/esm/tutorial/example02.js.map +1 -1
  43. package/dist/esm/tutorial/example03.js +1 -1
  44. package/dist/esm/tutorial/example03.js.map +1 -1
  45. package/dist/esm/tutorial/example04.js +1 -1
  46. package/dist/esm/tutorial/example04.js.map +1 -1
  47. package/dist/esm/tutorial/example05.js +1 -1
  48. package/dist/esm/tutorial/example05.js.map +1 -1
  49. package/package.json +8 -8
  50. package/src/examples/BridgedDevicesNode.ts +2 -3
  51. package/src/examples/BridgedDevicesNodeLegacy.ts +15 -16
  52. package/src/examples/ComposedDeviceNode.ts +2 -3
  53. package/src/examples/ComposedDeviceNodeLegacy.ts +15 -16
  54. package/src/examples/ControllerNode.ts +2 -6
  55. package/src/examples/ControllerNodeLegacy.ts +22 -23
  56. package/src/examples/DeviceNode.ts +2 -3
  57. package/src/examples/DeviceNodeFull.ts +5 -10
  58. package/src/examples/DeviceNodeFullLegacy.ts +16 -18
  59. package/src/examples/IlluminatedRollerShade.ts +1 -1
  60. package/src/examples/LegacyStorageConverter.ts +3 -3
  61. package/src/examples/LightDevice.ts +1 -1
  62. package/src/examples/MultiDeviceNode.ts +2 -3
  63. package/src/examples/MultiDeviceNodeLegacy.ts +15 -15
  64. package/src/examples/SensorDeviceNode.ts +2 -3
  65. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +11 -8
  66. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +15 -11
  67. package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +12 -10
  68. package/src/examples/cluster/MyFancyOwnFunctionality.ts +9 -9
  69. package/src/tsconfig.json +1 -1
  70. package/src/tutorial/example01.ts +1 -1
  71. package/src/tutorial/example02.ts +1 -1
  72. package/src/tutorial/example03.ts +1 -1
  73. package/src/tutorial/example04.ts +1 -1
  74. package/src/tutorial/example05.ts +1 -1
@@ -4,8 +4,8 @@
4
4
  * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- import "@project-chip/matter-node.js";
8
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
7
+ import { requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
8
+ import { Time } from "@project-chip/matter.js-general";
9
9
  import { BridgedDeviceBasicInformationServer } from "@project-chip/matter.js/behavior/definitions/bridged-device-basic-information";
10
10
  import { VendorId } from "@project-chip/matter.js/datatype";
11
11
  import { logEndpoint } from "@project-chip/matter.js/device";
@@ -15,7 +15,6 @@ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
15
15
  import { AggregatorEndpoint } from "@project-chip/matter.js/endpoints/AggregatorEndpoint";
16
16
  import { Environment, StorageService } from "@project-chip/matter.js/environment";
17
17
  import { ServerNode } from "@project-chip/matter.js/node";
18
- import { Time } from "@project-chip/matter.js/time";
19
18
  import { execSync } from "child_process";
20
19
  requireMinNodeVersion(16);
21
20
  const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } = await getConfiguration();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/BridgedDevicesNode.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 * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please\n * refer to the bridge 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 \"@project-chip/matter-node.js\";\n\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { BridgedDeviceBasicInformationServer } from \"@project-chip/matter.js/behavior/definitions/bridged-device-basic-information\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { AggregatorEndpoint } from \"@project-chip/matter.js/endpoints/AggregatorEndpoint\";\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\n/** Initialize configuration values */\nconst { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =\n await getConfiguration();\n\n/**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\nconst 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: AggregatorEndpoint.deviceType,\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 multiple endpoint to the node to make it a\n * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type\n * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore\n * the device on restart.\n *\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\nconst aggregator = new Endpoint(AggregatorEndpoint, { id: \"aggregator\" });\nawait server.add(aggregator);\n\nfor (let idx = 0; idx < isSocket.length; idx++) {\n const i = idx + 1;\n const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?\n\n const name = `OnOff ${isASocket ? \"Socket\" : \"Light\"} ${i}`;\n\n const endpoint = new Endpoint(\n isASocket\n ? // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server\n OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)\n : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),\n {\n id: `onoff-${i}`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name, // Main end user name for the device\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n },\n },\n );\n await aggregator.add(endpoint);\n\n /**\n * Register state change handlers and events of the endpoint for identify and onoff states to react to the commands.\n *\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n endpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic for ${name} ...`);\n });\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n}\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 */\nawait server.start();\n\n/**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/*\n If you want to dynamically add another device during runtime you can do so by doing the following:\n\n const name = `OnOff Light 3`;\n\n const endpoint = new Endpoint(OnOffLightDevice.with(BridgedDeviceBasicInformationServer), {\n id: `onoff-3`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name,\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-3`,\n reachable: true,\n },\n });\n await aggregator.add(endpoint);\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on3` : `off3`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n\n */\n\n/*\n To remove a device during runtime you can do so by doing the following:\n console.log(\"Removing Light 3 now!!\");\n\n await endpoint.close();\n\n This will automatically remove the endpoint from the bridge.\n */\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\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 isSocket = Array<boolean>();\n const numDevices = environment.vars.number(\"num\") || 2;\n if (await deviceStorage.has(\"isSocket\")) {\n console.log(`Device types found in storage. --type parameter is ignored.`);\n (await deviceStorage.get<Array<boolean>>(\"isSocket\")).forEach(type => isSocket.push(type));\n }\n for (let i = 1; i <= numDevices; i++) {\n if (isSocket[i - 1] !== undefined) continue;\n isSocket.push(environment.vars.string(`type${i}`) === \"socket\");\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await 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\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
- "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,2CAA2C;AACpD,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,S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: Apache-2.0\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. For information on how to add a composed device to a bridge please\n * refer to the bridge 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 { requireMinNodeVersion } from \"@project-chip/matter.js-nodejs\";\n\nimport { Time } from \"@project-chip/matter.js-general\";\nimport { BridgedDeviceBasicInformationServer } from \"@project-chip/matter.js/behavior/definitions/bridged-device-basic-information\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { AggregatorEndpoint } from \"@project-chip/matter.js/endpoints/AggregatorEndpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\n/** Initialize configuration values */\nconst { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =\n await getConfiguration();\n\n/**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\nconst 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: AggregatorEndpoint.deviceType,\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 multiple endpoint to the node to make it a\n * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type\n * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore\n * the device on restart.\n *\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\nconst aggregator = new Endpoint(AggregatorEndpoint, { id: \"aggregator\" });\nawait server.add(aggregator);\n\nfor (let idx = 0; idx < isSocket.length; idx++) {\n const i = idx + 1;\n const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?\n\n const name = `OnOff ${isASocket ? \"Socket\" : \"Light\"} ${i}`;\n\n const endpoint = new Endpoint(\n isASocket\n ? // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server\n OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)\n : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),\n {\n id: `onoff-${i}`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name, // Main end user name for the device\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n },\n },\n );\n await aggregator.add(endpoint);\n\n /**\n * Register state change handlers and events of the endpoint for identify and onoff states to react to the commands.\n *\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n endpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic for ${name} ...`);\n });\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n}\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 */\nawait server.start();\n\n/**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/*\n If you want to dynamically add another device during runtime you can do so by doing the following:\n\n const name = `OnOff Light 3`;\n\n const endpoint = new Endpoint(OnOffLightDevice.with(BridgedDeviceBasicInformationServer), {\n id: `onoff-3`,\n bridgedDeviceBasicInformation: {\n nodeLabel: name,\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-3`,\n reachable: true,\n },\n });\n await aggregator.add(endpoint);\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on3` : `off3`);\n console.log(`${name} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n\n */\n\n/*\n To remove a device during runtime you can do so by doing the following:\n console.log(\"Removing Light 3 now!!\");\n\n await endpoint.close();\n\n This will automatically remove the endpoint from the bridge.\n */\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\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 isSocket = Array<boolean>();\n const numDevices = environment.vars.number(\"num\") || 2;\n if (await deviceStorage.has(\"isSocket\")) {\n console.log(`Device types found in storage. --type parameter is ignored.`);\n (await deviceStorage.get<Array<boolean>>(\"isSocket\")).forEach(type => isSocket.push(type));\n }\n for (let i = 1; i <= numDevices; i++) {\n if (isSocket[i - 1] !== undefined) continue;\n isSocket.push(environment.vars.string(`type${i}`) === \"socket\");\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await 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\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,SAAS,6BAA6B;AAEtC,SAAS,YAAY;AACrB,SAAS,2CAA2C;AACpD,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,0BAA0B;AACnC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B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KAAK,YAAY,KAAK,OAAO,OAAO,CAAC,EAAE,MAAM,QAAQ;AAAA,EAClE;AAEA,QAAMC,cAAa;AACnB,QAAMC,cAAa;AACnB,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,QAAQ;AACrG,QAAMC,iBAAgB,YAAY,KAAK,OAAO,eAAe,KAAM,MAAM,cAAc,IAAI,iBAAiB,IAAI;AAEhH,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAM;AACnG,QAAMC,eAAc,qBAAqBN,YAAW,WAAW,OAAO;AACtE,QAAMO,aAAY,YAAY,KAAK,OAAO,WAAW,KAAM,MAAM,cAAc,IAAI,aAAa,KAAM;AAEtG,QAAMC,QAAO,YAAY,KAAK,OAAO,MAAM,KAAK;AAEhD,QAAMC,YACF,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAGvG,QAAM,cAAc,IAAI;AAAA,IACpB,UAAAN;AAAA,IACA,eAAAC;AAAA,IACA,UAAUC;AAAA,IACV,WAAWE;AAAA,IACX,UAAAP;AAAA,IACA,UAAUS;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACH,UAAAT;AAAA,IACA,YAAAC;AAAA,IACA,YAAAC;AAAA,IACA,UAAAC;AAAA,IACA,eAAAC;AAAA,IACA,UAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAAC;AAAA,IACA,MAAAC;AAAA,IACA,UAAAC;AAAA,EACJ;AACJ;",
6
6
  "names": ["isSocket", "deviceName", "vendorName", "passcode", "discriminator", "vendorId", "productName", "productId", "port", "uniqueId"]
7
7
  }
@@ -4,45 +4,44 @@
4
4
  * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
- import { VendorId } from "@project-chip/matter-node.js/datatype";
9
- import { Aggregator, DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter-node.js/device";
10
- import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
11
- import { QrCode } from "@project-chip/matter-node.js/schema";
12
- import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
13
- import { Time } from "@project-chip/matter-node.js/time";
14
7
  import {
8
+ StorageBackendDisk,
15
9
  commandExecutor,
16
10
  getIntParameter,
17
11
  getParameter,
18
12
  hasParameter,
19
13
  requireMinNodeVersion
20
- } from "@project-chip/matter-node.js/util";
14
+ } from "@project-chip/matter.js-nodejs";
15
+ import { CommissioningServer, MatterServer } from "@project-chip/matter.js";
16
+ import { LogFormat, LogLevel, Logger, StorageManager, Time } from "@project-chip/matter.js-general";
17
+ import { VendorId } from "@project-chip/matter.js/datatype";
18
+ import { Aggregator, DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter.js/device";
19
+ import { QrCode } from "@project-chip/matter.js/schema";
21
20
  const logger = Logger.get("Device");
22
21
  requireMinNodeVersion(16);
23
22
  switch (getParameter("loglevel")) {
24
23
  case "fatal":
25
- Logger.defaultLogLevel = Level.FATAL;
24
+ Logger.defaultLogLevel = LogLevel.FATAL;
26
25
  break;
27
26
  case "error":
28
- Logger.defaultLogLevel = Level.ERROR;
27
+ Logger.defaultLogLevel = LogLevel.ERROR;
29
28
  break;
30
29
  case "warn":
31
- Logger.defaultLogLevel = Level.WARN;
30
+ Logger.defaultLogLevel = LogLevel.WARN;
32
31
  break;
33
32
  case "info":
34
- Logger.defaultLogLevel = Level.INFO;
33
+ Logger.defaultLogLevel = LogLevel.INFO;
35
34
  break;
36
35
  }
37
36
  switch (getParameter("logformat")) {
38
37
  case "plain":
39
- Logger.format = Format.PLAIN;
38
+ Logger.format = LogFormat.PLAIN;
40
39
  break;
41
40
  case "html":
42
- Logger.format = Format.HTML;
41
+ Logger.format = LogFormat.HTML;
43
42
  break;
44
43
  default:
45
- if (process.stdin?.isTTY) Logger.format = Format.ANSI;
44
+ if (process.stdin?.isTTY) Logger.format = LogFormat.ANSI;
46
45
  }
47
46
  const storageLocation = getParameter("store") ?? ".device-node";
48
47
  const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/BridgedDevicesNodeLegacy.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 device bridge that exposed multiple devices.\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 { VendorId } from \"@project-chip/matter-node.js/datatype\";\nimport { Aggregator, 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\";\n\nconst logger = Logger.get(\"Device\");\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 BridgedDevice {\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\n const deviceStorage = storageManager.createContext(\"Device\");\n\n const deviceName = \"Matter Bridge device\";\n const deviceType = DeviceTypes.AGGREGATOR.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n uniqueid: uniqueId,\n });\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 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 /**\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 aggregator = new Aggregator();\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n const name = `OnOff ${onOffDevice instanceof OnOffPluginUnitDevice ? \"Socket\" : \"Light\"} ${i}`;\n aggregator.addBridgedDevice(onOffDevice, {\n nodeLabel: name, // Main end user name for the device\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n });\n }\n\n commissioningServer.addDevice(aggregator);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\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 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 }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new BridgedDevice();\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.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
5
- "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAoBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,gBAAgB;AACzB,SAAS,YAAY,aAAa,kBAAkB,6BAA6B;AACjF,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;AAEP,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBA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,aAAa,uBAAuB,mBAAmB;AASlE,UAAM,KAAK,aAAa,MAAM;AAS9B,WAAO,KAAK,WAAW;AACvB,QAAI,CAAC,oBAAoB,eAAe,GAAG;AACvC,YAAM,cAAc,oBAAoB,eAAe;AACvD,YAAM,EAAE,eAAe,kBAAkB,IAAI;AAE7C,cAAQ,IAAI,OAAO,IAAI,aAAa,CAAC;AACrC,cAAQ;AAAA,QACJ,gFAAgF,aAAa;AAAA,MACjG;AACA,cAAQ,IAAI,wBAAwB,iBAAiB,EAAE;AAAA,IAC3D,OAAO;AACH,cAAQ,IAAI,wEAAwE;AAAA,IACxF;AAAA,EACJ;AAAA,EAEA,MAAM,OAAO;AACT,UAAM,KAAK,cAAc,MAAM;AAAA,EACnC;AACJ;AAEA,MAAM,SAAS,IAAI,cAAc;AACjC,OACK,MAAM,EACN,KAAK,MAAM;AAEZ,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAEpC,QAAQ,GAAG,UAAU,MAAM;AAEvB,SACK,KAAK,EACL,KAAK,MAAM;AAER,YAAQ,MAAM;AACd,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
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 device bridge that exposed multiple devices.\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 {\n StorageBackendDisk,\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter.js-nodejs\";\n\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter.js\";\nimport { LogFormat, LogLevel, Logger, StorageManager, Time } from \"@project-chip/matter.js-general\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\nimport { Aggregator, DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter.js/device\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\n\nconst logger = Logger.get(\"Device\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = LogLevel.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = LogLevel.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = LogLevel.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = LogLevel.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = LogFormat.PLAIN;\n break;\n case \"html\":\n Logger.format = LogFormat.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = LogFormat.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 BridgedDevice {\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\n const deviceStorage = storageManager.createContext(\"Device\");\n\n const deviceName = \"Matter Bridge device\";\n const deviceType = DeviceTypes.AGGREGATOR.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n uniqueid: uniqueId,\n });\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 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 /**\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 aggregator = new Aggregator();\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n const name = `OnOff ${onOffDevice instanceof OnOffPluginUnitDevice ? \"Socket\" : \"Light\"} ${i}`;\n aggregator.addBridgedDevice(onOffDevice, {\n nodeLabel: name, // Main end user name for the device\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n });\n }\n\n commissioningServer.addDevice(aggregator);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\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 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 }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new BridgedDevice();\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.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAoBA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,qBAAqB,oBAAoB;AAClD,SAAS,WAAW,UAAU,QAAQ,gBAAgB,YAAY;AAClE,SAAS,gBAAgB;AACzB,SAAS,YAAY,aAAa,kBAAkB,6BAA6B;AACjF,SAAS,cAAc;AAEvB,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AACR;AAEA,QAAQ,aAAa,WAAW,GAAG;AAAA,EAC/B,KAAK;AACD,WAAO,SAAS,UAAU;AAC1B;AAAA,EACJ,KAAK;AACD,WAAO,SAAS,UAAU;AAC1B;AAAA,EACJ;AACI,QAAI,QAAQ,OAAO,MAAO,QAAO,SAAS,UAAU;AAC5D;AAEA,MAAM,kBAAkB,aAAa,OAAO,KAAK;AACjD,MAAM,UAAU,IAAI,mBAAmB,iBAAiB,aAAa,cAAc,CAAC;AACpF,OAAO,KAAK,qBAAqB,eAAe,cAAc;AAC9D,OAAO;AAAA,EACH;AACJ;AAEA,MAAM,cAAc;AAAA,EACR;AAAA,EAER,MAAM,QAAQ;AACV,WAAO,KAAK,aAAa;AASzB,UAAM,iBAAiB,IAAI,eAAe,OAAO;AACjD,UAAM,eAAe,WAAW;AAahC,UAAM,gBAAgB,eAAe,cAAc,QAAQ;AA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@@ -4,8 +4,8 @@
4
4
  * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- import "@project-chip/matter-node.js";
8
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
7
+ import { requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
8
+ import { Time } from "@project-chip/matter.js-general";
9
9
  import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
10
10
  import { logEndpoint } from "@project-chip/matter.js/device";
11
11
  import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
@@ -13,7 +13,6 @@ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlug
13
13
  import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
14
14
  import { Environment, StorageService } from "@project-chip/matter.js/environment";
15
15
  import { ServerNode } from "@project-chip/matter.js/node";
16
- import { Time } from "@project-chip/matter.js/time";
17
16
  import { execSync } from "child_process";
18
17
  requireMinNodeVersion(16);
19
18
  const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } = await getConfiguration();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/ComposedDeviceNode.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 * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please\n * refer to the bridge 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 \"@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 { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\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\n/** Initialize configuration values */\nconst { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =\n await getConfiguration();\n\n/**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\nconst 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(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),\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 multiple endpoint to the node to make it a\n * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type\n * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore\n * the device on restart.\n *\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\nfor (let idx = 0; idx < isSocket.length; idx++) {\n const i = idx + 1;\n const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?\n const endpoint = new Endpoint(isASocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: `onoff-${i}` });\n await server.add(endpoint);\n\n /**\n * Register state change handlers of the endpoint for identify and onoff states to react to the commands.\n *\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n endpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic for sub device ${i}, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic for sub device ${i}...`);\n });\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`OnOff ${i} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n}\n\n/**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\nlogEndpoint(EndpointServer.forEndpoint(server));\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 */\nawait server.run();\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/**\n * Defines a shell command from an environment variable and execute it and log the response\n */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\nasync function getConfiguration() {\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 isSocket = Array<boolean>();\n const numDevices = environment.vars.number(\"num\") || 2;\n if (await deviceStorage.has(\"isSocket\")) {\n console.log(`Device types found in storage. --type parameter is ignored.`);\n (await deviceStorage.get<Array<boolean>>(\"isSocket\")).forEach(type => isSocket.push(type));\n }\n for (let i = 1; i < numDevices; i++) {\n if (isSocket[i - 1] !== undefined) continue;\n isSocket.push(environment.vars.string(`type${i}`) === \"socket\");\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await 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\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
- "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAGxB,MAAM,EAAE,UAAU,YAAY,YAAY,UAAU,eAAe,UAAU,aAAa,WAAW,MAAM,SAAS,IAChH,MAAM,iBAAiB;AAK3B,MAAM,SAAS,MAAM,W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K,OAAO,MAAM,KAAK;AAEhD,QAAMC,YACF,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAGvG,QAAM,cAAc,IAAI;AAAA,IACpB,UAAAN;AAAA,IACA,eAAAC;AAAA,IACA,UAAUC;AAAA,IACV,WAAWE;AAAA,IACX,UAAAP;AAAA,IACA,UAAUS;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACH,UAAAT;AAAA,IACA,YAAAC;AAAA,IACA,YAAAC;AAAA,IACA,UAAAC;AAAA,IACA,eAAAC;AAAA,IACA,UAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAAC;AAAA,IACA,MAAAC;AAAA,IACA,UAAAC;AAAA,EACJ;AACJ;",
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 * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. For information on how to add a composed device to a bridge please\n * refer to the bridge 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 { requireMinNodeVersion } from \"@project-chip/matter.js-nodejs\";\n\nimport { Time } from \"@project-chip/matter.js-general\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\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 { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\n/** Initialize configuration values */\nconst { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } =\n await getConfiguration();\n\n/**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\nconst 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(isSocket[0] ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),\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 multiple endpoint to the node to make it a\n * composed device. This example uses the OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type\n * parameter. It also assigns each Endpoint a unique ID to store the endpoint number for it in the storage to restore\n * the device on restart.\n *\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\nfor (let idx = 0; idx < isSocket.length; idx++) {\n const i = idx + 1;\n const isASocket = isSocket[idx]; // Is the Device we add a Socket or a Light?\n const endpoint = new Endpoint(isASocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: `onoff-${i}` });\n await server.add(endpoint);\n\n /**\n * Register state change handlers of the endpoint for identify and onoff states to react to the commands.\n *\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n endpoint.events.identify.startIdentifying.on(() => {\n console.log(`Run identify logic for sub device ${i}, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic for sub device ${i}...`);\n });\n\n endpoint.events.onOff.onOff$Changed.on(value => {\n executeCommand(value ? `on${i}` : `off${i}`);\n console.log(`OnOff ${i} is now ${value ? \"ON\" : \"OFF\"}`);\n });\n}\n\n/**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\nlogEndpoint(EndpointServer.forEndpoint(server));\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 */\nawait server.run();\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/**\n * Defines a shell command from an environment variable and execute it and log the response\n */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\nasync function getConfiguration() {\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 isSocket = Array<boolean>();\n const numDevices = environment.vars.number(\"num\") || 2;\n if (await deviceStorage.has(\"isSocket\")) {\n console.log(`Device types found in storage. --type parameter is ignored.`);\n (await deviceStorage.get<Array<boolean>>(\"isSocket\")).forEach(type => isSocket.push(type));\n }\n for (let i = 1; i < numDevices; i++) {\n if (isSocket[i - 1] !== undefined) continue;\n isSocket.push(environment.vars.string(`type${i}`) === \"socket\");\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await 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\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,SAAS,6BAA6B;AAEtC,SAAS,YAAY;AACrB,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAGxB,MAAM,EAAE,UAAU,YAAY,YAAY,UAAU,eAAe,UAAU,aAAa,WAAW,MAAM,SAAS,IAChH,MAAM,iBAAiB;AAK3B,MAAM,SAAS,MAAM,WAAW,OAAO;AAAA;AAAA,EAEnC,IAAI;AAAA;AAAA;AAAA,EAIJ,SAAS;AAAA,IACL;AAAA,EACJ;AAAA;AAAA;AAAA,EAIA,eAAe;AAAA,IACX;AAAA,IACA;AAAA,EACJ;AAAA;AAAA;AAAA,EAIA,oBAAoB;AAAA,IAChB,MAAM;AAAA,IACN,YAAY,aAAa,SAAS,CAAC,IAAI,sBAAsB,aAAa,iBAAiB,UAAU;AAAA,EACzG;AAAA;AAAA;AAAA,EAIA,kBAAkB;AAAA,IAC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,IACA,YAAAC;AAAA,IACA,UAAAC;AAAA,IACA,eAAAC;AAAA,IACA,UAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAAC;AAAA,IACA,MAAAC;AAAA,IACA,UAAAC;AAAA,EACJ;AACJ;",
6
6
  "names": ["isSocket", "deviceName", "vendorName", "passcode", "discriminator", "vendorId", "productName", "productId", "port", "uniqueId"]
7
7
  }
@@ -4,45 +4,44 @@
4
4
  * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
- import { VendorId } from "@project-chip/matter-node.js/datatype";
9
- import { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter-node.js/device";
10
- import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
11
- import { QrCode } from "@project-chip/matter-node.js/schema";
12
- import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
13
- import { Time } from "@project-chip/matter-node.js/time";
14
7
  import {
15
8
  commandExecutor,
16
9
  getIntParameter,
17
10
  getParameter,
18
11
  hasParameter,
19
- requireMinNodeVersion
20
- } from "@project-chip/matter-node.js/util";
12
+ requireMinNodeVersion,
13
+ StorageBackendDisk
14
+ } from "@project-chip/matter.js-nodejs";
15
+ import { CommissioningServer, MatterServer } from "@project-chip/matter.js";
16
+ import { LogFormat, Logger, LogLevel, StorageManager, Time } from "@project-chip/matter.js-general";
17
+ import { VendorId } from "@project-chip/matter.js/datatype";
18
+ import { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter.js/device";
19
+ import { QrCode } from "@project-chip/matter.js/schema";
21
20
  const logger = Logger.get("Device");
22
21
  requireMinNodeVersion(16);
23
22
  switch (getParameter("loglevel")) {
24
23
  case "fatal":
25
- Logger.defaultLogLevel = Level.FATAL;
24
+ Logger.defaultLogLevel = LogLevel.FATAL;
26
25
  break;
27
26
  case "error":
28
- Logger.defaultLogLevel = Level.ERROR;
27
+ Logger.defaultLogLevel = LogLevel.ERROR;
29
28
  break;
30
29
  case "warn":
31
- Logger.defaultLogLevel = Level.WARN;
30
+ Logger.defaultLogLevel = LogLevel.WARN;
32
31
  break;
33
32
  case "info":
34
- Logger.defaultLogLevel = Level.INFO;
33
+ Logger.defaultLogLevel = LogLevel.INFO;
35
34
  break;
36
35
  }
37
36
  switch (getParameter("logformat")) {
38
37
  case "plain":
39
- Logger.format = Format.PLAIN;
38
+ Logger.format = LogFormat.PLAIN;
40
39
  break;
41
40
  case "html":
42
- Logger.format = Format.HTML;
41
+ Logger.format = LogFormat.HTML;
43
42
  break;
44
43
  default:
45
- if (process.stdin?.isTTY) Logger.format = Format.ANSI;
44
+ if (process.stdin?.isTTY) Logger.format = LogFormat.ANSI;
46
45
  }
47
46
  const storageLocation = getParameter("store") ?? ".device-node";
48
47
  const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/ComposedDeviceNodeLegacy.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 { VendorId } from \"@project-chip/matter-node.js/datatype\";\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\";\n\nconst logger = Logger.get(\"Device\");\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 ComposedDevice {\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\n const deviceStorage = storageManager.createContext(\"Device\");\n\n if (deviceStorage.has(\"isSocket\")) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(\"isSocket\", getParameter(\"type\") === \"socket\");\n const deviceName = \"Matter composed device\";\n const deviceType =\n getParameter(\"type\") === \"socket\" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\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 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 /**\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 numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n commissioningServer.addDevice(onOffDevice);\n }\n\n await this.matterServer.addCommissioningServer(commissioningServer);\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 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 }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new ComposedDevice();\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.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
5
- "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,gBAAgB;AACzB,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;AAEP,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,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,WAAO,SAAS,OAAO;AACvB;AAAA,EACJ,KAAK;AACD,WAAO,SAAS,OAAO;AACvB;AAAA,EACJ;AACI,QAAI,QAAQ,OAAO,MAAO,QAAO,SAAS,OAAO;AACzD;AAEA,MAAM,kBAAkB,aAAa,OAAO,KAAK;AACjD,MAAM,UAAU,IAAI,mBAAmB,iBAAiB,aAAa,cAAc,CAAC;AACpF,OAAO,KAAK,qBAAqB,eAAe,cAAc;AAC9D,OAAO;AAAA,EACH;AACJ;AAEA,MAAM,eAAe;AAAA,EACT;AAAA,EAER,MAAM,QAAQ;AACV,WAAO,KAAK,aAAa;AASzB,UAAM,iBAAiB,IAAI,eAA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AAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
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 {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n StorageBackendDisk,\n} from \"@project-chip/matter.js-nodejs\";\n\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter.js\";\nimport { LogFormat, Logger, LogLevel, StorageManager, Time } from \"@project-chip/matter.js-general\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\nimport { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter.js/device\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\n\nconst logger = Logger.get(\"Device\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = LogLevel.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = LogLevel.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = LogLevel.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = LogLevel.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = LogFormat.PLAIN;\n break;\n case \"html\":\n Logger.format = LogFormat.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = LogFormat.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 ComposedDevice {\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\n const deviceStorage = storageManager.createContext(\"Device\");\n\n if (deviceStorage.has(\"isSocket\")) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(\"isSocket\", getParameter(\"type\") === \"socket\");\n const deviceName = \"Matter composed device\";\n const deviceType =\n getParameter(\"type\") === \"socket\" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\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 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 /**\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 numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n commissioningServer.addDevice(onOffDevice);\n }\n\n await this.matterServer.addCommissioningServer(commissioningServer);\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 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 }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new ComposedDevice();\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.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,qBAAqB,oBAAoB;AAClD,SAAS,WAAW,QAAQ,UAAU,gBAAgB,YAAY;AAClE,SAAS,gBAAgB;AACzB,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAAS,cAAc;AAEvB,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,SAAS;AAClC;AAAA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B,eAAe;AACvD,YAAM,EAAE,eAAe,kBAAkB,IAAI;AAE7C,cAAQ,IAAI,OAAO,IAAI,aAAa,CAAC;AACrC,cAAQ;AAAA,QACJ,gFAAgF,aAAa;AAAA,MACjG;AACA,cAAQ,IAAI,wBAAwB,iBAAiB,EAAE;AAAA,IAC3D,OAAO;AACH,cAAQ,IAAI,wEAAwE;AAAA,IACxF;AAAA,EACJ;AAAA,EAEA,MAAM,OAAO;AACT,UAAM,KAAK,cAAc,MAAM;AAAA,EACnC;AACJ;AAEA,MAAM,SAAS,IAAI,eAAe;AAClC,OACK,MAAM,EACN,KAAK,MAAM;AAEZ,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAEpC,QAAQ,GAAG,UAAU,MAAM;AAEvB,SACK,KAAK,EACL,KAAK,MAAM;AAER,YAAQ,MAAM;AACd,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
6
6
  "names": []
7
7
  }
@@ -4,10 +4,10 @@
4
4
  * Copyright 2022-2024 Matter.js Authors
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- import "@project-chip/matter-node.js";
7
+ import { requireMinNodeVersion } from "@project-chip/matter.js-nodejs";
8
8
  import { BleNode } from "@project-chip/matter-node-ble.js/ble";
9
- import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
10
9
  import { CommissioningController } from "@project-chip/matter.js";
10
+ import { Logger, singleton, Time } from "@project-chip/matter.js-general";
11
11
  import { Ble } from "@project-chip/matter.js/ble";
12
12
  import {
13
13
  BasicInformationCluster,
@@ -18,10 +18,7 @@ import {
18
18
  import { NodeId } from "@project-chip/matter.js/datatype";
19
19
  import { NodeStateInformation } from "@project-chip/matter.js/device";
20
20
  import { Environment, StorageService } from "@project-chip/matter.js/environment";
21
- import { Logger } from "@project-chip/matter.js/log";
22
21
  import { ManualPairingCodeCodec } from "@project-chip/matter.js/schema";
23
- import { Time } from "@project-chip/matter.js/time";
24
- import { singleton } from "@project-chip/matter.js/util";
25
22
  const logger = Logger.get("Controller");
26
23
  requireMinNodeVersion(16);
27
24
  const environment = Environment.default;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/ControllerNode.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 * 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\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { CommissioningController, NodeCommissioningOptions } from \"@project-chip/matter.js\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport {\n BasicInformationCluster,\n ClusterClientObj,\n DescriptorCluster,\n GeneralCommissioning,\n OnOff,\n} from \"@project-chip/matter.js/cluster\";\nimport { NodeId } from \"@project-chip/matter.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter.js/device\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { CommissioningOptions } from \"@project-chip/matter.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter.js/schema\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { singleton } from \"@project-chip/matter.js/util\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\nconst environment = Environment.default;\n\nif (environment.vars.get(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageService = environment.get(StorageService);\n\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nlogger.info(\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\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\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 = (await storageService.open(\"controller\")).createContext(\"data\");\n const ip = (await controllerStorage.has(\"ip\"))\n ? await controllerStorage.get<string>(\"ip\")\n : environment.vars.string(\"ip\");\n const port = (await controllerStorage.has(\"port\"))\n ? await controllerStorage.get<number>(\"port\")\n : environment.vars.number(\"port\");\n const uniqueId = (await controllerStorage.has(\"uniqueid\"))\n ? await controllerStorage.get<string>(\"uniqueid\")\n : (environment.vars.string(\"uniqueid\") ?? Time.nowMs().toString());\n await controllerStorage.set(\"uniqueid\", uniqueId);\n\n const pairingCode = environment.vars.string(\"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 environment.vars.number(\"longDiscriminator\") ??\n (await controllerStorage.get(\"longDiscriminator\", 3840));\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = environment.vars.number(\"pin\") ?? (await 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 (environment.vars.get(\"ble\")) {\n ble = true;\n const wifiSsid = environment.vars.string(\"ble-wifi-ssid\");\n const wifiCredentials = environment.vars.string(\"ble-wifi-credentials\");\n const threadNetworkName = environment.vars.string(\"ble-thread-networkname\");\n const threadOperationalDataset = environment.vars.string(\"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 commissioningController = new CommissioningController({\n environment: {\n environment,\n id: uniqueId,\n },\n autoConnect: false,\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 await commissioningController.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 ... ${Logger.toJSON(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(environment.vars.number(\"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: ClusterClientObj<OnOff.Complete> | undefined = devices[0].getClusterClient(OnOff.Complete);\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"],
5
- "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,eAAe;AACxB,SAAS,6BAA6B;AACtC,SAAS,+BAAyD;AAClE,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,cAAc;AAEvB,SAAS,8BAA8B;AACvC,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAE1B,MAAM,SAAS,OAAO,IAAI,YAAY;AAEtC,sBAAsB,EAAE;AAExB,MAAM,cAAc,YAAY;AAEhC,IAAI,YAAY,KAAK,IAAI,KAAK,GAAG;AAE7B,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,YAAY,KAAK,OAAO,YAAY;AAAA,IAC/C,CAAC;AAAA,EACT;AACJ;AAEA,MAAM,iBAAiB,YAAY,IAAI,cAAc;AAErD,QAAQ,IAAI,qBAAqB,eAA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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;",
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 * 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 { requireMinNodeVersion } from \"@project-chip/matter.js-nodejs\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { CommissioningController, NodeCommissioningOptions } from \"@project-chip/matter.js\";\nimport { Logger, singleton, Time } from \"@project-chip/matter.js-general\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport {\n BasicInformationCluster,\n ClusterClientObj,\n DescriptorCluster,\n GeneralCommissioning,\n OnOff,\n} from \"@project-chip/matter.js/cluster\";\nimport { NodeId } from \"@project-chip/matter.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter.js/device\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { CommissioningOptions } from \"@project-chip/matter.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter.js/schema\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\nconst environment = Environment.default;\n\nif (environment.vars.get(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageService = environment.get(StorageService);\n\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nlogger.info(\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\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\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 = (await storageService.open(\"controller\")).createContext(\"data\");\n const ip = (await controllerStorage.has(\"ip\"))\n ? await controllerStorage.get<string>(\"ip\")\n : environment.vars.string(\"ip\");\n const port = (await controllerStorage.has(\"port\"))\n ? await controllerStorage.get<number>(\"port\")\n : environment.vars.number(\"port\");\n const uniqueId = (await controllerStorage.has(\"uniqueid\"))\n ? await controllerStorage.get<string>(\"uniqueid\")\n : (environment.vars.string(\"uniqueid\") ?? Time.nowMs().toString());\n await controllerStorage.set(\"uniqueid\", uniqueId);\n\n const pairingCode = environment.vars.string(\"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 environment.vars.number(\"longDiscriminator\") ??\n (await controllerStorage.get(\"longDiscriminator\", 3840));\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = environment.vars.number(\"pin\") ?? (await 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 (environment.vars.get(\"ble\")) {\n ble = true;\n const wifiSsid = environment.vars.string(\"ble-wifi-ssid\");\n const wifiCredentials = environment.vars.string(\"ble-wifi-credentials\");\n const threadNetworkName = environment.vars.string(\"ble-thread-networkname\");\n const threadOperationalDataset = environment.vars.string(\"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 commissioningController = new CommissioningController({\n environment: {\n environment,\n id: uniqueId,\n },\n autoConnect: false,\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 await commissioningController.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 ... ${Logger.toJSON(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(environment.vars.number(\"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: ClusterClientObj<OnOff.Complete> | undefined = devices[0].getClusterClient(OnOff.Complete);\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"],
5
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,SAAS,6BAA6B;AAEtC,SAAS,eAAe;AACxB,SAAS,+BAAyD;AAClE,SAAS,QAAQ,WAAW,YAAY;AACxC,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,aAAa,sBAAsB;AAE5C,SAAS,8BAA8B;AAEvC,MAAM,SAAS,OAAO,IAAI,YAAY;AAEtC,sBAAsB,EAAE;AAExB,MAAM,cAAc,YAAY;AAEhC,IAAI,YAAY,KAAK,IAAI,KAAK,GAAG;AAE7B,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,YAAY,KAAK,OAAO,YAAY;AAAA,IAC/C,CAAC;AAAA,EACT;AACJ;AAEA,MAAM,iBAAiB,YAAY,IAAI,cAAc;AAErD,QAAQ,IAAI,qBAAqB,eAAe,QAAQ,cAAc;AACtE,OAAO;AAAA,EACH;AACJ;AAEA,MAAM,eAAe;AAAA,EACjB,MAAM,QAAQ;AACV,WAAO,KAAK,gCAAgC;AAa5C,UAAM,qBAAqB,MAAM,eAAe,KAAK,YAAY,GAAG,cAAc,MAAM;AACxF,UAAM,K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