@project-chip/matter-node.js-examples 0.10.0-alpha.0-20240801-644afa31 → 0.10.0-alpha.0-20240803-f4969d2b
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +1 -1
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js +1 -0
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +1 -1
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js +1 -0
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +1 -1
- package/dist/esm/examples/ControllerNode.js +2 -2
- package/dist/esm/examples/ControllerNode.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFullLegacy.js +1 -0
- package/dist/esm/examples/DeviceNodeFullLegacy.js.map +1 -1
- package/dist/esm/examples/LegacyStorageConverter.js +2 -2
- package/dist/esm/examples/LegacyStorageConverter.js.map +2 -2
- package/dist/esm/examples/MultiDeviceNodeLegacy.js +1 -0
- package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +1 -1
- package/dist/esm/examples/SensorDeviceNode.js +2 -2
- package/dist/esm/examples/SensorDeviceNode.js.map +1 -1
- package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +2 -2
- package/package.json +7 -8
- package/src/examples/ControllerNode.ts +3 -2
- package/src/examples/LegacyStorageConverter.ts +2 -2
- package/src/examples/SensorDeviceNode.ts +2 -2
- package/src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts +2 -2
package/README.md
CHANGED
@@ -4,7 +4,7 @@
|
|
4
4
|
|
5
5
|
This project provides a set of reference implementations to offer several types of Matter device nodes or also a controller.
|
6
6
|
|
7
|
-
> This package requires Node
|
7
|
+
> This package requires Node 18+
|
8
8
|
|
9
9
|
# matter-node.js Usage examples / Reference implementations
|
10
10
|
|
@@ -51,6 +51,7 @@ logger.info(
|
|
51
51
|
'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
|
52
52
|
);
|
53
53
|
class BridgedDevice {
|
54
|
+
matterServer;
|
54
55
|
async start() {
|
55
56
|
logger.info(`node-matter`);
|
56
57
|
const storageManager = new StorageManager(storage);
|
@@ -2,6 +2,6 @@
|
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/BridgedDevicesNodeLegacy.ts"],
|
4
4
|
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a device bridge that exposed multiple devices.\n * It can be used as CLI script and starting point for your own device node implementation.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { VendorId } from \"@project-chip/matter-node.js/datatype\";\nimport { Aggregator, DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\n\nconst logger = Logger.get(\"Device\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass BridgedDevice {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n const deviceName = \"Matter Bridge device\";\n const deviceType = DeviceTypes.AGGREGATOR.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n uniqueid: uniqueId,\n });\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const aggregator = new Aggregator();\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n const name = `OnOff ${onOffDevice instanceof OnOffPluginUnitDevice ? \"Socket\" : \"Light\"} ${i}`;\n aggregator.addBridgedDevice(onOffDevice, {\n nodeLabel: name, // Main end user name for the device\n productName: name,\n productLabel: name,\n serialNumber: `node-matter-${uniqueId}-${i}`,\n reachable: true,\n });\n }\n\n commissioningServer.addDevice(aggregator);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new BridgedDevice();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAoBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,gBAAgB;AACzB,SAAS,YAAY,aAAa,kBAAkB,6BAA6B;AACjF,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KA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Q,IAAI,wEAAwE;AAAA,IACxF;AAAA,EACJ;AAAA,EAEA,MAAM,OAAO;AACT,UAAM,KAAK,cAAc,MAAM;AAAA,EACnC;AACJ;AAEA,MAAM,SAAS,IAAI,cAAc;AACjC,OACK,MAAM,EACN,KAAK,MAAM;AAEZ,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAEpC,QAAQ,GAAG,UAAU,MAAM;AAEvB,SACK,KAAK,EACL,KAAK,MAAM;AAER,YAAQ,MAAM;AACd,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -51,6 +51,7 @@ logger.info(
|
|
51
51
|
'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
|
52
52
|
);
|
53
53
|
class ComposedDevice {
|
54
|
+
matterServer;
|
54
55
|
async start() {
|
55
56
|
logger.info(`node-matter`);
|
56
57
|
const storageManager = new StorageManager(storage);
|
@@ -2,6 +2,6 @@
|
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/ComposedDeviceNodeLegacy.ts"],
|
4
4
|
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. When you want to add a composed devices to a Aggregator you need to\n * add all endpoints of the composed device to an \"ComposedDevice\" instance! (not shown in this example).\n * It can be used as CLI script and starting point for your own device node implementation.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { VendorId } from \"@project-chip/matter-node.js/datatype\";\nimport { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\n\nconst logger = Logger.get(\"Device\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass ComposedDevice {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n if (deviceStorage.has(\"isSocket\")) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(\"isSocket\", getParameter(\"type\") === \"socket\");\n const deviceName = \"Matter composed device\";\n const deviceType =\n getParameter(\"type\") === \"socket\" ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff-Bridge`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n isSocket,\n uniqueid: uniqueId,\n });\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n onOffDevice.addCommandHandler(\"identify\", async ({ request: { identifyTime } }) =>\n console.log(\n `Identify called for OnOffDevice ${onOffDevice.name} with id: ${i} and identifyTime: ${identifyTime}`,\n ),\n );\n\n commissioningServer.addDevice(onOffDevice);\n }\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new ComposedDevice();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage.close();\n process.exit(0);\n })\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,gBAAgB;AACzB,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AACR;AAEA,QAAQ,aAAa,WAAW,GAAG;AAAA,EAC/B,KAAK;AACD,WAAO,SAAS,OAAO;AACvB;AAAA,EACJ,KAAK;AACD,WAAO,SAAS,OAAO;AACvB;AAAA,EACJ;AACI,QAAI,QAAQ,OAAO,MAAO,QAAO,SAAS,OAAO;AACzD;AAEA,MAAM,kBAAkB,aAAa,OAAO,KAAK;AACjD,MAAM,UAAU,IAAI,mBAAmB,iBAAiB,aAAa,cAAc,CAAC;AACpF,OAAO,KAAK,qBAAqB,eAAe,cAAc;AAC9D,OAAO;AAAA,EACH;AACJ;AAEA,MAAM,eAAe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|
15
15
|
GeneralCommissioning,
|
16
|
-
|
16
|
+
OnOff
|
17
17
|
} from "@project-chip/matter.js/cluster";
|
18
18
|
import { NodeId } from "@project-chip/matter.js/datatype";
|
19
19
|
import { NodeStateInformation } from "@project-chip/matter.js/device";
|
@@ -172,7 +172,7 @@ class ControllerNode {
|
|
172
172
|
}
|
173
173
|
const devices = node.getDevices();
|
174
174
|
if (devices[0] && devices[0].number === 1) {
|
175
|
-
const onOff = devices[0].getClusterClient(
|
175
|
+
const onOff = devices[0].getClusterClient(OnOff.Complete);
|
176
176
|
if (onOff !== void 0) {
|
177
177
|
let onOffStatus = await onOff.getOnOffAttribute();
|
178
178
|
console.log("initial onOffStatus", onOffStatus);
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/ControllerNode.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a Matter controller to pair with a device and interfact with it.\n * It can be used as CLI script, but is more thought as a starting point for your own controller implementation\n * because you need to adjust the code in any way depending on your use case.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { CommissioningController, NodeCommissioningOptions } from \"@project-chip/matter.js\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport {\n BasicInformationCluster,\n DescriptorCluster,\n GeneralCommissioning,\n OnOffCluster,\n} from \"@project-chip/matter.js/cluster\";\nimport { NodeId } from \"@project-chip/matter.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter.js/device\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { CommissioningOptions } from \"@project-chip/matter.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter.js/schema\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { singleton } from \"@project-chip/matter.js/util\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\nconst environment = Environment.default;\n\nif (environment.vars.get(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageService = environment.get(StorageService);\n\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nlogger.info(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n);\n\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const controllerStorage = (await storageService.open(\"controller\")).createContext(\"data\");\n const ip = (await controllerStorage.has(\"ip\"))\n ? await controllerStorage.get<string>(\"ip\")\n : environment.vars.string(\"ip\");\n const port = (await controllerStorage.has(\"port\"))\n ? await controllerStorage.get<number>(\"port\")\n : environment.vars.number(\"port\");\n const uniqueId = (await controllerStorage.has(\"uniqueid\"))\n ? await controllerStorage.get<string>(\"uniqueid\")\n : (environment.vars.string(\"uniqueid\") ?? Time.nowMs().toString());\n await controllerStorage.set(\"uniqueid\", uniqueId);\n\n const pairingCode = environment.vars.string(\"pairingcode\");\n let longDiscriminator, setupPin, shortDiscriminator;\n if (pairingCode !== undefined) {\n const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);\n shortDiscriminator = pairingCodeCodec.shortDiscriminator;\n longDiscriminator = undefined;\n setupPin = pairingCodeCodec.passcode;\n logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);\n } else {\n longDiscriminator =\n environment.vars.number(\"longDiscriminator\") ??\n (await controllerStorage.get(\"longDiscriminator\", 3840));\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = environment.vars.number(\"pin\") ?? (await controllerStorage.get(\"pin\", 20202021));\n }\n if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {\n throw new Error(\n \"Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode\",\n );\n }\n\n // Collect commissioning options from commandline parameters\n const commissioningOptions: CommissioningOptions = {\n regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,\n regulatoryCountryCode: \"XX\",\n };\n\n let ble = false;\n if (environment.vars.get(\"ble\")) {\n ble = true;\n const wifiSsid = environment.vars.string(\"ble-wifi-ssid\");\n const wifiCredentials = environment.vars.string(\"ble-wifi-credentials\");\n const threadNetworkName = environment.vars.string(\"ble-thread-networkname\");\n const threadOperationalDataset = environment.vars.string(\"ble-thread-operationaldataset\");\n if (wifiSsid !== undefined && wifiCredentials !== undefined) {\n logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);\n commissioningOptions.wifiNetwork = {\n wifiSsid: wifiSsid,\n wifiCredentials: wifiCredentials,\n };\n }\n if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {\n logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);\n commissioningOptions.threadNetwork = {\n networkName: threadNetworkName,\n operationalDataset: threadOperationalDataset,\n };\n }\n }\n\n /**\n * Create Matter Server and Controller Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * CommissioningController to it and add the just created device instance to it.\n * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n const commissioningController = new CommissioningController({\n environment: {\n environment,\n id: uniqueId,\n },\n autoConnect: false,\n });\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n await commissioningController.start();\n\n if (!commissioningController.isCommissioned()) {\n const options = {\n commissioning: commissioningOptions,\n discovery: {\n knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: \"udp\" } : undefined,\n identifierData:\n longDiscriminator !== undefined\n ? { longDiscriminator }\n : shortDiscriminator !== undefined\n ? { shortDiscriminator }\n : {},\n discoveryCapabilities: {\n ble,\n },\n },\n passcode: setupPin,\n } as NodeCommissioningOptions;\n logger.info(`Commissioning ... ${Logger.toJSON(options)}`);\n const nodeId = await commissioningController.commissionNode(options);\n\n console.log(`Commissioning successfully done with nodeId ${nodeId}`);\n }\n\n /**\n * TBD\n */\n try {\n const nodes = commissioningController.getCommissionedNodes();\n console.log(\"Found commissioned nodes:\", Logger.toJSON(nodes));\n\n const nodeId = NodeId(environment.vars.number(\"nodeid\") ?? nodes[0]);\n if (!nodes.includes(nodeId)) {\n throw new Error(`Node ${nodeId} not found in commissioned nodes`);\n }\n\n const node = await commissioningController.connectNode(nodeId, {\n attributeChangedCallback: (\n peerNodeId,\n { path: { nodeId, clusterId, endpointId, attributeName }, value },\n ) =>\n console.log(\n `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(\n value,\n )}`,\n ),\n eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>\n console.log(\n `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(\n events,\n )}`,\n ),\n stateInformationCallback: (peerNodeId, info) => {\n switch (info) {\n case NodeStateInformation.Connected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);\n break;\n case NodeStateInformation.Disconnected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);\n break;\n case NodeStateInformation.Reconnecting:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);\n break;\n case NodeStateInformation.WaitingForDeviceDiscovery:\n console.log(\n `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,\n );\n break;\n case NodeStateInformation.StructureChanged:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);\n break;\n case NodeStateInformation.Decommissioned:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);\n break;\n }\n },\n });\n\n // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!\n // It is provided to proof the concept\n\n node.logStructure();\n\n // Example to initialize a ClusterClient and access concrete fields as API methods\n const descriptor = node.getRootClusterClient(DescriptorCluster);\n if (descriptor !== undefined) {\n console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way\n console.log(await descriptor.getServerListAttribute()); // or more convenient that way\n } else {\n console.log(\"No Descriptor Cluster found. This should never happen!\");\n }\n\n // Example to subscribe to a field and get the value\n const info = node.getRootClusterClient(BasicInformationCluster);\n if (info !== undefined) {\n console.log(await info.getProductNameAttribute()); // This call is executed remotely\n //console.log(await info.subscribeProductNameAttribute(value => console.log(\"productName\", value), 5, 30));\n //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!\n } else {\n console.log(\"No BasicInformation Cluster found. This should never happen!\");\n }\n\n // Example to get all Attributes of the commissioned node: */*/*\n //const attributesAll = await interactionClient.getAllAttributes();\n //console.log(\"Attributes-All:\", Logger.toJSON(attributesAll));\n\n // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*\n //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);\n //console.log(\"Attributes-Descriptor:\", JSON.stringify(attributesAllDescriptor, null, 2));\n\n // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*\n //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);\n //console.log(\"Attributes-BasicInformation:\", JSON.stringify(attributesBasicInformation, null, 2));\n\n const devices = node.getDevices();\n if (devices[0] && devices[0].number === 1) {\n // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*\n //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {\n // console.log(\"Subscribe-All Data:\", Logger.toJSON(data));\n //});\n\n const onOff = devices[0].getClusterClient(OnOffCluster);\n if (onOff !== undefined) {\n let onOffStatus = await onOff.getOnOffAttribute();\n console.log(\"initial onOffStatus\", onOffStatus);\n\n onOff.addOnOffAttributeListener(value => {\n console.log(\"subscription onOffStatus\", value);\n onOffStatus = value;\n });\n // read data every minute to keep up the connection to show the subscription is working\n setInterval(() => {\n onOff\n .toggle()\n .then(() => {\n onOffStatus = !onOffStatus;\n console.log(\"onOffStatus\", onOffStatus);\n })\n .catch(error => logger.error(error));\n }, 60000);\n }\n }\n } finally {\n //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed\n setTimeout(() => process.exit(0), 1000000);\n }\n }\n}\n\nnew ControllerNode().start().catch(error => logger.error(error));\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,eAAe;AACxB,SAAS,6BAA6B;AACtC,SAAS,+BAAyD;AAClE,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,
|
4
|
+
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a Matter controller to pair with a device and interfact with it.\n * It can be used as CLI script, but is more thought as a starting point for your own controller implementation\n * because you need to adjust the code in any way depending on your use case.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { CommissioningController, NodeCommissioningOptions } from \"@project-chip/matter.js\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport {\n BasicInformationCluster,\n ClusterClientObj,\n DescriptorCluster,\n GeneralCommissioning,\n OnOff,\n} from \"@project-chip/matter.js/cluster\";\nimport { NodeId } from \"@project-chip/matter.js/datatype\";\nimport { NodeStateInformation } from \"@project-chip/matter.js/device\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { CommissioningOptions } from \"@project-chip/matter.js/protocol\";\nimport { ManualPairingCodeCodec } from \"@project-chip/matter.js/schema\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { singleton } from \"@project-chip/matter.js/util\";\n\nconst logger = Logger.get(\"Controller\");\n\nrequireMinNodeVersion(16);\n\nconst environment = Environment.default;\n\nif (environment.vars.get(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageService = environment.get(StorageService);\n\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nlogger.info(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n);\n\nclass ControllerNode {\n async start() {\n logger.info(`node-matter Controller started`);\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const controllerStorage = (await storageService.open(\"controller\")).createContext(\"data\");\n const ip = (await controllerStorage.has(\"ip\"))\n ? await controllerStorage.get<string>(\"ip\")\n : environment.vars.string(\"ip\");\n const port = (await controllerStorage.has(\"port\"))\n ? await controllerStorage.get<number>(\"port\")\n : environment.vars.number(\"port\");\n const uniqueId = (await controllerStorage.has(\"uniqueid\"))\n ? await controllerStorage.get<string>(\"uniqueid\")\n : (environment.vars.string(\"uniqueid\") ?? Time.nowMs().toString());\n await controllerStorage.set(\"uniqueid\", uniqueId);\n\n const pairingCode = environment.vars.string(\"pairingcode\");\n let longDiscriminator, setupPin, shortDiscriminator;\n if (pairingCode !== undefined) {\n const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);\n shortDiscriminator = pairingCodeCodec.shortDiscriminator;\n longDiscriminator = undefined;\n setupPin = pairingCodeCodec.passcode;\n logger.debug(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);\n } else {\n longDiscriminator =\n environment.vars.number(\"longDiscriminator\") ??\n (await controllerStorage.get(\"longDiscriminator\", 3840));\n if (longDiscriminator > 4095) throw new Error(\"Discriminator value must be less than 4096\");\n setupPin = environment.vars.number(\"pin\") ?? (await controllerStorage.get(\"pin\", 20202021));\n }\n if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {\n throw new Error(\n \"Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode\",\n );\n }\n\n // Collect commissioning options from commandline parameters\n const commissioningOptions: CommissioningOptions = {\n regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,\n regulatoryCountryCode: \"XX\",\n };\n\n let ble = false;\n if (environment.vars.get(\"ble\")) {\n ble = true;\n const wifiSsid = environment.vars.string(\"ble-wifi-ssid\");\n const wifiCredentials = environment.vars.string(\"ble-wifi-credentials\");\n const threadNetworkName = environment.vars.string(\"ble-thread-networkname\");\n const threadOperationalDataset = environment.vars.string(\"ble-thread-operationaldataset\");\n if (wifiSsid !== undefined && wifiCredentials !== undefined) {\n logger.info(`Registering Commissioning over BLE with WiFi: ${wifiSsid}`);\n commissioningOptions.wifiNetwork = {\n wifiSsid: wifiSsid,\n wifiCredentials: wifiCredentials,\n };\n }\n if (threadNetworkName !== undefined && threadOperationalDataset !== undefined) {\n logger.info(`Registering Commissioning over BLE with Thread: ${threadNetworkName}`);\n commissioningOptions.threadNetwork = {\n networkName: threadNetworkName,\n operationalDataset: threadOperationalDataset,\n };\n }\n }\n\n /**\n * Create Matter Server and Controller Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * CommissioningController to it and add the just created device instance to it.\n * The Controller node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n const commissioningController = new CommissioningController({\n environment: {\n environment,\n id: uniqueId,\n },\n autoConnect: false,\n });\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n await commissioningController.start();\n\n if (!commissioningController.isCommissioned()) {\n const options = {\n commissioning: commissioningOptions,\n discovery: {\n knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: \"udp\" } : undefined,\n identifierData:\n longDiscriminator !== undefined\n ? { longDiscriminator }\n : shortDiscriminator !== undefined\n ? { shortDiscriminator }\n : {},\n discoveryCapabilities: {\n ble,\n },\n },\n passcode: setupPin,\n } as NodeCommissioningOptions;\n logger.info(`Commissioning ... ${Logger.toJSON(options)}`);\n const nodeId = await commissioningController.commissionNode(options);\n\n console.log(`Commissioning successfully done with nodeId ${nodeId}`);\n }\n\n /**\n * TBD\n */\n try {\n const nodes = commissioningController.getCommissionedNodes();\n console.log(\"Found commissioned nodes:\", Logger.toJSON(nodes));\n\n const nodeId = NodeId(environment.vars.number(\"nodeid\") ?? nodes[0]);\n if (!nodes.includes(nodeId)) {\n throw new Error(`Node ${nodeId} not found in commissioned nodes`);\n }\n\n const node = await commissioningController.connectNode(nodeId, {\n attributeChangedCallback: (\n peerNodeId,\n { path: { nodeId, clusterId, endpointId, attributeName }, value },\n ) =>\n console.log(\n `attributeChangedCallback ${peerNodeId}: Attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(\n value,\n )}`,\n ),\n eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>\n console.log(\n `eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(\n events,\n )}`,\n ),\n stateInformationCallback: (peerNodeId, info) => {\n switch (info) {\n case NodeStateInformation.Connected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);\n break;\n case NodeStateInformation.Disconnected:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);\n break;\n case NodeStateInformation.Reconnecting:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);\n break;\n case NodeStateInformation.WaitingForDeviceDiscovery:\n console.log(\n `stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`,\n );\n break;\n case NodeStateInformation.StructureChanged:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);\n break;\n case NodeStateInformation.Decommissioned:\n console.log(`stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);\n break;\n }\n },\n });\n\n // Important: This is a temporary API to proof the methods working and this will change soon and is NOT stable!\n // It is provided to proof the concept\n\n node.logStructure();\n\n // Example to initialize a ClusterClient and access concrete fields as API methods\n const descriptor = node.getRootClusterClient(DescriptorCluster);\n if (descriptor !== undefined) {\n console.log(await descriptor.attributes.deviceTypeList.get()); // you can call that way\n console.log(await descriptor.getServerListAttribute()); // or more convenient that way\n } else {\n console.log(\"No Descriptor Cluster found. This should never happen!\");\n }\n\n // Example to subscribe to a field and get the value\n const info = node.getRootClusterClient(BasicInformationCluster);\n if (info !== undefined) {\n console.log(await info.getProductNameAttribute()); // This call is executed remotely\n //console.log(await info.subscribeProductNameAttribute(value => console.log(\"productName\", value), 5, 30));\n //console.log(await info.getProductNameAttribute()); // This call is resolved locally because we have subscribed to the value!\n } else {\n console.log(\"No BasicInformation Cluster found. This should never happen!\");\n }\n\n // Example to get all Attributes of the commissioned node: */*/*\n //const attributesAll = await interactionClient.getAllAttributes();\n //console.log(\"Attributes-All:\", Logger.toJSON(attributesAll));\n\n // Example to get all Attributes of all Descriptor Clusters of the commissioned node: */DescriptorCluster/*\n //const attributesAllDescriptor = await interactionClient.getMultipleAttributes([{ clusterId: DescriptorCluster.id} ]);\n //console.log(\"Attributes-Descriptor:\", JSON.stringify(attributesAllDescriptor, null, 2));\n\n // Example to get all Attributes of the Basic Information Cluster of endpoint 0 of the commissioned node: 0/BasicInformationCluster/*\n //const attributesBasicInformation = await interactionClient.getMultipleAttributes([{ endpointId: 0, clusterId: BasicInformationCluster.id} ]);\n //console.log(\"Attributes-BasicInformation:\", JSON.stringify(attributesBasicInformation, null, 2));\n\n const devices = node.getDevices();\n if (devices[0] && devices[0].number === 1) {\n // Example to subscribe to all Attributes of endpoint 1 of the commissioned node: */*/*\n //await interactionClient.subscribeMultipleAttributes([{ endpointId: 1, /* subscribe anything from endpoint 1 */ }], 0, 180, data => {\n // console.log(\"Subscribe-All Data:\", Logger.toJSON(data));\n //});\n\n const onOff: ClusterClientObj<OnOff.Complete> | undefined = devices[0].getClusterClient(OnOff.Complete);\n if (onOff !== undefined) {\n let onOffStatus = await onOff.getOnOffAttribute();\n console.log(\"initial onOffStatus\", onOffStatus);\n\n onOff.addOnOffAttributeListener(value => {\n console.log(\"subscription onOffStatus\", value);\n onOffStatus = value;\n });\n // read data every minute to keep up the connection to show the subscription is working\n setInterval(() => {\n onOff\n .toggle()\n .then(() => {\n onOffStatus = !onOffStatus;\n console.log(\"onOffStatus\", onOffStatus);\n })\n .catch(error => logger.error(error));\n }, 60000);\n }\n }\n } finally {\n //await matterServer.close(); // Comment out when subscribes are used, else the connection will be closed\n setTimeout(() => process.exit(0), 1000000);\n }\n }\n}\n\nnew ControllerNode().start().catch(error => logger.error(error));\n"],
|
5
|
+
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAiBA,OAAO;AAEP,SAAS,eAAe;AACxB,SAAS,6BAA6B;AACtC,SAAS,+BAAyD;AAClE,SAAS,WAAW;AACpB;AAAA,EACI;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,cAAc;AAEvB,SAAS,8BAA8B;AACvC,SAAS,YAAY;AACrB,SAAS,iBAAiB;AAE1B,MAAM,SAAS,OAAO,IAAI,YAAY;AAEtC,sBAAsB,EAAE;AAExB,MAAM,cAAc,YAAY;AAEhC,IAAI,YAAY,KAAK,IAAI,KAAK,GAAG;AAE7B,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,YAAY,KAAK,OAAO,YAAY;AAAA,IAC/C,CAAC;AAAA,EACT;AACJ;AAEA,MAAM,iBAAiB,YAAY,IAAI,cAAc;AAErD,QAAQ,IAAI,qBAAqB,eAAe,QAAQ,cAAc;AACtE,OAAO;AAAA,EACH;AACJ;AAEA,MAAM,eAAe;AAAA,EACjB,MAAM,QAAQ;AACV,WAAO,KAAK,gCAAgC;AAa5C,UAAM,qBAAqB,MAAM,eAAe,KAAK,YAAY,GAAG,cAAc,MAAM;AACxF,UAAM,KAAM,MAAM,kBAAkB,IAAI,IAAI,IACtC,MAAM,kBAAkB,IAAY,IAAI,IACxC,YAAY,KAAK,OAAO,IAAI;AAClC,UAAM,OAAQ,MAAM,kBAAkB,IAAI,MAAM,IAC1C,MAAM,kBAAkB,IAAY,MAAM,IAC1C,YAAY,KAAK,OAAO,MAAM;A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,IAAI,MAAM,WAAW,uBAAuB,CAAC;AAAA,MACzD,OAAO;AACH,gBAAQ,IAAI,wDAAwD;AAAA,MACxE;AAGA,YAAM,OAAO,KAAK,qBAAqB,uBAAuB;AAC9D,UAAI,SAAS,QAAW;AACpB,gBAAQ,IAAI,MAAM,KAAK,wBAAwB,CAAC;AAAA,MAGpD,OAAO;AACH,gBAAQ,IAAI,8DAA8D;AAAA,MAC9E;AAcA,YAAM,UAAU,KAAK,WAAW;AAChC,UAAI,QAAQ,CAAC,KAAK,QAAQ,CAAC,EAAE,WAAW,GAAG;AAMvC,cAAM,QAAsD,QAAQ,CAAC,EAAE,iBAAiB,MAAM,QAAQ;AACtG,YAAI,UAAU,QAAW;AACrB,cAAI,cAAc,MAAM,MAAM,kBAAkB;AAChD,kBAAQ,IAAI,uBAAuB,WAAW;AAE9C,gBAAM,0BAA0B,WAAS;AACrC,oBAAQ,IAAI,4BAA4B,KAAK;AAC7C,0BAAc;AAAA,UAClB,CAAC;AAED,sBAAY,MAAM;AACd,kBACK,OAAO,EACP,KAAK,MAAM;AACR,4BAAc,CAAC;AACf,sBAAQ,IAAI,eAAe,WAAW;AAAA,YAC1C,CAAC,EACA,MAAM,WAAS,OAAO,MAAM,KAAK,CAAC;AAAA,UAC3C,GAAG,GAAK;AAAA,QACZ;AAAA,MACJ;AAAA,IACJ,UAAE;AAEE,iBAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,GAAO;AAAA,IAC7C;AAAA,EACJ;AACJ;AAEA,IAAI,eAAe,EAAE,MAAM,EAAE,MAAM,WAAS,OAAO,MAAM,KAAK,CAAC;",
|
6
6
|
"names": ["nodeId", "info"]
|
7
7
|
}
|
@@ -62,6 +62,7 @@ logger.info(
|
|
62
62
|
'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
|
63
63
|
);
|
64
64
|
class Device {
|
65
|
+
matterServer;
|
65
66
|
async start() {
|
66
67
|
logger.info(`node-matter`);
|
67
68
|
const storageManager = new StorageManager(storage);
|
@@ -2,6 +2,6 @@
|
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/DeviceNodeFullLegacy.ts"],
|
4
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,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,eAAe;AACxB,SAAS,WAAW;AACpB,SAAS,kBAAkB,uBAAuB,mBAAmB;AACrE,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,cAAc,gBAAgB;AACvC,OAAO,gDAAgD;AAEvD,MAAM,SAAS,OAAO,IAAI,QAAQ;AAElC,sBAAs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AAK,CAAC;AAAA,EAClB,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -62,14 +62,14 @@ if (legacyNodes.includes("Controller")) {
|
|
62
62
|
}
|
63
63
|
console.log(uniqueIds);
|
64
64
|
if (!Object.keys(uniqueIds).length) {
|
65
|
-
console.error("No uniqueId(s) found in legacy storage.
|
65
|
+
console.error("No uniqueId(s) found in legacy storage. Cannot convert the node storage.");
|
66
66
|
process.exit(1);
|
67
67
|
}
|
68
68
|
for (const nodeId of legacyNodes) {
|
69
69
|
if (!uniqueIds[nodeId]) {
|
70
70
|
const rootCertId = legacyStorage.get(["0", "RootCertificateManager"], "rootCertId");
|
71
71
|
if (nodeId !== "0" || rootCertId === void 0) {
|
72
|
-
console.error(`No uniqueId found for node ${nodeId}.
|
72
|
+
console.error(`No uniqueId found for node ${nodeId}. Cannot convert the node storage.`);
|
73
73
|
continue;
|
74
74
|
}
|
75
75
|
const newControllerStorage = (await storageService.open("controller")).createContext("data");
|
@@ -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 \"@project-chip/matter-node.js\";\nimport { StorageBackendDisk } from \"@project-chip/matter-node.js/storage\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { Time } from \"@project-chip/matter.js/time\";\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.
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAMA,OAAO;AACP,SAAS,0BAA0B;AACnC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,YAAY;AACrB,SAAS,oBAA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YAAM,iBAAiB,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,IACjD;AAAA,EACJ;AACJ;AAEA,IAAI,YAAY,SAAS,YAAY,GAAG;AACpC,UAAQ,IAAI,8BAA8B;AAC1C,cAAY,OAAO,YAAY,QAAQ,YAAY,GAAG,CAAC;AAEvD,QAAM,wBAAwB,MAAM,eAAe,KAAK,YAAY,GAAG,cAAc,MAAM;AAE3F,aAAW,OAAO,cAAc,KAAK,CAAC,YAAY,CAAC,GAAG;AAClD,YAAQ,IAAI,uBAAuB,GAAG;AACtC,UAAM,QAAQ,cAAc,IAAI,CAAC,YAAY,GAAG,GAAG;AACnD,UAAM,qBAAqB,IAAI,KAAK,KAAK;AACzC,QAAI,QAAQ,YAAY;AACpB,gBAAU,GAAG,IAAI,OAAO,KAAK;AAC7B,YAAM,qBAAqB,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,IACrD;AAAA,EACJ;AACJ;AAEA,QAAQ,IAAI,SAAS;AAErB,IAAI,CAAC,OAAO,KAAK,SAAS,EAAE,QAAQ;AAChC,UAAQ,MAAM,
|
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 \"@project-chip/matter-node.js\";\nimport { StorageBackendDisk } from \"@project-chip/matter-node.js/storage\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { Time } from \"@project-chip/matter.js/time\";\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,OAAO;AACP,SAAS,0BAA0B;AACnC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,YAAY;AACrB,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,KAAK,kBAAkB,EAAE,QAAQ,SAAO;AAC3C,QAAM,aAAa,IAAI,MAAM,GAAG,EAAE,CAAC;AACnC,MAAI,CAAC,YAAY,SAAS,UAAU,GAAG;AACnC,gBAAY,KAAK,UAAU;AAAA,EAC/B;AACJ,CAAC;AAED,MAAM,iBAAiB,YAAY,IAAI,cAAc;AAErD,MAAM,gBAAgB,IAAI,mBAAmB,iBAAiB;AAC9D,cAAc,WAAW;AAEzB,MAAM,YAAoC,CAAC;AAC3C,IAAI,YAAY,SAAS,QAAQ,GAAG;AAChC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f;AAAA,MACA,cAAc,IAAI,CAAC,QAAQ,kBAAkB,GAAG,mBAAmB;AAAA,IACvE;AAEA,YAAQ,IAAI,mBAAmB,MAAM,uBAAuB,QAAQ,yBAAyB;AAAA,EACjG,OAAO;AAEH,UAAM,iBAAiB,MAAM,eAAe,KAAK,UAAU,MAAM,CAAC;AAElE,UAAM,qBAAqB,cAAc,IAAY,CAAC,QAAQ,mBAAmB,GAAG,gBAAgB;AACpG,QAAI,uBAAuB,UAAa,qBAAqB,GAAG;AAC5D,cAAQ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAEA,UAAM,gBAAgB,eAAe,cAAc,QAAQ;AAC3D,UAAM,cAAc,IAAI,mBAAmB,cAAc,IAAI,CAAC,QAAQ,cAAc,GAAG,iBAAiB,CAAC;AAEzG,UAAM,iBAAiB,eAAe,cAAc,SAAS;AAC7D,UAAM,eAAe,IAAI,WAAW,cAAc,IAAI,CAAC,QAAQ,eAAe,GAAG,SAAS,CAAC;AAC3F,UAAM,eAAe,IAAI,mBAAmB,cAAc,IAAI,CAAC,QAAQ,eAAe,GAAG,iBAAiB,CAAC;AAE3G,UAAM,kBAAkB,eAAe,cAAc,UAAU;AAC/D,UAAM,gBAAgB;AAAA,MAClB;AAAA,MACA,cAAc,IAAI,CAAC,QAAQ,gBAAgB,GAAG,mBAAmB;AAAA,IACrE;AAEA,YAAQ,IAAI,eAAe,MAAM,mBAAmB,UAAU,MAAM,CAAC,yBAAyB;AAAA,EAClG;AACJ;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -51,6 +51,7 @@ logger.info(
|
|
51
51
|
'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
|
52
52
|
);
|
53
53
|
class Device {
|
54
|
+
matterServer;
|
54
55
|
async start() {
|
55
56
|
logger.info(`node-matter`);
|
56
57
|
const storageManager = new StorageManager(storage);
|
@@ -2,6 +2,6 @@
|
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/MultiDeviceNodeLegacy.ts"],
|
4
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,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAA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AAC;AAEpC,QAAQ,GAAG,UAAU,MAAM;AAEvB,SACK,KAAK,EACL,KAAK,MAAM;AAER,YAAQ,MAAM;AACd,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -71,7 +71,7 @@ async function main() {
|
|
71
71
|
id: "tempsensor",
|
72
72
|
temperatureMeasurement: {
|
73
73
|
// Use this to initialize the measuredValue with the most uptodate value.
|
74
|
-
// If you do not know the value and also
|
74
|
+
// If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
|
75
75
|
measuredValue: getIntValueFromCommandOrRandom("value")
|
76
76
|
}
|
77
77
|
});
|
@@ -80,7 +80,7 @@ async function main() {
|
|
80
80
|
id: "humsensor",
|
81
81
|
relativeHumidityMeasurement: {
|
82
82
|
// Use this to initialize the measuredValue with the most uptodate value.
|
83
|
-
// If you do not know the value and also
|
83
|
+
// If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
|
84
84
|
measuredValue: getIntValueFromCommandOrRandom("value", false)
|
85
85
|
}
|
86
86
|
});
|
@@ -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;\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 can not 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 can not 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"],
|
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;\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
5
|
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAgBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB,eAA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AAA,EACJ;AACJ;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../src/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.ts"],
|
4
|
-
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getParameter } from \"@project-chip/matter-node.js/util\";\nimport {\n ClusterServer,\n
|
5
|
-
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,oBAAoB;AAC7B;AAAA,EACI;AAAA,EAEA;AAAA,EACA;AAAA,OACG;AACP,SAAS,iBAAiB;AAE1B,MAAM,iBAAiB,IAAI,UAAU,EAAE;AAEvC,MAAM,qBAAqB,qBAAqB,QAAQ,KAAK,qBAAqB,QAAQ,oBAAoB;AAO9G,MAAM,
|
4
|
+
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getParameter } from \"@project-chip/matter-node.js/util\";\nimport {\n ClusterServer,\n ClusterServerObj,\n GeneralCommissioningCluster,\n NetworkCommissioning,\n} from \"@project-chip/matter.js/cluster\";\nimport { ByteArray } from \"@project-chip/matter.js/util\";\n\nconst firstNetworkId = new ByteArray(32);\n\nconst WifiNetworkCluster = NetworkCommissioning.Cluster.with(NetworkCommissioning.Feature.WiFiNetworkInterface);\n\n/**\n * This represents a Dummy version of a Wifi Network Commissioning Cluster Server without real Wifi related logic, beside\n * returning some values provided as CLI parameters. This dummy implementation is only there for tests/as showcase for BLE\n * commissioning of a device.\n */\nconst Server: ClusterServerObj<typeof WifiNetworkCluster> = ClusterServer(\n NetworkCommissioning.Cluster.with(NetworkCommissioning.Feature.WiFiNetworkInterface),\n {\n maxNetworks: 1,\n interfaceEnabled: true,\n lastConnectErrorValue: 0,\n lastNetworkId: null,\n lastNetworkingStatus: null,\n networks: [{ networkId: firstNetworkId, connected: false }],\n scanMaxTimeSeconds: 3,\n connectMaxTimeSeconds: 3,\n supportedWiFiBands: [NetworkCommissioning.WiFiBand[\"2G4\"]],\n },\n {\n scanNetworks: async ({ request: { ssid, breadcrumb }, attributes: { lastNetworkingStatus }, endpoint }) => {\n console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${ssid?.toHex()} ${breadcrumb}`);\n\n // Simulate successful scan\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = endpoint.getClusterServer(GeneralCommissioningCluster);\n generalCommissioningCluster?.setBreadcrumbAttribute(breadcrumb);\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n lastNetworkingStatus?.setLocal(networkingStatus);\n\n return {\n networkingStatus,\n wiFiScanResults: [\n {\n security: {\n unencrypted: false,\n wep: false,\n wpaPersonal: false,\n wpa2Personal: true,\n wpa3Personal: true,\n },\n ssid: ssid || ByteArray.fromString(getParameter(\"ble-wifi-scan-ssid\") ?? \"TestSSID\"), // Set a valid existing local Wi-Fi SSID here\n bssid: ByteArray.fromString(getParameter(\"ble-wifi-scan-bssid\") ?? \"00:00:00:00:00:00\"),\n channel: 1,\n },\n ],\n };\n },\n addOrUpdateWiFiNetwork: async ({\n request: { ssid, credentials, breadcrumb },\n attributes: { lastNetworkingStatus, lastNetworkId },\n endpoint,\n session,\n }) => {\n console.log(\n `---> addOrUpdateWiFiNetwork called on NetworkCommissioning cluster: ${ssid.toHex()} ${credentials.toHex()} ${breadcrumb}`,\n );\n\n session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = endpoint.getClusterServer(GeneralCommissioningCluster);\n generalCommissioningCluster?.setBreadcrumbAttribute(breadcrumb);\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n lastNetworkingStatus?.setLocal(networkingStatus);\n lastNetworkId?.setLocal(firstNetworkId);\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n },\n removeNetwork: async ({\n request: { networkId, breadcrumb },\n attributes: { lastNetworkingStatus, lastNetworkId },\n endpoint,\n session,\n }) => {\n console.log(\n `---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`,\n );\n\n session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = endpoint.getClusterServer(GeneralCommissioningCluster);\n generalCommissioningCluster?.setBreadcrumbAttribute(breadcrumb);\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n lastNetworkingStatus?.setLocal(networkingStatus);\n lastNetworkId?.setLocal(firstNetworkId);\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n },\n connectNetwork: async ({\n request: { networkId, breadcrumb },\n attributes: { lastNetworkingStatus, lastNetworkId, lastConnectErrorValue, networks },\n endpoint,\n session,\n }) => {\n console.log(\n `---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`,\n );\n\n session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = endpoint.getClusterServer(GeneralCommissioningCluster);\n generalCommissioningCluster?.setBreadcrumbAttribute(breadcrumb);\n }\n\n const networkList = networks.getLocal();\n networkList[0].connected = true;\n networks.setLocal(networkList);\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n lastNetworkingStatus?.setLocal(networkingStatus);\n lastNetworkId?.setLocal(firstNetworkId);\n lastConnectErrorValue?.setLocal(null);\n\n // Announce operational in IP network\n const device = session.context;\n await device.startAnnouncement();\n\n return {\n networkingStatus,\n errorValue: null,\n };\n },\n reorderNetwork: async ({\n request: { networkId, networkIndex, breadcrumb },\n attributes: { lastNetworkingStatus },\n endpoint,\n }) => {\n console.log(\n `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`,\n );\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = endpoint.getClusterServer(GeneralCommissioningCluster);\n generalCommissioningCluster?.setBreadcrumbAttribute(breadcrumb);\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n lastNetworkingStatus?.setLocal(networkingStatus);\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n },\n },\n);\n\nexport default Server;\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,oBAAoB;AAC7B;AAAA,EACI;AAAA,EAEA;AAAA,EACA;AAAA,OACG;AACP,SAAS,iBAAiB;AAE1B,MAAM,iBAAiB,IAAI,UAAU,EAAE;AAEvC,MAAM,qBAAqB,qBAAqB,QAAQ,KAAK,qBAAqB,QAAQ,oBAAoB;AAO9G,MAAM,SAAsD;AAAA,EACxD,qBAAqB,QAAQ,KAAK,qBAAqB,QAAQ,oBAAoB;AAAA,EACnF;AAAA,IACI,aAAa;AAAA,IACb,kBAAkB;AAAA,IAClB,uBAAuB;AAAA,IACvB,eAAe;AAAA,IACf,sBAAsB;AAAA,IACtB,UAAU,CAAC,EAAE,WAAW,gBAAgB,WAAW,MAAM,CAAC;AAAA,IAC1D,oBAAoB;AAAA,IACpB,uBAAuB;AAAA,IACvB,oBAAoB,CAAC,qBAAqB,SAAS,KAAK,CAAC;AAAA,EAC7D;AAAA,EACA;AAAA,IACI,cAAc,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,GAAG,YAAY,EAAE,qBAAqB,GAAG,SAAS,MAAM;AACvG,cAAQ,IAAI,6DAA6D,MAAM,MAAM,CAAC,IAAI,UAAU,EAAE;AAGtG,UAAI,eAAe,QAAW;AAC1B,cAAM,8BAA8B,SAAS,iBAAiB,2BAA2B;AACzF,qCAA6B,uBAAuB,UAAU;AAAA,MAClE;AAEA,YAAM,mBAAmB,qBAAqB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,qCAA6B,uBAAuB,UAAU;AAAA,MAClE;AAEA,YAAM,mBAAmB,qBAAqB,2BAA2B;AACzE,4BAAsB,SAAS,gBAAgB;AAE/C,aAAO;AAAA,QACH;AAAA,QACA,cAAc;AAAA,MAClB;AAAA,IACJ;AAAA,EACJ;AACJ;AAEA,IAAO,oDAAQ;",
|
6
6
|
"names": []
|
7
7
|
}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@project-chip/matter-node.js-examples",
|
3
|
-
"version": "0.10.0-alpha.0-
|
3
|
+
"version": "0.10.0-alpha.0-20240803-f4969d2b",
|
4
4
|
"description": "CLI/Reference implementation scripts for Matter protocol for node.js",
|
5
5
|
"keywords": [
|
6
6
|
"iot",
|
@@ -64,14 +64,13 @@
|
|
64
64
|
"typescript": "~5.5.3"
|
65
65
|
},
|
66
66
|
"dependencies": {
|
67
|
-
"@project-chip/matter-node-ble.js": "0.10.0-alpha.0-
|
68
|
-
"@project-chip/matter-node.js": "0.10.0-alpha.0-
|
69
|
-
"@project-chip/matter.js": "0.10.0-alpha.0-
|
70
|
-
"@project-chip/matter.js-tools": "0.10.0-alpha.0-
|
67
|
+
"@project-chip/matter-node-ble.js": "0.10.0-alpha.0-20240803-f4969d2b",
|
68
|
+
"@project-chip/matter-node.js": "0.10.0-alpha.0-20240803-f4969d2b",
|
69
|
+
"@project-chip/matter.js": "0.10.0-alpha.0-20240803-f4969d2b",
|
70
|
+
"@project-chip/matter.js-tools": "0.10.0-alpha.0-20240803-f4969d2b"
|
71
71
|
},
|
72
72
|
"engines": {
|
73
|
-
"
|
74
|
-
"node": ">=16.0.0"
|
73
|
+
"node": ">=18.0.0"
|
75
74
|
},
|
76
75
|
"files": [
|
77
76
|
"dist/**/*",
|
@@ -83,5 +82,5 @@
|
|
83
82
|
"publishConfig": {
|
84
83
|
"access": "public"
|
85
84
|
},
|
86
|
-
"gitHead": "
|
85
|
+
"gitHead": "2813687f85e0d0946aaebad5662e0d226da03e0b"
|
87
86
|
}
|
@@ -24,9 +24,10 @@ import { CommissioningController, NodeCommissioningOptions } from "@project-chip
|
|
24
24
|
import { Ble } from "@project-chip/matter.js/ble";
|
25
25
|
import {
|
26
26
|
BasicInformationCluster,
|
27
|
+
ClusterClientObj,
|
27
28
|
DescriptorCluster,
|
28
29
|
GeneralCommissioning,
|
29
|
-
|
30
|
+
OnOff,
|
30
31
|
} from "@project-chip/matter.js/cluster";
|
31
32
|
import { NodeId } from "@project-chip/matter.js/datatype";
|
32
33
|
import { NodeStateInformation } from "@project-chip/matter.js/device";
|
@@ -286,7 +287,7 @@ class ControllerNode {
|
|
286
287
|
// console.log("Subscribe-All Data:", Logger.toJSON(data));
|
287
288
|
//});
|
288
289
|
|
289
|
-
const onOff = devices[0].getClusterClient(
|
290
|
+
const onOff: ClusterClientObj<OnOff.Complete> | undefined = devices[0].getClusterClient(OnOff.Complete);
|
290
291
|
if (onOff !== undefined) {
|
291
292
|
let onOffStatus = await onOff.getOnOffAttribute();
|
292
293
|
console.log("initial onOffStatus", onOffStatus);
|
@@ -78,7 +78,7 @@ if (legacyNodes.includes("Controller")) {
|
|
78
78
|
console.log(uniqueIds);
|
79
79
|
|
80
80
|
if (!Object.keys(uniqueIds).length) {
|
81
|
-
console.error("No uniqueId(s) found in legacy storage.
|
81
|
+
console.error("No uniqueId(s) found in legacy storage. Cannot convert the node storage.");
|
82
82
|
process.exit(1);
|
83
83
|
}
|
84
84
|
|
@@ -87,7 +87,7 @@ for (const nodeId of legacyNodes) {
|
|
87
87
|
const rootCertId = legacyStorage.get(["0", "RootCertificateManager"], "rootCertId");
|
88
88
|
|
89
89
|
if (nodeId !== "0" || rootCertId === undefined) {
|
90
|
-
console.error(`No uniqueId found for node ${nodeId}.
|
90
|
+
console.error(`No uniqueId found for node ${nodeId}. Cannot convert the node storage.`);
|
91
91
|
continue;
|
92
92
|
}
|
93
93
|
|
@@ -102,7 +102,7 @@ async function main() {
|
|
102
102
|
id: "tempsensor",
|
103
103
|
temperatureMeasurement: {
|
104
104
|
// Use this to initialize the measuredValue with the most uptodate value.
|
105
|
-
// If you do not know the value and also
|
105
|
+
// If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
|
106
106
|
measuredValue: getIntValueFromCommandOrRandom("value"),
|
107
107
|
},
|
108
108
|
});
|
@@ -111,7 +111,7 @@ async function main() {
|
|
111
111
|
id: "humsensor",
|
112
112
|
relativeHumidityMeasurement: {
|
113
113
|
// Use this to initialize the measuredValue with the most uptodate value.
|
114
|
-
// If you do not know the value and also
|
114
|
+
// If you do not know the value and also cannot request it, best use "null" (if allowed by the cluster).
|
115
115
|
measuredValue: getIntValueFromCommandOrRandom("value", false),
|
116
116
|
},
|
117
117
|
});
|
@@ -7,7 +7,7 @@
|
|
7
7
|
import { getParameter } from "@project-chip/matter-node.js/util";
|
8
8
|
import {
|
9
9
|
ClusterServer,
|
10
|
-
|
10
|
+
ClusterServerObj,
|
11
11
|
GeneralCommissioningCluster,
|
12
12
|
NetworkCommissioning,
|
13
13
|
} from "@project-chip/matter.js/cluster";
|
@@ -22,7 +22,7 @@ const WifiNetworkCluster = NetworkCommissioning.Cluster.with(NetworkCommissionin
|
|
22
22
|
* returning some values provided as CLI parameters. This dummy implementation is only there for tests/as showcase for BLE
|
23
23
|
* commissioning of a device.
|
24
24
|
*/
|
25
|
-
const Server:
|
25
|
+
const Server: ClusterServerObj<typeof WifiNetworkCluster> = ClusterServer(
|
26
26
|
NetworkCommissioning.Cluster.with(NetworkCommissioning.Feature.WiFiNetworkInterface),
|
27
27
|
{
|
28
28
|
maxNetworks: 1,
|