@project-chip/matter-node.js-examples 0.11.0-alpha.0-20240909-b3b29745 → 0.11.0-alpha.0-20240911-db8f7c80
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/esm/examples/BridgedDevicesNode.js +2 -3
- package/dist/esm/examples/BridgedDevicesNode.js.map +2 -2
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js +14 -15
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNode.js +2 -3
- package/dist/esm/examples/ComposedDeviceNode.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js +15 -16
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ControllerNode.js +2 -5
- package/dist/esm/examples/ControllerNode.js.map +2 -2
- package/dist/esm/examples/ControllerNodeLegacy.js +21 -22
- package/dist/esm/examples/ControllerNodeLegacy.js.map +2 -2
- package/dist/esm/examples/DeviceNode.js +2 -3
- package/dist/esm/examples/DeviceNode.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFull.js +4 -8
- package/dist/esm/examples/DeviceNodeFull.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFullLegacy.js +16 -18
- package/dist/esm/examples/DeviceNodeFullLegacy.js.map +2 -2
- package/dist/esm/examples/IlluminatedRollerShade.js +1 -1
- package/dist/esm/examples/IlluminatedRollerShade.js.map +1 -1
- package/dist/esm/examples/LegacyStorageConverter.js +2 -3
- package/dist/esm/examples/LegacyStorageConverter.js.map +2 -2
- package/dist/esm/examples/LightDevice.js +1 -1
- package/dist/esm/examples/LightDevice.js.map +1 -1
- package/dist/esm/examples/MultiDeviceNode.js +2 -3
- package/dist/esm/examples/MultiDeviceNode.js.map +2 -2
- package/dist/esm/examples/MultiDeviceNodeLegacy.js +13 -14
- package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/SensorDeviceNode.js +2 -3
- package/dist/esm/examples/SensorDeviceNode.js.map +2 -2
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +11 -8
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +2 -2
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +15 -11
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +2 -2
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js +12 -10
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +2 -2
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +8 -8
- package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +2 -2
- package/dist/esm/tutorial/example01.js +1 -1
- package/dist/esm/tutorial/example01.js.map +1 -1
- package/dist/esm/tutorial/example02.js +1 -1
- package/dist/esm/tutorial/example02.js.map +1 -1
- package/dist/esm/tutorial/example03.js +1 -1
- package/dist/esm/tutorial/example03.js.map +1 -1
- package/dist/esm/tutorial/example04.js +1 -1
- package/dist/esm/tutorial/example04.js.map +1 -1
- package/dist/esm/tutorial/example05.js +1 -1
- package/dist/esm/tutorial/example05.js.map +1 -1
- package/package.json +6 -5
- package/src/examples/BridgedDevicesNode.ts +2 -3
- package/src/examples/BridgedDevicesNodeLegacy.ts +15 -16
- package/src/examples/ComposedDeviceNode.ts +2 -3
- package/src/examples/ComposedDeviceNodeLegacy.ts +15 -16
- package/src/examples/ControllerNode.ts +2 -6
- package/src/examples/ControllerNodeLegacy.ts +22 -23
- package/src/examples/DeviceNode.ts +2 -3
- package/src/examples/DeviceNodeFull.ts +5 -10
- package/src/examples/DeviceNodeFullLegacy.ts +16 -18
- package/src/examples/IlluminatedRollerShade.ts +1 -1
- package/src/examples/LegacyStorageConverter.ts +3 -3
- package/src/examples/LightDevice.ts +1 -1
- package/src/examples/MultiDeviceNode.ts +2 -3
- package/src/examples/MultiDeviceNodeLegacy.ts +15 -15
- package/src/examples/SensorDeviceNode.ts +2 -3
- package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +11 -8
- package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +15 -11
- package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +12 -10
- package/src/examples/cluster/MyFancyOwnFunctionality.ts +9 -9
- package/src/tsconfig.json +1 -1
- package/src/tutorial/example01.ts +1 -1
- package/src/tutorial/example02.ts +1 -1
- package/src/tutorial/example03.ts +1 -1
- package/src/tutorial/example04.ts +1 -1
- package/src/tutorial/example05.ts +1 -1
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/DeviceNodeFullLegacy.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 simple on-off Matter device as a light or as a socket.\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 { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { Ble } from \"@project-chip/matter-node.js/ble\";\nimport { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } 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 singleton,\n} from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport DummyWifiNetworkCommissioningClusterServer from \"./cluster/DummyWifiNetworkCommissioningServerLegacy.js\";\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\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\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 test device\";\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 ${isSocket ? \"Socket\" : \"Light\"}`;\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 * 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 onOffDevice = isSocket ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addOnOffListener(on => commandExecutor(on ? \"on\" : \"off\")?.());\n\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n logger.info(`Identify called for OnOffDevice: ${identifyTime}`),\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: DeviceTypeId(onOffDevice.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 delayedAnnouncement: hasParameter(\"ble\"), // Delay announcement when BLE is used to show how limited advertisement works\n activeSessionsChangedCallback: fabricIndex => {\n console.log(\n `activeSessionsChangedCallback: Active sessions changed on Fabric ${fabricIndex}`,\n commissioningServer.getActiveSessionInformation(fabricIndex),\n );\n },\n commissioningChangedCallback: fabricIndex => {\n console.log(\n `commissioningChangedCallback: Commissioning changed on Fabric ${fabricIndex}`,\n commissioningServer.getCommissionedFabricInformation(fabricIndex)[0],\n );\n },\n });\n\n // optionally add a listener for the testEventTrigger command from the GeneralDiagnostics cluster\n commissioningServer.addCommandHandler(\"testEventTrigger\", async ({ request: { enableKey, eventTrigger } }) =>\n logger.info(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`),\n );\n\n /**\n * Modify automatically added clusters of the Root endpoint if needed\n * In this example we change the networkCommissioning cluster into one for \"Wifi only\" devices when BLE is used\n * for commissioning, to demonstrate how to do this.\n * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,\n * then all this is not needed.\n * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.\n */\n\n if (hasParameter(\"ble\")) {\n // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.\n // To offer e.g. a \"Wi-Fi only device\" (or any other combination) we need to override the Network Commissioning\n // cluster and implement all the need handling here. This is a \"static implementation\" for pure demonstration\n // purposes and just \"simulates\" the actions to be done. In a real world implementation this would be done by\n // the device implementor based on the relevant networking stack.\n // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8\n commissioningServer.addRootClusterServer(DummyWifiNetworkCommissioningClusterServer);\n }\n\n commissioningServer.addDevice(onOffDevice);\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 logEndpoint(commissioningServer.getRootEndpoint());\n\n // When we want to limit the initial announcement to one medium (e.g. BLE) then we need to delay the\n // announcement and provide the limiting information.\n // Without delaying the announcement is directly triggered with the above \"start()\" call.\n if (hasParameter(\"ble\")) {\n // Announce operational in BLE network only if we have ble enabled, else everywhere\n await commissioningServer.advertise({ ble: true });\n }\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 ble: hasParameter(\"ble\"),\n onIpNetwork: false,\n });\n\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n logger.info(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n logger.info(`Manual pairing code: ${manualPairingCode}`);\n } else {\n logger.info(\"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 Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAoBA,
|
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 simple on-off Matter device as a light or as a socket.\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 { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter.js\";\nimport { LogFormat, LogLevel, Logger, StorageManager, Time, singleton } from \"@project-chip/matter.js-general\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from \"@project-chip/matter.js/device\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\nimport DummyWifiNetworkCommissioningClusterServer from \"./cluster/DummyWifiNetworkCommissioningServerLegacy.js\";\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\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\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 test device\";\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 ${isSocket ? \"Socket\" : \"Light\"}`;\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 * 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 onOffDevice = isSocket ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addOnOffListener(on => commandExecutor(on ? \"on\" : \"off\")?.());\n\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n logger.info(`Identify called for OnOffDevice: ${identifyTime}`),\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: DeviceTypeId(onOffDevice.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 delayedAnnouncement: hasParameter(\"ble\"), // Delay announcement when BLE is used to show how limited advertisement works\n activeSessionsChangedCallback: fabricIndex => {\n console.log(\n `activeSessionsChangedCallback: Active sessions changed on Fabric ${fabricIndex}`,\n commissioningServer.getActiveSessionInformation(fabricIndex),\n );\n },\n commissioningChangedCallback: fabricIndex => {\n console.log(\n `commissioningChangedCallback: Commissioning changed on Fabric ${fabricIndex}`,\n commissioningServer.getCommissionedFabricInformation(fabricIndex)[0],\n );\n },\n });\n\n // optionally add a listener for the testEventTrigger command from the GeneralDiagnostics cluster\n commissioningServer.addCommandHandler(\"testEventTrigger\", async ({ request: { enableKey, eventTrigger } }) =>\n logger.info(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`),\n );\n\n /**\n * Modify automatically added clusters of the Root endpoint if needed\n * In this example we change the networkCommissioning cluster into one for \"Wifi only\" devices when BLE is used\n * for commissioning, to demonstrate how to do this.\n * If you want to implement Ethernet only devices that get connected to the network via LAN/Ethernet cable,\n * then all this is not needed.\n * The same as shown here for Wi-Fi is also possible theoretical for Thread only or combined devices.\n */\n\n if (hasParameter(\"ble\")) {\n // matter.js will create a Ethernet-only device by default when ut comes to Network Commissioning Features.\n // To offer e.g. a \"Wi-Fi only device\" (or any other combination) we need to override the Network Commissioning\n // cluster and implement all the need handling here. This is a \"static implementation\" for pure demonstration\n // purposes and just \"simulates\" the actions to be done. In a real world implementation this would be done by\n // the device implementor based on the relevant networking stack.\n // The NetworkCommissioningCluster and all logics are described in Matter Core Specifications section 11.8\n commissioningServer.addRootClusterServer(DummyWifiNetworkCommissioningClusterServer);\n }\n\n commissioningServer.addDevice(onOffDevice);\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 logEndpoint(commissioningServer.getRootEndpoint());\n\n // When we want to limit the initial announcement to one medium (e.g. BLE) then we need to delay the\n // announcement and provide the limiting information.\n // Without delaying the announcement is directly triggered with the above \"start()\" call.\n if (hasParameter(\"ble\")) {\n // Announce operational in BLE network only if we have ble enabled, else everywhere\n await commissioningServer.advertise({ ble: true });\n }\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 ble: hasParameter(\"ble\"),\n onIpNetwork: false,\n });\n\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n logger.info(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n logger.info(`Manual pairing code: ${manualPairingCode}`);\n } else {\n logger.info(\"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 Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.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,eAAe;AACxB,SAAS,qBAAqB,oBAAoB;AAClD,SAAS,WAAW,UAAU,QAAQ,gBAAgB,MAAM,iBAAiB;AAC7E,SAAS,WAAW;AACpB,SAAS,cAAc,gBAAgB;AACvC,SAAS,kBAAkB,uBAAuB,mBAAmB;AACrE,SAAS,cAAc;AACvB,OAAO,gDAAgD;AAEvD,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,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minatedRollerShade.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// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter
|
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// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter.js-nodejs\";\n\nimport {\n MovementDirection,\n MovementType,\n WindowCoveringServer,\n} from \"@project-chip/matter.js/behaviors/window-covering\";\nimport { OnOffLightDevice, OnOffLightRequirements } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { WindowCoveringDevice } from \"@project-chip/matter.js/devices/WindowCoveringDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\n/**\n * This example demonstrates implementation of a \"composed\" device comprising multiple sub-devices\n *\n * Our example device, the Excelsior 1000 EZ-Nite\u2122, is a roller shade with an illuminated valance.\n */\n\nconst LiftingWindowCoveringServer = WindowCoveringServer.with(\"Lift\", \"AbsolutePosition\", \"PositionAwareLift\");\n\n/**\n * Implementation of the Matter WindowCovering cluster for the shade motor.\n */\nclass RollerShade extends LiftingWindowCoveringServer {\n override async handleMovement(\n type: MovementType,\n reversed: boolean,\n direction: MovementDirection,\n targetPercent100ths?: number,\n ) {\n console.log(\n \"Move window shade\",\n direction === MovementDirection.Open ? \"Open\" : \"Close\",\n targetPercent100ths !== undefined ? `${targetPercent100ths / 100}%` : \"\",\n );\n\n // Updates the shade position\n await super.handleMovement(type, reversed, direction, targetPercent100ths);\n }\n}\n\n/**\n * Implementation of the OnOff cluster for our valance light.\n */\nclass ValanceLight extends OnOffLightRequirements.OnOffServer {\n override initialize() {\n this.reactTo(this.events.onOff$Changed, this.#stateChanged);\n }\n\n #stateChanged(value: boolean) {\n console.log(`Valance is now ${value ? \"illuminated\" : \"dark\"}`);\n }\n}\n\n/**\n * Our Matter node.\n */\nconst node = new ServerNode({\n id: \"excelsior1000\",\n\n productDescription: {},\n\n commissioning: {\n passcode: 20202021,\n discriminator: 3840,\n },\n\n basicInformation: {\n vendorName: \"Acme Corporation\",\n productName: \"Excelsior 1000 EZ-Nite\u2122\",\n vendorId: 0xfff1,\n productId: 0x8000,\n serialNumber: \"1234-12345-123\",\n },\n\n parts: [\n {\n type: WindowCoveringDevice.with(RollerShade),\n id: \"shade\",\n },\n\n {\n type: OnOffLightDevice.with(ValanceLight),\n id: \"valance\",\n },\n ],\n});\n\nawait node.run();\n"],
|
5
5
|
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAOA,OAAO;AAEP;AAAA,EACI;AAAA,EAEA;AAAA,OACG;AACP,SAAS,kBAAkB,8BAA8B;AACzD,SAAS,4BAA4B;AACrC,SAAS,kBAAkB;AAQ3B,MAAM,8BAA8B,qBAAqB,KAAK,QAAQ,oBAAoB,mBAAmB;AAK7G,MAAM,oBAAoB,4BAA4B;AAAA,EAClD,MAAe,eACX,MACA,UACA,WACA,qBACF;AACE,YAAQ;AAAA,MACJ;AAAA,MACA,cAAc,kBAAkB,OAAO,SAAS;AAAA,MAChD,wBAAwB,SAAY,GAAG,sBAAsB,GAAG,MAAM;AAAA,IAC1E;AAGA,UAAM,MAAM,eAAe,MAAM,UAAU,WAAW,mBAAmB;AAAA,EAC7E;AACJ;AAKA,MAAM,qBAAqB,uBAAuB,YAAY;AAAA,EACjD,aAAa;AAClB,SAAK,QAAQ,KAAK,OAAO,eAAe,KAAK,aAAa;AAAA,EAC9D;AAAA,EAEA,cAAc,OAAgB;AAC1B,YAAQ,IAAI,kBAAkB,QAAQ,gBAAgB,MAAM,EAAE;AAAA,EAClE;AACJ;AAKA,MAAM,OAAO,IAAI,WAAW;AAAA,EACxB,IAAI;AAAA,EAEJ,oBAAoB,CAAC;AAAA,EAErB,eAAe;AAAA,IACX,UAAU;AAAA,IACV,eAAe;AAAA,EACnB;AAAA,EAEA,kBAAkB;AAAA,IACd,YAAY;AAAA,IACZ,aAAa;AAAA,IACb,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc;AAAA,EAClB;AAAA,EAEA,OAAO;AAAA,IACH;AAAA,MACI,MAAM,qBAAqB,KAAK,WAAW;AAAA,MAC3C,IAAI;AAAA,IACR;AAAA,IAEA;AAAA,MACI,MAAM,iBAAiB,KAAK,YAAY;AAAA,MACxC,IAAI;AAAA,IACR;AAAA,EACJ;AACJ,CAAC;AAED,MAAM,KAAK,IAAI;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -4,10 +4,9 @@
|
|
4
4
|
* Copyright 2022-2024 Matter.js Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import "@project-chip/matter
|
8
|
-
import {
|
7
|
+
import { StorageBackendDisk } from "@project-chip/matter.js-nodejs";
|
8
|
+
import { Time } from "@project-chip/matter.js-general";
|
9
9
|
import { Environment, StorageService } from "@project-chip/matter.js/environment";
|
10
|
-
import { Time } from "@project-chip/matter.js/time";
|
11
10
|
import { LocalStorage } from "node-localstorage";
|
12
11
|
const environment = Environment.default;
|
13
12
|
const legacyStoragePath = environment.vars.string("legacy.storage.path");
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/LegacyStorageConverter.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\nimport
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAMA,
|
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\nimport { StorageBackendDisk } from \"@project-chip/matter.js-nodejs\";\n\nimport { Time } from \"@project-chip/matter.js-general\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { LocalStorage } from \"node-localstorage\";\n\nconst environment = Environment.default;\n\nconst legacyStoragePath = environment.vars.string(\"legacy.storage.path\");\nconst newStoragePath = environment.vars.string(\"storage.path\");\n\nif (!legacyStoragePath || !newStoragePath) {\n console.error(\"Usage: node LegacyStorageConverter.js --legacy-storage-path=<path> --storage-path=<path>\");\n process.exit(1);\n}\n\nconst legacyLocalStorage = new LocalStorage(legacyStoragePath);\n\nconst legacyNodes = new Array<string>();\nObject.keys(legacyLocalStorage).forEach(key => {\n const firstLevel = key.split(\".\")[0];\n if (!legacyNodes.includes(firstLevel)) {\n legacyNodes.push(firstLevel);\n }\n});\n\nconst storageService = environment.get(StorageService);\n\nconst legacyStorage = new StorageBackendDisk(legacyStoragePath);\nlegacyStorage.initialize();\n\nconst uniqueIds: Record<string, string> = {};\nif (legacyNodes.includes(\"Device\")) {\n console.log(\"Example Device found ...\");\n legacyNodes.splice(legacyNodes.indexOf(\"Device\"), 1);\n\n const newDeviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n for (const key of legacyStorage.keys([\"Device\"])) {\n console.log(\"Migrate Device.\", key);\n const value = legacyStorage.get([\"Device\"], key);\n await newDeviceStorage.set(key, value);\n if (key === \"uniqueid\") {\n uniqueIds[\"0\"] = String(value);\n await newDeviceStorage.set(key, String(value));\n } else if (key.startsWith(\"uniqueid\")) {\n const id = parseInt(key.substring(8));\n uniqueIds[id - 1] = String(value);\n await newDeviceStorage.set(key, String(value));\n }\n }\n}\n\nif (legacyNodes.includes(\"Controller\")) {\n console.log(\"Example Controller found ...\");\n legacyNodes.splice(legacyNodes.indexOf(\"Controller\"), 1);\n\n const newControllerStorage = (await storageService.open(\"controller\")).createContext(\"data\");\n\n for (const key of legacyStorage.keys([\"Controller\"])) {\n console.log(\"Migrate Controller.\", key);\n const value = legacyStorage.get([\"Controller\"], key);\n await newControllerStorage.set(key, value);\n if (key === \"uniqueid\") {\n uniqueIds[\"0\"] = String(value);\n await newControllerStorage.set(key, String(value));\n }\n }\n}\n\nconsole.log(uniqueIds);\n\nif (!Object.keys(uniqueIds).length) {\n console.error(\"No uniqueId(s) found in legacy storage. Cannot convert the node storage.\");\n process.exit(1);\n}\n\nfor (const nodeId of legacyNodes) {\n if (!uniqueIds[nodeId]) {\n const rootCertId = legacyStorage.get([\"0\", \"RootCertificateManager\"], \"rootCertId\");\n\n if (nodeId !== \"0\" || rootCertId === undefined) {\n console.error(`No uniqueId found for node ${nodeId}. Cannot convert the node storage.`);\n continue;\n }\n\n // Migrate the controller storage\n const newControllerStorage = (await storageService.open(\"controller\")).createContext(\"data\");\n const uniqueId = Time.nowMs().toString();\n await newControllerStorage.set(\"uniqueid\", uniqueId);\n\n const newNodeStorage = await storageService.open(uniqueId);\n\n const credentialsStorage = newNodeStorage.createContext(\"credentials\");\n await credentialsStorage.set(\"rootCertId\", rootCertId);\n await credentialsStorage.set(\n \"nextCertificateId\",\n legacyStorage.get([\"0\", \"RootCertificateManager\"], \"nextCertificateId\"),\n );\n await credentialsStorage.set(\n \"rootCertBytes\",\n legacyStorage.get([\"0\", \"RootCertificateManager\"], \"rootCertBytes\"),\n );\n await credentialsStorage.set(\n \"rootKeyIdentifier\",\n legacyStorage.get([\"0\", \"RootCertificateManager\"], \"rootKeyIdentifier\"),\n );\n await credentialsStorage.set(\"rootKeyPair\", legacyStorage.get([\"0\", \"RootCertificateManager\"], \"rootKeyPair\"));\n await credentialsStorage.set(\"fabric\", legacyStorage.get([\"0\", \"MatterController\"], \"fabric\"));\n\n const sessionsStorage = newNodeStorage.createContext(\"sessions\");\n await sessionsStorage.set(\n \"resumptionRecords\",\n legacyStorage.get([nodeId, \"SessionManager\"], \"resumptionRecords\"),\n );\n\n const nodesStorage = newNodeStorage.createContext(\"nodes\");\n await nodesStorage.set(\n \"resumptionRecords\",\n legacyStorage.get([nodeId, \"MatterController\"], \"commissionedNodes\"),\n );\n\n console.log(`Controller Node ${nodeId} with new unique id ${uniqueId} migrated successfully.`);\n } else {\n // Migrate the device storage\n const newNodeStorage = await storageService.open(uniqueIds[nodeId]);\n\n const nextEndpointNumber = legacyStorage.get<number>([nodeId, \"EndpointStructure\"], \"nextEndpointId\");\n if (nextEndpointNumber !== undefined && nextEndpointNumber > 2) {\n console.log(\n \"It seems you used a bridged or composed example before, please make sure to use all details (type, ids,...) in the parameters when starting the new example. When using a bridge and you had changed devices after pairing it could happen that the new example introduces new devices to the controller. If you are unsure unpair the old example and start fresh.\",\n );\n }\n\n const eventsStorage = newNodeStorage.createContext(\"events\");\n await eventsStorage.set(\"lastEventNumber\", legacyStorage.get([nodeId, \"EventHandler\"], \"lastEventNumber\"));\n\n const fabricsStorage = newNodeStorage.createContext(\"fabrics\");\n await fabricsStorage.set(\"fabrics\", legacyStorage.get([nodeId, \"FabricManager\"], \"fabrics\"));\n await fabricsStorage.set(\"nextFabricIndex\", legacyStorage.get([nodeId, \"FabricManager\"], \"nextFabricIndex\"));\n\n const sessionsStorage = newNodeStorage.createContext(\"sessions\");\n await sessionsStorage.set(\n \"resumptionRecords\",\n legacyStorage.get([nodeId, \"SessionManager\"], \"resumptionRecords\"),\n );\n\n console.log(`Device Node ${nodeId} with unique id ${uniqueIds[nodeId]} migrated successfully.`);\n }\n}\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,0BAA0B;AAEnC,SAAS,YAAY;AACrB,SAAS,aAAa,sBAAsB;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,cAAc,YAAY;AAEhC,MAAM,oBAAoB,YAAY,KAAK,OAAO,qBAAqB;AACvE,MAAM,iBAAiB,YAAY,KAAK,OAAO,cAAc;AAE7D,IAAI,CAAC,qBAAqB,CAAC,gBAAgB;AACvC,UAAQ,MAAM,0FAA0F;AACxG,UAAQ,KAAK,CAAC;AAClB;AAEA,MAAM,qBAAqB,IAAI,aAAa,iBAAiB;AAE7D,MAAM,cAAc,IAAI,MAAc;AACtC,OAAO,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MAAM,CAAC,yBAAyB;AAAA,EAClG;AACJ;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -4,7 +4,7 @@
|
|
4
4
|
* Copyright 2022-2024 Matter.js Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import "@project-chip/matter
|
7
|
+
import "@project-chip/matter.js-nodejs";
|
8
8
|
import { OnOffLightDevice, OnOffLightRequirements } from "@project-chip/matter.js/devices/OnOffLightDevice";
|
9
9
|
import { ServerNode } from "@project-chip/matter.js/node";
|
10
10
|
class ReportingOnOffServer extends OnOffLightRequirements.OnOffServer {
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/LightDevice.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// This demonstrates bringing a \"light\" device online with matter.js.\n\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter
|
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// This demonstrates bringing a \"light\" device online with matter.js.\n\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter.js-nodejs\";\n\nimport { OnOffLightDevice, OnOffLightRequirements } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\n\n// Matter exposes functionality in groups called \"clusters\". For this example device we override the matter.js \"On/Off\"\n// cluster implementation to print status to the console.\nclass ReportingOnOffServer extends OnOffLightRequirements.OnOffServer {\n // Intercept the \"on\" command to the Matter On/Off cluster to print a log message.\n override async on() {\n console.log(\"Turning light ON\");\n await super.on();\n }\n\n // This is the functional inverse of on() above.\n //\n // For demonstration purposes we update state ourselves rather than deferring to matter.js's default \"off\" handler\n // via super.off().\n override off() {\n console.log(\"Turning light OFF\");\n this.state.onOff = false;\n }\n\n // Use event handlers to log on/off state reactively, after it changes.\n override initialize() {\n this.events.onOff$Changed.on(value => {\n console.log(`Light is now ${value ? \"ON\" : \"OFF\"}`);\n });\n }\n}\n\n// Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.\n//\n// In this case we are using with() to install our On/Off cluster behavior.\nconst ExampleLight = OnOffLightDevice.with(ReportingOnOffServer);\n\n// Physical devices appear as \"nodes\" on a Matter network. As a device implementer you use a NodeServer to bring a\n// device online.\n//\n// Note there are a large number of options to NodeServer that we are allowing to take default values here. See\n// IlluminatedRollerShade.ts for a more detailed example.\nconst node = await ServerNode.create();\n\n// Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.\nawait node.add(ExampleLight);\n\n// Our device is now built and we can bring the node online.\n//\n// Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()\n// method of the node.\nawait node.run();\n"],
|
5
5
|
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AASA,OAAO;AAEP,SAAS,kBAAkB,8BAA8B;AACzD,SAAS,kBAAkB;AAI3B,MAAM,6BAA6B,uBAAuB,YAAY;AAAA;AAAA,EAElE,MAAe,KAAK;AAChB,YAAQ,IAAI,kBAAkB;AAC9B,UAAM,MAAM,GAAG;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMS,MAAM;AACX,YAAQ,IAAI,mBAAmB;AAC/B,SAAK,MAAM,QAAQ;AAAA,EACvB;AAAA;AAAA,EAGS,aAAa;AAClB,SAAK,OAAO,cAAc,GAAG,WAAS;AAClC,cAAQ,IAAI,gBAAgB,QAAQ,OAAO,KAAK,EAAE;AAAA,IACtD,CAAC;AAAA,EACL;AACJ;AAKA,MAAM,eAAe,iBAAiB,KAAK,oBAAoB;AAO/D,MAAM,OAAO,MAAM,WAAW,OAAO;AAGrC,MAAM,KAAK,IAAI,YAAY;AAM3B,MAAM,KAAK,IAAI;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -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
|
8
|
-
import {
|
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 devices = await getConfiguration();
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/MultiDeviceNode.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
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,
|
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\nconst devices = await getConfiguration();\nfor (let idx = 1; idx < devices.length; idx++) {\n const {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = devices[idx];\n const i = idx + 1;\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(isSocket ? 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 console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: \"onoff\" });\n await server.add(endpoint);\n\n /**\n * Register state change handlers of the node for identify and onoff states to react to the commands.\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 device ${i}, ideally blink a light every 0.5s ...`);\n });\n\n endpoint.events.identify.stopIdentifying.on(() => {\n console.log(`Stop identify logic for 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 * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n console.log(\"----------------------------\");\n console.log(`QR Code for Device ${i} on port ${port}:`);\n console.log(\"----------------------------\");\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.start();\n}\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 let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const devices = [];\n const numDevices = environment.vars.number(\"num\") ?? 2;\n for (let i = 1; i <= numDevices; i++) {\n const isSocket = await deviceStorage.get(`isSocket${i}`, environment.vars.string(`type${i}`) === \"socket\");\n if (await deviceStorage.has(`isSocket${i}`)) {\n console.log(`Device type ${isSocket ? \"socket\" : \"light\"} found in storage. --type parameter is ignored.`);\n }\n const deviceName = `Matter ${environment.vars.string(`type${i}`) ?? \"light\"} device ${i}`;\n const vendorName = \"matter-node.js\";\n const passcode =\n environment.vars.number(`passcode${i}`) ?? (await deviceStorage.get(`passcode${i}`, defaultPasscode++));\n const discriminator =\n environment.vars.number(`discriminator${i}`) ??\n (await deviceStorage.get(`discriminator${i}`, defaultDiscriminator++));\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(`vendorid${i}`) ?? (await deviceStorage.get(`vendorid${i}`, 0xfff1));\n const productName = `node-matter OnOff-Device ${i}`;\n const productId =\n environment.vars.number(`productid${i}`) ?? (await deviceStorage.get(`productid${i}`, 0x8000));\n\n const port = environment.vars.number(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n environment.vars.string(`uniqueid${i}`) ??\n (await deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set(`passcode${i}`, passcode);\n await deviceStorage.set(`discriminator${i}`, discriminator);\n await deviceStorage.set(`vendorid${i}`, vendorId);\n await deviceStorage.set(`productid${i}`, productId);\n await deviceStorage.set(`isSocket${i}`, isSocket);\n await deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n devices.push({\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\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AM,cAAc,IAAI,WAAW,CAAC,IAAI,QAAQ;AAChD,UAAM,cAAc,IAAI,WAAW,CAAC,IAAI,QAAQ;AAEhD,IAAAA,SAAQ,KAAK;AAAA,MACT;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,CAAC;AAAA,EACL;AAEA,SAAOA;AACX;",
|
6
6
|
"names": ["devices"]
|
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 { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from "@project-chip/matter-node.js/device";
|
9
|
-
import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
|
10
|
-
import { QrCode } from "@project-chip/matter-node.js/schema";
|
11
|
-
import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
|
12
|
-
import { Time } from "@project-chip/matter-node.js/time";
|
13
7
|
import {
|
8
|
+
StorageBackendDisk,
|
14
9
|
commandExecutor,
|
15
10
|
getIntParameter,
|
16
11
|
getParameter,
|
17
12
|
hasParameter,
|
18
13
|
requireMinNodeVersion
|
19
|
-
} from "@project-chip/matter
|
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";
|
20
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("MultiDevice");
|
22
21
|
requireMinNodeVersion(16);
|
23
22
|
switch (getParameter("loglevel")) {
|
24
23
|
case "fatal":
|
25
|
-
Logger.defaultLogLevel =
|
24
|
+
Logger.defaultLogLevel = LogLevel.FATAL;
|
26
25
|
break;
|
27
26
|
case "error":
|
28
|
-
Logger.defaultLogLevel =
|
27
|
+
Logger.defaultLogLevel = LogLevel.ERROR;
|
29
28
|
break;
|
30
29
|
case "warn":
|
31
|
-
Logger.defaultLogLevel =
|
30
|
+
Logger.defaultLogLevel = LogLevel.WARN;
|
32
31
|
break;
|
33
32
|
case "info":
|
34
|
-
Logger.defaultLogLevel =
|
33
|
+
Logger.defaultLogLevel = LogLevel.INFO;
|
35
34
|
break;
|
36
35
|
}
|
37
36
|
switch (getParameter("logformat")) {
|
38
37
|
case "plain":
|
39
|
-
Logger.format =
|
38
|
+
Logger.format = LogFormat.PLAIN;
|
40
39
|
break;
|
41
40
|
case "html":
|
42
|
-
Logger.format =
|
41
|
+
Logger.format = LogFormat.HTML;
|
43
42
|
break;
|
44
43
|
default:
|
45
|
-
if (process.stdin?.isTTY) Logger.format =
|
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/MultiDeviceNodeLegacy.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. When you want to add a composed devices to a Aggregator you need to\n * add all endpoints of the composed device to an \"ComposedDevice\" instance! (not shown in this example).\n * It can be used as CLI script and starting point for your own device node implementation.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\n\nconst logger = Logger.get(\"MultiDevice\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n const netInterface = getParameter(\"netinterface\");\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const commissioningServers = new Array<CommissioningServer>();\n\n let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n if (deviceStorage.has(`isSocket${i}`)) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === \"socket\");\n const deviceName = `Matter ${getParameter(`type${i}`) ?? \"light\"} device ${i}`;\n const deviceType =\n getParameter(`type${i}`) === \"socket\"\n ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code\n : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = getIntParameter(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n commissioningServer.addDevice(onOffDevice);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n commissioningServers.push(commissioningServer);\n }\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n console.log();\n commissioningServers.forEach((commissioningServer, index) => {\n console.log(\"----------------------------\");\n console.log(`Device ${index + 1}:`);\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n console.log();\n });\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA,
|
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 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\";\n\nimport { LogFormat, LogLevel, Logger, 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(\"MultiDevice\");\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 Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n const netInterface = getParameter(\"netinterface\");\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const commissioningServers = new Array<CommissioningServer>();\n\n let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n if (deviceStorage.has(`isSocket${i}`)) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === \"socket\");\n const deviceName = `Matter ${getParameter(`type${i}`) ?? \"light\"} device ${i}`;\n const deviceType =\n getParameter(`type${i}`) === \"socket\"\n ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code\n : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = getIntParameter(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n commissioningServer.addDevice(onOffDevice);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n commissioningServers.push(commissioningServer);\n }\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n console.log();\n commissioningServers.forEach((commissioningServer, index) => {\n console.log(\"----------------------------\");\n console.log(`Device ${index + 1}:`);\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n console.log();\n });\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.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;AAElD,SAAS,WAAW,UAAU,QAAQ,gBAAgB,YAAY;AAClE,SAAS,gBAAgB;AACzB,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAAS,cAAc;AAEvB,MAAM,SAAS,OAAO,IAAI,aAAa;AAEvC,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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
|
* Copyright 2022-2024 Matter.js Authors
|
5
5
|
* SPDX-License-Identifier: Apache-2.0
|
6
6
|
*/
|
7
|
-
import "@project-chip/matter
|
8
|
-
import {
|
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 { HumiditySensorDevice } from "@project-chip/matter.js/devices/HumiditySensorDevice";
|
@@ -13,7 +13,6 @@ import { TemperatureSensorDevice } from "@project-chip/matter.js/devices/Tempera
|
|
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
|
async function main() {
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/SensorDeviceNode.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 simple Sensor Matter device as temperature or humidity device.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { HumiditySensorDevice } from \"@project-chip/matter.js/devices/HumiditySensorDevice\";\nimport { TemperatureSensorDevice } from \"@project-chip/matter.js/devices/TemperatureSensorDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(\n isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,\n ),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n let endpoint: Endpoint<TemperatureSensorDevice | HumiditySensorDevice>;\n if (isTemperature) {\n endpoint = new Endpoint(TemperatureSensorDevice, {\n id: \"tempsensor\",\n temperatureMeasurement: {\n // Use this to initialize the measuredValue with the most uptodate value.\n // If you do not know the value and also cannot request it, best use \"null\" (if allowed by the cluster).\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n endpoint = new Endpoint(HumiditySensorDevice, {\n id: \"humsensor\",\n relativeHumidityMeasurement: {\n // Use this to initialize the measuredValue with the most uptodate value.\n // If you do not know the value and also cannot request it, best use \"null\" (if allowed by the cluster).\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n\n await server.add(endpoint);\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n const updateInterval = setInterval(() => {\n let setter: Promise<void>;\n if (isTemperature) {\n setter = endpoint.set({\n temperatureMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n setter = endpoint.set({\n relativeHumidityMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n setter.catch(error => console.error(\"Error updating measured value:\", error));\n }, interval * 1000);\n\n // Cleanup our update interval when node goes offline\n server.lifecycle.offline.on(() => clearTimeout(updateInterval));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\n\nfunction getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) {\n if (!allowNegativeValues) return Math.round(Math.random() * 100);\n return (Math.round(Math.random() * 100) - 50) * 100;\n }\n let result = execSync(script).toString().trim();\n if ((result.startsWith(\"'\") && result.endsWith(\"'\")) || (result.startsWith('\"') && result.endsWith('\"')))\n result = result.slice(1, -1);\n console.log(`Command result: ${result}`);\n let value = Math.round(parseFloat(result));\n if (!allowNegativeValues && value < 0) value = 0;\n return value;\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isTemperature = await deviceStorage.get(\"isTemperature\", environment.vars.get(\"type\") !== \"humidity\");\n if (await deviceStorage.has(\"isTemperature\")) {\n console.log(\n `Device type ${isTemperature ? \"temperature\" : \"humidity\"} found in storage. --type parameter is ignored.`,\n );\n }\n let interval = environment.vars.number(\"interval\") ?? (await deviceStorage.get(\"interval\", 60));\n if (interval < 1) {\n console.log(`Invalid Interval ${interval}, set to 60s`);\n interval = 60;\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (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 ${isTemperature ? \"Temperature\" : \"Humidity\"}`;\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 interval,\n isTemperature,\n uniqueid: uniqueId,\n });\n\n return {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,
|
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 simple Sensor Matter device as temperature or humidity device.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { 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 { HumiditySensorDevice } from \"@project-chip/matter.js/devices/HumiditySensorDevice\";\nimport { TemperatureSensorDevice } from \"@project-chip/matter.js/devices/TemperatureSensorDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(\n isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,\n ),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n let endpoint: Endpoint<TemperatureSensorDevice | HumiditySensorDevice>;\n if (isTemperature) {\n endpoint = new Endpoint(TemperatureSensorDevice, {\n id: \"tempsensor\",\n temperatureMeasurement: {\n // Use this to initialize the measuredValue with the most uptodate value.\n // If you do not know the value and also cannot request it, best use \"null\" (if allowed by the cluster).\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n endpoint = new Endpoint(HumiditySensorDevice, {\n id: \"humsensor\",\n relativeHumidityMeasurement: {\n // Use this to initialize the measuredValue with the most uptodate value.\n // If you do not know the value and also cannot request it, best use \"null\" (if allowed by the cluster).\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n\n await server.add(endpoint);\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n const updateInterval = setInterval(() => {\n let setter: Promise<void>;\n if (isTemperature) {\n setter = endpoint.set({\n temperatureMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n setter = endpoint.set({\n relativeHumidityMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n setter.catch(error => console.error(\"Error updating measured value:\", error));\n }, interval * 1000);\n\n // Cleanup our update interval when node goes offline\n server.lifecycle.offline.on(() => clearTimeout(updateInterval));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\n\nfunction getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) {\n if (!allowNegativeValues) return Math.round(Math.random() * 100);\n return (Math.round(Math.random() * 100) - 50) * 100;\n }\n let result = execSync(script).toString().trim();\n if ((result.startsWith(\"'\") && result.endsWith(\"'\")) || (result.startsWith('\"') && result.endsWith('\"')))\n result = result.slice(1, -1);\n console.log(`Command result: ${result}`);\n let value = Math.round(parseFloat(result));\n if (!allowNegativeValues && value < 0) value = 0;\n return value;\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isTemperature = await deviceStorage.get(\"isTemperature\", environment.vars.get(\"type\") !== \"humidity\");\n if (await deviceStorage.has(\"isTemperature\")) {\n console.log(\n `Device type ${isTemperature ? \"temperature\" : \"humidity\"} found in storage. --type parameter is ignored.`,\n );\n }\n let interval = environment.vars.number(\"interval\") ?? (await deviceStorage.get(\"interval\", 60));\n if (interval < 1) {\n console.log(`Invalid Interval ${interval}, set to 60s`);\n interval = 60;\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (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 ${isTemperature ? \"Temperature\" : \"Humidity\"}`;\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 interval,\n isTemperature,\n uniqueid: uniqueId,\n });\n\n return {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,SAAS,6BAA6B;AAEtC,SAAS,YAAY;AACrB,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB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