@project-chip/matter-node.js-examples 0.8.0-alpha.1-20240308-033110a3 → 0.8.1-alpha.0-20240401-c87f2ece
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +17 -0
- package/dist/esm/examples/{BridgedDeviceNode.js → BridgedDevicesNode.js} +21 -23
- package/dist/esm/examples/BridgedDevicesNode.js.map +7 -0
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js +9 -6
- package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNode.js +20 -22
- package/dist/esm/examples/ComposedDeviceNode.js.map +2 -2
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js +10 -7
- package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/ControllerNode.js +23 -56
- package/dist/esm/examples/ControllerNode.js.map +2 -2
- package/dist/esm/examples/ControllerNodeLegacy.js +2 -1
- package/dist/esm/examples/ControllerNodeLegacy.js.map +2 -2
- package/dist/esm/examples/DeviceNode.js +20 -22
- package/dist/esm/examples/DeviceNode.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFull.js +22 -24
- package/dist/esm/examples/DeviceNodeFull.js.map +2 -2
- package/dist/esm/examples/DeviceNodeFullLegacy.js +10 -7
- package/dist/esm/examples/DeviceNodeFullLegacy.js.map +2 -2
- package/dist/esm/examples/LegacyStorageConverter.js +126 -0
- package/dist/esm/examples/LegacyStorageConverter.js.map +7 -0
- package/dist/esm/examples/MultiDeviceNode.js +18 -22
- package/dist/esm/examples/MultiDeviceNode.js.map +2 -2
- package/dist/esm/examples/MultiDeviceNodeLegacy.js +2 -1
- package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +2 -2
- package/dist/esm/examples/SensorDeviceNode.js +17 -15
- package/dist/esm/examples/SensorDeviceNode.js.map +2 -2
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +1 -1
- package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +2 -2
- package/package.json +26 -10
- package/src/examples/{BridgedDeviceNode.ts → BridgedDevicesNode.ts} +23 -24
- package/src/examples/BridgedDevicesNodeLegacy.ts +9 -9
- package/src/examples/ComposedDeviceNode.ts +22 -23
- package/src/examples/ComposedDeviceNodeLegacy.ts +10 -10
- package/src/examples/ControllerNode.ts +32 -74
- package/src/examples/ControllerNodeLegacy.ts +2 -4
- package/src/examples/DeviceNode.ts +23 -24
- package/src/examples/DeviceNodeFull.ts +23 -24
- package/src/examples/DeviceNodeFullLegacy.ts +10 -11
- package/src/examples/LegacyStorageConverter.ts +156 -0
- package/src/examples/MultiDeviceNode.ts +21 -23
- package/src/examples/MultiDeviceNodeLegacy.ts +2 -4
- package/src/examples/SensorDeviceNode.ts +18 -15
- package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +2 -2
- package/dist/esm/examples/BridgedDeviceNode.js.map +0 -7
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/MultiDeviceNodeLegacy.ts"],
|
4
|
-
"sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a new device node that is composed of multiple devices.\n * It creates multiple endpoints on the server. When you want to add a composed devices to a Aggregator you need to\n * add all endpoints of the composed device to an \"ComposedDevice\" instance! (not shown in this example).\n * It can be used as CLI script and starting point for your own device node implementation.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { DeviceTypes, OnOffLightDevice, OnOffPluginUnitDevice } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n} from \"@project-chip/matter-node.js/util\";\nimport { VendorId } from \"@project-chip/matter.js/datatype\";\n\nconst logger = Logger.get(\"MultiDevice\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n const netInterface = getParameter(\"netinterface\");\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n /**\n * Create Matter Server and CommissioningServer Node\n *\n * To allow the device to be announced, found, paired and operated we need a MatterServer instance and add a\n * commissioningServer to it and add the just created device instance to it.\n * The CommissioningServer node defines the port where the server listens for the UDP packages of the Matter protocol\n * and initializes deice specific certificates and such.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled internally\n * like testEventTrigger (General Diagnostic Cluster) that can be implemented with the logic when these commands\n * are called.\n */\n\n this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });\n\n /**\n * Create Device instance and add needed Listener\n *\n * Create an instance of the matter device class you want to use.\n * This example uses the OnOffLightDevice or OnOffPluginUnitDevice depending on the value of the type parameter.\n * To execute the on/off scripts defined as parameters a listener for the onOff attribute is registered via the\n * device specific API.\n *\n * The below logic also adds command handlers for commands of clusters that normally are handled device internally\n * like identify that can be implemented with the logic when these commands are called.\n */\n\n const commissioningServers = new Array<CommissioningServer>();\n\n let defaultPasscode = 20202021;\n let defaultDiscriminator = 3840;\n let defaultPort = 5550;\n\n const numDevices = getIntParameter(\"num\") || 2;\n for (let i = 1; i <= numDevices; i++) {\n if (deviceStorage.has(`isSocket${i}`)) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(`isSocket${i}`, getParameter(`type${i}`) === \"socket\");\n const deviceName = `Matter ${getParameter(`type${i}`) ?? \"light\"} device ${i}`;\n const deviceType =\n getParameter(`type${i}`) === \"socket\"\n ? DeviceTypes.ON_OFF_PLUGIN_UNIT.code\n : DeviceTypes.ON_OFF_LIGHT.code;\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(`passcode${i}`) ?? deviceStorage.get(`passcode${i}`, defaultPasscode++);\n const discriminator =\n getIntParameter(`discriminator${i}`) ?? deviceStorage.get(`discriminator${i}`, defaultDiscriminator++);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(`vendorid${i}`) ?? deviceStorage.get(`vendorid${i}`, 0xfff1);\n const productName = `node-matter OnOff-Device ${i}`;\n const productId = getIntParameter(`productid${i}`) ?? deviceStorage.get(`productid${i}`, 0x8000);\n\n const port = getIntParameter(`port${i}`) ?? defaultPort++;\n\n const uniqueId =\n getIntParameter(`uniqueid${i}`) ?? deviceStorage.get(`uniqueid${i}`, `${i}-${Time.nowMs()}`);\n\n deviceStorage.set(`passcode${i}`, passcode);\n deviceStorage.set(`discriminator${i}`, discriminator);\n deviceStorage.set(`vendorid${i}`, vendorId);\n deviceStorage.set(`productid${i}`, productId);\n deviceStorage.set(`isSocket${i}`, isSocket);\n deviceStorage.set(`uniqueid${i}`, uniqueId);\n\n const commissioningServer = new CommissioningServer({\n port,\n deviceName,\n deviceType,\n passcode,\n discriminator,\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n },\n });\n\n console.log(\n `Added device ${i} on port ${port} and unique id ${uniqueId}: Passcode: ${passcode}, Discriminator: ${discriminator}`,\n );\n\n const onOffDevice =\n getParameter(`type${i}`) === \"socket\" ? new OnOffPluginUnitDevice() : new OnOffLightDevice();\n onOffDevice.addFixedLabel(\"orientation\", getParameter(`orientation${i}`) ?? `orientation ${i}`);\n onOffDevice.addOnOffListener(on => commandExecutor(on ? `on${i}` : `off${i}`)?.());\n commissioningServer.addDevice(onOffDevice);\n\n await this.matterServer.addCommissioningServer(commissioningServer);\n\n commissioningServers.push(commissioningServer);\n }\n\n /**\n * Start the Matter Server\n *\n * After everything was plugged together we can start the server. When not delayed announcement is set for the\n * CommissioningServer node then this command also starts the announcement of the device into the network.\n */\n\n await this.matterServer.start();\n\n /**\n * Print Pairing Information\n *\n * If the device is not already commissioned (this info is stored in the storage system) then get and print the\n * pairing details. This includes the QR code that can be scanned by the Matter app to pair the device.\n */\n\n logger.info(\"Listening\");\n console.log();\n commissioningServers.forEach((commissioningServer, index) => {\n console.log(\"----------------------------\");\n console.log(`Device ${index + 1}:`);\n if (!commissioningServer.isCommissioned()) {\n const pairingData = commissioningServer.getPairingCode();\n const { qrPairingCode, manualPairingCode } = pairingData;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(\n `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`,\n );\n console.log(`Manual pairing code: ${manualPairingCode}`);\n } else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n }\n console.log();\n });\n }\n\n async stop() {\n await this.matterServer?.close();\n }\n}\n\nconst device = new Device();\ndevice\n .start()\n .then(() => {\n /* done */\n })\n .catch(err => console.error(err));\n\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n device\n .stop()\n .then(() => {\n // Pragmatic way to make sure the storage is correctly closed before the process ends.\n storage\n .close()\n .then(() => process.exit(0))\n .catch(err => console.error(err));\n })\n .catch(err => console.error(err));\n});\n"],
|
5
|
-
"mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAsBA,SAAS,qBAAqB,oBAAoB;AAElD,SAAS,aAAa,kBAAkB,6BAA6B;AACrE,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,gBAAgB;AAEzB,MAAM,SAAS,OAAO,IAAI,aAAa;AAEvC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AAAA,EACJ,KAAK;AACD,WAAO,kBAAkB,MAAM;AAC/B;AACR;AAEA,QAAQ,aAAa,WAAW,GAAG;AAAA,EAC/B,KAAK;AACD,WAAO,SAAS,OAAO;AACvB;AAAA,EACJ,KAAK;AACD,WAAO,SA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K,CAAC,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC;AACjF,0BAAoB,UAAU,WAAW;AAEzC,YAAM,KAAK,aAAa,uBAAuB,mBAAmB;AAElE,2BAAqB,KAAK,mBAAmB;AAAA,IACjD;AASA,UAAM,KAAK,aAAa,MAAM;AAS9B,WAAO,KAAK,WAAW;AACvB,YAAQ,IAAI;AACZ,yBAAqB,QAAQ,CAAC,qBAAqB,UAAU;AACzD,cAAQ,IAAI,8BAA8B;AAC1C,cAAQ,IAAI,UAAU,QAAQ,CAAC,GAAG;AAClC,UAAI,CAAC,oBAAoB,eAAe,GAAG;AACvC,cAAM,cAAc,oBAAoB,eAAe;AACvD,cAAM,EAAE,eAAe,kBAAkB,IAAI;AAE7C,gBAAQ,IAAI,OAAO,IAAI,aAAa,CAAC;AACrC,gBAAQ;AAAA,UACJ,gFAAgF,aAAa;AAAA,QACjG;AACA,gBAAQ,IAAI,wBAAwB,iBAAiB,EAAE;AAAA,MAC3D,OAAO;AACH,gBAAQ,IAAI,wEAAwE;AAAA,MACxF;AACA,cAAQ,IAAI;AAAA,IAChB,CAAC;AAAA,EACL;AAAA,EAEA,MAAM,OAAO;AACT,UAAM,KAAK,cAAc,MAAM;AAAA,EACnC;AACJ;AAEA,MAAM,SAAS,IAAI,OAAO;AAC1B,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,
|
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,SAAS,QAAQ,OAAO,cAAc;AACtC,SAAS,cAAc;AACvB,SAAS,oBAAoB,sBAAsB;AACnD,SAAS,YAAY;AACrB;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,gBAAgB;AAEzB,MAAM,SAAS,OAAO,IAAI,aAAa;AAEvC,sBAAsB,EAAE;AAGxB,QAAQ,aAAa,UAAU,GAAG;AAAA,EAC9B,KAAK;AAC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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
|
}
|
@@ -123,33 +123,35 @@ async function getConfiguration() {
|
|
123
123
|
'Use the parameter "--storage-path=NAME-OR-PATH" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.'
|
124
124
|
);
|
125
125
|
const deviceStorage = (await storageService.open("device")).createContext("data");
|
126
|
-
const isTemperature = deviceStorage.get("isTemperature", environment.vars.get("type") !== "humidity");
|
127
|
-
if (deviceStorage.has("isTemperature")) {
|
126
|
+
const isTemperature = await deviceStorage.get("isTemperature", environment.vars.get("type") !== "humidity");
|
127
|
+
if (await deviceStorage.has("isTemperature")) {
|
128
128
|
console.log(
|
129
129
|
`Device type ${isTemperature ? "temperature" : "humidity"} found in storage. --type parameter is ignored.`
|
130
130
|
);
|
131
131
|
}
|
132
|
-
let interval = environment.vars.number("interval") ?? deviceStorage.get("interval", 60);
|
132
|
+
let interval = environment.vars.number("interval") ?? await deviceStorage.get("interval", 60);
|
133
133
|
if (interval < 1) {
|
134
134
|
console.log(`Invalid Interval ${interval}, set to 60s`);
|
135
135
|
interval = 60;
|
136
136
|
}
|
137
137
|
const deviceName = "Matter test device";
|
138
138
|
const vendorName = "matter-node.js";
|
139
|
-
const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
|
140
|
-
const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
|
141
|
-
const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
|
139
|
+
const passcode = environment.vars.number("passcode") ?? await deviceStorage.get("passcode", 20202021);
|
140
|
+
const discriminator = environment.vars.number("discriminator") ?? await deviceStorage.get("discriminator", 3840);
|
141
|
+
const vendorId = environment.vars.number("vendorid") ?? await deviceStorage.get("vendorid", 65521);
|
142
142
|
const productName = `node-matter OnOff ${isTemperature ? "Temperature" : "Humidity"}`;
|
143
|
-
const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
|
143
|
+
const productId = environment.vars.number("productid") ?? await deviceStorage.get("productid", 32768);
|
144
144
|
const port = environment.vars.number("port") ?? 5540;
|
145
|
-
const uniqueId = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
|
146
|
-
deviceStorage.set(
|
147
|
-
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
|
152
|
-
|
145
|
+
const uniqueId = environment.vars.string("uniqueid") ?? await deviceStorage.get("uniqueid", Time.nowMs().toString());
|
146
|
+
await deviceStorage.set({
|
147
|
+
passcode,
|
148
|
+
discriminator,
|
149
|
+
vendorid: vendorId,
|
150
|
+
productid: productId,
|
151
|
+
interval,
|
152
|
+
isTemperature,
|
153
|
+
uniqueid: uniqueId
|
154
|
+
});
|
153
155
|
return {
|
154
156
|
isTemperature,
|
155
157
|
interval,
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../src/examples/SensorDeviceNode.ts"],
|
4
|
-
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple Sensor Matter device as temperature or humidity device.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { HumiditySensorDevice } from \"@project-chip/matter.js/devices/HumiditySensorDevice\";\nimport { TemperatureSensorDevice } from \"@project-chip/matter.js/devices/TemperatureSensorDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(\n isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,\n ),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n let endpoint: Endpoint;\n if (isTemperature) {\n endpoint = new Endpoint(TemperatureSensorDevice, {\n id: \"tempsensor\",\n temperatureMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\") },\n });\n } else {\n endpoint = new Endpoint(HumiditySensorDevice, {\n id: \"humsensor\",\n relativeHumidityMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\", false) },\n });\n }\n\n await server.add(endpoint);\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n const updateInterval = setInterval(() => {\n let setter: Promise<void>;\n if (isTemperature) {\n setter = endpoint.set({\n temperatureMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n setter = endpoint.set({\n relativeHumidityMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n setter.catch(error => console.error(\"Error updating measured value:\", error));\n }, interval * 1000);\n\n // Cleanup our update interval when node goes offline\n server.lifecycle.offline.on(() => clearTimeout(updateInterval));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\n\nfunction getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) {\n if (!allowNegativeValues) return Math.round(Math.random() * 100);\n return (Math.round(Math.random() * 100) - 50) * 100;\n }\n let result = execSync(script).toString().trim();\n if ((result.startsWith(\"'\") && result.endsWith(\"'\")) || (result.startsWith('\"') && result.endsWith('\"')))\n result = result.slice(1, -1);\n console.log(`Command result: ${result}`);\n let value = Math.round(parseFloat(result));\n if (!allowNegativeValues && value < 0) value = 0;\n return value;\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isTemperature = deviceStorage.get(\"isTemperature\", environment.vars.get(\"type\") !== \"humidity\");\n if (deviceStorage.has(\"isTemperature\")) {\n console.log(\n `Device type ${isTemperature ? \"temperature\" : \"humidity\"} found in storage. --type parameter is ignored.`,\n );\n }\n let interval = environment.vars.number(\"interval\") ?? deviceStorage.get(\"interval\", 60);\n if (interval < 1) {\n console.log(`Invalid Interval ${interval}, set to 60s`);\n interval = 60;\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = environment.vars.number(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff ${isTemperature ? \"Temperature\" : \"Humidity\"}`;\n const productId = environment.vars.number(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId
|
5
|
-
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB,eAAe,OA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AAc,IAAI,iBAAiB,YAAY,KAAK,IAAI,MAAM,MAAM,UAAU;
|
4
|
+
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple Sensor Matter device as temperature or humidity device.\n * It can be used as CLI script and starting point for your own device node implementation.\n * This example is CJS conform and do not use top level await's.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport \"@project-chip/matter-node.js\";\n\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { HumiditySensorDevice } from \"@project-chip/matter.js/devices/HumiditySensorDevice\";\nimport { TemperatureSensorDevice } from \"@project-chip/matter.js/devices/TemperatureSensorDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n } = await getConfiguration();\n\n /**\n * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration\n */\n const server = await ServerNode.create({\n // Required: Give the Node a unique ID which is used to store the state of this node\n id: uniqueId,\n\n // Provide Network relevant configuration like the port\n // Optional when operating only one device on a host, Default port is 5540\n network: {\n port,\n },\n\n // Provide Commissioning relevant settings\n // Optional for development/testing purposes\n commissioning: {\n passcode,\n discriminator,\n },\n\n // Provide Node announcement settings\n // Optional: If Ommitted some development defaults are used\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(\n isTemperature ? TemperatureSensorDevice.deviceType : HumiditySensorDevice.deviceType,\n ),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\n * Matter Nodes are a composition of endpoints. Create and add a single endpoint to the node. This example uses the\n * OnOffLightDevice or OnOffPlugInUnitDevice depending on the value of the type parameter. It also assigns this Part a\n * unique ID to store the endpoint number for it in the storage to restore the device on restart.\n * In this case we directly use the default command implementation from matter.js. Check out the DeviceNodeFull example\n * to see how to customize the command handlers.\n */\n let endpoint: Endpoint;\n if (isTemperature) {\n endpoint = new Endpoint(TemperatureSensorDevice, {\n id: \"tempsensor\",\n temperatureMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\") },\n });\n } else {\n endpoint = new Endpoint(HumiditySensorDevice, {\n id: \"humsensor\",\n relativeHumidityMeasurement: { measuredValue: getIntValueFromCommandOrRandom(\"value\", false) },\n });\n }\n\n await server.add(endpoint);\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n const updateInterval = setInterval(() => {\n let setter: Promise<void>;\n if (isTemperature) {\n setter = endpoint.set({\n temperatureMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\"),\n },\n });\n } else {\n setter = endpoint.set({\n relativeHumidityMeasurement: {\n measuredValue: getIntValueFromCommandOrRandom(\"value\", false),\n },\n });\n }\n setter.catch(error => console.error(\"Error updating measured value:\", error));\n }, interval * 1000);\n\n // Cleanup our update interval when node goes offline\n server.lifecycle.offline.on(() => clearTimeout(updateInterval));\n\n /**\n * In order to start the node and announce it into the network we use the run method which resolves when the node goes\n * offline again because we do not need anything more here. See the Full example for other starting options.\n * The QR Code is printed automatically.\n */\n await server.run();\n}\n\nmain().catch(error => console.error(error));\n\n/*********************************************************************************************************\n * Convenience Methods\n *********************************************************************************************************/\n\n/** Defined a shell command from an environment variable and execute it and log the response. */\n\nfunction getIntValueFromCommandOrRandom(scriptParamName: string, allowNegativeValues = true) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) {\n if (!allowNegativeValues) return Math.round(Math.random() * 100);\n return (Math.round(Math.random() * 100) - 50) * 100;\n }\n let result = execSync(script).toString().trim();\n if ((result.startsWith(\"'\") && result.endsWith(\"'\")) || (result.startsWith('\"') && result.endsWith('\"')))\n result = result.slice(1, -1);\n console.log(`Command result: ${result}`);\n let value = Math.round(parseFloat(result));\n if (!allowNegativeValues && value < 0) value = 0;\n return value;\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isTemperature = await deviceStorage.get(\"isTemperature\", environment.vars.get(\"type\") !== \"humidity\");\n if (await deviceStorage.has(\"isTemperature\")) {\n console.log(\n `Device type ${isTemperature ? \"temperature\" : \"humidity\"} found in storage. --type parameter is ignored.`,\n );\n }\n let interval = environment.vars.number(\"interval\") ?? (await deviceStorage.get(\"interval\", 60));\n if (interval < 1) {\n console.log(`Invalid Interval ${interval}, set to 60s`);\n interval = 60;\n }\n\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = environment.vars.number(\"passcode\") ?? (await deviceStorage.get(\"passcode\", 20202021));\n const discriminator = environment.vars.number(\"discriminator\") ?? (await deviceStorage.get(\"discriminator\", 3840));\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = environment.vars.number(\"vendorid\") ?? (await deviceStorage.get(\"vendorid\", 0xfff1));\n const productName = `node-matter OnOff ${isTemperature ? \"Temperature\" : \"Humidity\"}`;\n const productId = environment.vars.number(\"productid\") ?? (await deviceStorage.get(\"productid\", 0x8000));\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId =\n environment.vars.string(\"uniqueid\") ?? (await deviceStorage.get(\"uniqueid\", Time.nowMs().toString()));\n\n // Persist basic data to keep them also on restart\n await deviceStorage.set({\n passcode,\n discriminator,\n vendorid: vendorId,\n productid: productId,\n interval,\n isTemperature,\n uniqueid: uniqueId,\n });\n\n return {\n isTemperature,\n interval,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAsB,EAAE;AAExB,eAAe,OAAO;AAElB,QAAM;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ,IAAI,MAAM,iBAAiB;AAK3B,QAAM,SAAS,MAAM,WAAW,OAAO;AAAA;AAAA,IAEnC,IAAI;AAAA;AAAA;AAAA,IAIJ,SAAS;AAAA,MACL;AAAA,IACJ;AAAA;AAAA;AAAA,IAIA,eAAe;AAAA,MACX;AAAA,MACA;AAAA,IACJ;AAAA;AAAA;AAAA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Aa;AACnB,QAAM,aAAa;AACnB,QAAM,WAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,QAAQ;AACrG,QAAM,gBAAgB,YAAY,KAAK,OAAO,eAAe,KAAM,MAAM,cAAc,IAAI,iBAAiB,IAAI;AAEhH,QAAM,WAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAM;AACnG,QAAM,cAAc,qBAAqB,gBAAgB,gBAAgB,UAAU;AACnF,QAAM,YAAY,YAAY,KAAK,OAAO,WAAW,KAAM,MAAM,cAAc,IAAI,aAAa,KAAM;AAEtG,QAAM,OAAO,YAAY,KAAK,OAAO,MAAM,KAAK;AAEhD,QAAM,WACF,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAGvG,QAAM,cAAc,IAAI;AAAA,IACpB;AAAA,IACA;AAAA,IACA,UAAU;AAAA,IACV,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;",
|
6
6
|
"names": []
|
7
7
|
}
|
@@ -44,7 +44,7 @@ class DummyThreadNetworkCommissioningServer extends NetworkCommissioningBehavior
|
|
44
44
|
}
|
45
45
|
addOrUpdateThreadNetwork({ operationalDataset, breadcrumb }) {
|
46
46
|
console.log(
|
47
|
-
`--->
|
47
|
+
`---> addOrUpdateThreadNetwork called on NetworkCommissioning cluster: ${operationalDataset.toHex()} ${breadcrumb}`
|
48
48
|
);
|
49
49
|
this.session.context.assertFailSafeArmed("Failsafe timer needs to be armed to add or update networks.");
|
50
50
|
if (breadcrumb !== void 0) {
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../src/examples/cluster/DummyThreadNetworkCommissioningServer.ts"],
|
4
|
-
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GeneralCommissioningBehavior } from \"@project-chip/matter.js/behavior/definitions/general-commissioning\";\nimport {\n AddOrUpdateThreadNetworkRequest,\n ConnectNetworkRequest,\n NetworkCommissioningBehavior,\n RemoveNetworkRequest,\n ReorderNetworkRequest,\n ScanNetworksRequest,\n ScanNetworksResponse,\n} from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { ByteArray } from \"@project-chip/matter.js/util\";\n\nconst firstNetworkId = new ByteArray(32);\n\n/**\n * This represents a Dummy version of a
|
5
|
-
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,oCAAoC;AAC7C;AAAA,EAGI;AAAA,OAKG;AACP,SAAS,4BAA4B;AACrC,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAE1B,MAAM,iBAAiB,IAAI,UAAU,EAAE;AAOhC,MAAM,8CAA8C,6BAA6B;AAAA,EACpF,qBAAqB,QAAQ;AACjC,EAAE;AAAA,EACW,aAAa,EAAE,WAAW,GAA8C;AAC7E,YAAQ,IAAI,6DAA6D,UAAU,EAAE;AAGrF,QAAI,eAAe,QAAW;AAC1B,YAAM,8BAA8B,KAAK,MAAM,IAAI,4BAA4B;AAC/E,kCAA4B,MAAM,aAAa;AAAA,IACnD;AAEA,UAAM,mBAAmB,qBAAqB,2BAA2B;AACzE,SAAK,MAAM,uBAAuB;AAElC,UAAM,oBAAoB;AAAA,MACtB;AAAA,QACI,OAAO,KAAK,SAAS,IAAI,KAAK,OAAO,kBAAkB;AAAA,QACvD,eAAe,OAAO,KAAK,SAAS,IAAI,KAAK,OAAO,0BAA0B,CAAC;AAAA,QAC/E,aAAa,KAAK,SAAS,IAAI,KAAK,OAAO,wBAAwB;AAAA,QACnE,SAAS,KAAK,SAAS,IAAI,KAAK,OAAO,oBAAoB;AAAA,QAC3D,SAAS;AAAA,QACT,iBAAiB,UAAU;AAAA,WACtB,KAAK,SAAS,IAAI,KAAK,OAAO,oBAAoB,KAAK,gBAAgB,YAAY;AAAA,QACxF;AAAA,QACA,MAAM;AAAA,QACN,KAAK;AAAA,MACT;AAAA,IACJ;AACA,YAAQ,IAAI,OAAO,OAAO,iBAAiB,CAAC;AAE5C,WAAO;AAAA,MACH;AAAA,MACA;AAAA,IACJ;AAAA,EACJ;AAAA,EAES,yBAAyB,EAAE,oBAAoB,WAAW,GAAoC;AACnG,YAAQ;AAAA,MACJ,
|
4
|
+
"sourcesContent": ["/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GeneralCommissioningBehavior } from \"@project-chip/matter.js/behavior/definitions/general-commissioning\";\nimport {\n AddOrUpdateThreadNetworkRequest,\n ConnectNetworkRequest,\n NetworkCommissioningBehavior,\n RemoveNetworkRequest,\n ReorderNetworkRequest,\n ScanNetworksRequest,\n ScanNetworksResponse,\n} from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { Logger } from \"@project-chip/matter.js/log\";\nimport { ByteArray } from \"@project-chip/matter.js/util\";\n\nconst firstNetworkId = new ByteArray(32);\n\n/**\n * This represents a Dummy version of a Thread Network Commissioning Cluster Server without real thread related logic, beside\n * returning some values provided as CLI parameters. This dummy implementation is only there for tests/as showcase for BLE\n * commissioning of a device.\n */\nexport class DummyThreadNetworkCommissioningServer extends NetworkCommissioningBehavior.with(\n NetworkCommissioning.Feature.ThreadNetworkInterface,\n) {\n override scanNetworks({ breadcrumb }: ScanNetworksRequest): ScanNetworksResponse {\n console.log(`---> scanNetworks called on NetworkCommissioning cluster: ${breadcrumb}`);\n\n // Simulate successful scan\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n\n const threadScanResults = [\n {\n panId: this.endpoint.env.vars.number(\"ble.thread.panId\"),\n extendedPanId: BigInt(this.endpoint.env.vars.string(\"ble.thread.extendedPanId\")),\n networkName: this.endpoint.env.vars.string(\"ble.thread.networkName\"),\n channel: this.endpoint.env.vars.number(\"ble.thread.channel\"),\n version: 130,\n extendedAddress: ByteArray.fromString(\n (this.endpoint.env.vars.string(\"ble.thread.address\") ?? \"000000000000\").toLowerCase(),\n ),\n rssi: -50,\n lqi: 50,\n },\n ];\n console.log(Logger.toJSON(threadScanResults));\n\n return {\n networkingStatus,\n threadScanResults,\n };\n }\n\n override addOrUpdateThreadNetwork({ operationalDataset, breadcrumb }: AddOrUpdateThreadNetworkRequest) {\n console.log(\n `---> addOrUpdateThreadNetwork called on NetworkCommissioning cluster: ${operationalDataset.toHex()} ${breadcrumb}`,\n );\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n\n override removeNetwork({ networkId, breadcrumb }: RemoveNetworkRequest) {\n console.log(`---> removeNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful add or update\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n\n override async connectNetwork({ networkId, breadcrumb }: ConnectNetworkRequest) {\n console.log(`---> connectNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${breadcrumb}`);\n\n this.session.context.assertFailSafeArmed(\"Failsafe timer needs to be armed to add or update networks.\");\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n this.state.networks[0].connected = true;\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n this.state.lastNetworkId = firstNetworkId;\n this.state.lastConnectErrorValue = null;\n\n // Announce operational in IP network\n const device = this.session.context;\n await device.startAnnouncement();\n\n return {\n networkingStatus,\n errorValue: null,\n };\n }\n\n override reorderNetwork({ networkId, networkIndex, breadcrumb }: ReorderNetworkRequest) {\n console.log(\n `---> reorderNetwork called on NetworkCommissioning cluster: ${networkId.toHex()} ${networkIndex} ${breadcrumb}`,\n );\n\n // Simulate successful connection\n if (breadcrumb !== undefined) {\n const generalCommissioningCluster = this.agent.get(GeneralCommissioningBehavior);\n generalCommissioningCluster.state.breadcrumb = breadcrumb;\n }\n\n const networkingStatus = NetworkCommissioning.NetworkCommissioningStatus.Success;\n this.state.lastNetworkingStatus = networkingStatus;\n\n return {\n networkingStatus,\n networkIndex: 0,\n };\n }\n}\n"],
|
5
|
+
"mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,SAAS,oCAAoC;AAC7C;AAAA,EAGI;AAAA,OAKG;AACP,SAAS,4BAA4B;AACrC,SAAS,cAAc;AAC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,IAAI,UAAU;AAAA,IAClH;AAGA,QAAI,eAAe,QAAW;AAC1B,YAAM,8BAA8B,KAAK,MAAM,IAAI,4BAA4B;AAC/E,kCAA4B,MAAM,aAAa;AAAA,IACnD;AAEA,UAAM,mBAAmB,qBAAqB,2BAA2B;AACzE,SAAK,MAAM,uBAAuB;AAElC,WAAO;AAAA,MACH;AAAA,MACA,cAAc;AAAA,IAClB;AAAA,EACJ;AACJ;",
|
6
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.8.
|
3
|
+
"version": "0.8.1-alpha.0-20240401-c87f2ece",
|
4
4
|
"description": "CLI/Reference implementation scripts for Matter protocol for node.js",
|
5
5
|
"keywords": [
|
6
6
|
"iot",
|
@@ -27,31 +27,47 @@
|
|
27
27
|
"clean": "matter-build clean",
|
28
28
|
"build": "matter-build",
|
29
29
|
"build-clean": "matter-build --clean",
|
30
|
-
"light": "matter-run src/examples/LightDevice.ts",
|
31
|
-
"
|
30
|
+
"matter-light": "matter-run src/examples/LightDevice.ts",
|
31
|
+
"matter-sensor": "matter-run src/examples/SensorDeviceNode.ts",
|
32
|
+
"matter-excelsior1000": "matter-run src/examples/IlluminatedRollerShade.ts",
|
32
33
|
"matter-device": "matter-run src/examples/DeviceNode.ts",
|
33
34
|
"matter-bridge": "matter-run src/examples/BridgedDevicesNode.ts",
|
34
35
|
"matter-composeddevice": "matter-run src/examples/ComposedDeviceNode.ts",
|
35
36
|
"matter-multidevice": "matter-run src/examples/MultiDeviceNode.ts",
|
36
37
|
"matter-controller": "matter-run src/examples/ControllerNode.ts",
|
38
|
+
"matter-device-legacy": "matter-run src/examples/DeviceNodeLegacy.ts",
|
39
|
+
"matter-bridge-legacy": "matter-run src/examples/BridgedDevicesNodeLegacy.ts",
|
40
|
+
"matter-composeddevice-legacy": "matter-run src/examples/ComposedDeviceNodeLegacy.ts",
|
41
|
+
"matter-multidevice-legacy": "matter-run src/examples/MultiDeviceNodeLegacy.ts",
|
42
|
+
"matter-controller-legacy": "matter-run src/examples/ControllerNodeLegacy.ts",
|
43
|
+
"matter-legacystorageconverter": "matter-run src/examples/LegacyStorageConverter.ts",
|
37
44
|
"bundle-device": "esbuild src/examples/DeviceNode.ts --bundle --platform=node --conditions=esbuild --external:@stoprocent/bleno --external:@stoprocent/bluetooth-hci-socket --sourcemap --minify --outfile=build/bundle/DeviceNode.cjs",
|
38
45
|
"matter-device-bundled": "node --enable-source-maps build/bundle/DeviceNode.cjs"
|
39
46
|
},
|
40
47
|
"bin": {
|
48
|
+
"matter-light": "./dist/esm/examples/LightDevice.ts",
|
49
|
+
"matter-excelsior1000": "./dist/esm/examples/IlluminatedRollerShade.ts",
|
50
|
+
"matter-sensor": "./dist/esm/examples/SensorDeviceNode.js",
|
41
51
|
"matter-device": "./dist/esm/examples/DeviceNode.js",
|
42
52
|
"matter-bridge": "./dist/esm/examples/BridgedDevicesNode.js",
|
43
53
|
"matter-composeddevice": "./dist/esm/examples/ComposedDeviceNode.js",
|
44
54
|
"matter-multidevice": "./dist/esm/examples/MultiDeviceNode.js",
|
45
|
-
"matter-controller": "./dist/esm/examples/ControllerNode.js"
|
55
|
+
"matter-controller": "./dist/esm/examples/ControllerNode.js",
|
56
|
+
"matter-device-legacy": "./dist/esm/examples/DeviceNodeLegacy.js",
|
57
|
+
"matter-bridge-legacy": "./dist/esm/examples/BridgedDevicesNodeLegacy.js",
|
58
|
+
"matter-composeddevice-legacy": "./dist/esm/examples/ComposedDeviceNodeLegacy.js",
|
59
|
+
"matter-multidevice-legacy": "./dist/esm/examples/MultiDeviceNodeLegacy.js",
|
60
|
+
"matter-controller-legacy": "./dist/esm/examples/ControllerNodeLegacy.js",
|
61
|
+
"matter-legacystorageconverter": "./dist/esm/examples/LegacyStorageConverter.js"
|
46
62
|
},
|
47
63
|
"devDependencies": {
|
48
|
-
"typescript": "
|
64
|
+
"typescript": "~5.4.3"
|
49
65
|
},
|
50
66
|
"dependencies": {
|
51
|
-
"@project-chip/matter-node-ble.js": "0.8.
|
52
|
-
"@project-chip/matter-node.js": "0.8.
|
53
|
-
"@project-chip/matter.js": "0.8.
|
54
|
-
"@project-chip/matter.js-tools": "0.8.
|
67
|
+
"@project-chip/matter-node-ble.js": "0.8.1-alpha.0-20240401-c87f2ece",
|
68
|
+
"@project-chip/matter-node.js": "0.8.1-alpha.0-20240401-c87f2ece",
|
69
|
+
"@project-chip/matter.js": "0.8.1-alpha.0-20240401-c87f2ece",
|
70
|
+
"@project-chip/matter.js-tools": "0.8.1-alpha.0-20240401-c87f2ece"
|
55
71
|
},
|
56
72
|
"engines": {
|
57
73
|
"_comment": "For Crypto.hkdf support",
|
@@ -67,5 +83,5 @@
|
|
67
83
|
"publishConfig": {
|
68
84
|
"access": "public"
|
69
85
|
},
|
70
|
-
"gitHead": "
|
86
|
+
"gitHead": "1a6f113eb3155489112d41c555add70cb5c43d52"
|
71
87
|
}
|
@@ -115,21 +115,17 @@ for (let idx = 0; idx < isSocket.length; idx++) {
|
|
115
115
|
await aggregator.add(endpoint);
|
116
116
|
|
117
117
|
/**
|
118
|
-
* Register state change handlers of the endpoint for identify and onoff states to react to the commands.
|
118
|
+
* Register state change handlers and events of the endpoint for identify and onoff states to react to the commands.
|
119
119
|
*
|
120
120
|
* If the code in these change handlers fail then the change is also rolled back and not executed and an error is
|
121
121
|
* reported back to the controller.
|
122
122
|
*/
|
123
|
-
|
124
|
-
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
} else if (value === 0) {
|
130
|
-
isIdentifying = false;
|
131
|
-
console.log(`${name}: Stop identify logic ...`);
|
132
|
-
}
|
123
|
+
endpoint.events.identify.startIdentifying.on(() => {
|
124
|
+
console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);
|
125
|
+
});
|
126
|
+
|
127
|
+
endpoint.events.identify.stopIdentifying.on(() => {
|
128
|
+
console.log(`Stop identify logic for ${name} ...`);
|
133
129
|
});
|
134
130
|
|
135
131
|
endpoint.events.onOff.onOff$Change.on(value => {
|
@@ -215,9 +211,9 @@ async function getConfiguration() {
|
|
215
211
|
|
216
212
|
const isSocket = Array<boolean>();
|
217
213
|
const numDevices = environment.vars.number("num") || 2;
|
218
|
-
if (deviceStorage.has("isSocket")) {
|
214
|
+
if (await deviceStorage.has("isSocket")) {
|
219
215
|
console.log(`Device types found in storage. --type parameter is ignored.`);
|
220
|
-
deviceStorage.get<Array<boolean>>("isSocket").forEach(type => isSocket.push(type));
|
216
|
+
(await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
|
221
217
|
}
|
222
218
|
for (let i = 1; i <= numDevices; i++) {
|
223
219
|
if (isSocket[i - 1] !== undefined) continue;
|
@@ -226,24 +222,27 @@ async function getConfiguration() {
|
|
226
222
|
|
227
223
|
const deviceName = "Matter test device";
|
228
224
|
const vendorName = "matter-node.js";
|
229
|
-
const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
|
230
|
-
const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
|
225
|
+
const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
|
226
|
+
const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
|
231
227
|
// product name / id and vendor id should match what is in the device certificate
|
232
|
-
const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 0xfff1);
|
228
|
+
const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
|
233
229
|
const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
|
234
|
-
const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 0x8000);
|
230
|
+
const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
|
235
231
|
|
236
232
|
const port = environment.vars.number("port") ?? 5540;
|
237
233
|
|
238
|
-
const uniqueId =
|
234
|
+
const uniqueId =
|
235
|
+
environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
|
239
236
|
|
240
237
|
// Persist basic data to keep them also on restart
|
241
|
-
deviceStorage.set(
|
242
|
-
|
243
|
-
|
244
|
-
|
245
|
-
|
246
|
-
|
238
|
+
await deviceStorage.set({
|
239
|
+
passcode,
|
240
|
+
discriminator,
|
241
|
+
vendorid: vendorId,
|
242
|
+
productid: productId,
|
243
|
+
isSocket,
|
244
|
+
uniqueid: uniqueId,
|
245
|
+
});
|
247
246
|
|
248
247
|
return {
|
249
248
|
isSocket,
|
@@ -117,11 +117,13 @@ class BridgedDevice {
|
|
117
117
|
|
118
118
|
const uniqueId = getIntParameter("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs());
|
119
119
|
|
120
|
-
deviceStorage.set(
|
121
|
-
|
122
|
-
|
123
|
-
|
124
|
-
|
120
|
+
deviceStorage.set({
|
121
|
+
passcode,
|
122
|
+
discriminator,
|
123
|
+
vendorid: vendorId,
|
124
|
+
productid: productId,
|
125
|
+
uniqueid: uniqueId,
|
126
|
+
});
|
125
127
|
|
126
128
|
/**
|
127
129
|
* Create Matter Server and CommissioningServer Node
|
@@ -245,10 +247,8 @@ process.on("SIGINT", () => {
|
|
245
247
|
.stop()
|
246
248
|
.then(() => {
|
247
249
|
// Pragmatic way to make sure the storage is correctly closed before the process ends.
|
248
|
-
storage
|
249
|
-
|
250
|
-
.then(() => process.exit(0))
|
251
|
-
.catch(err => console.error(err));
|
250
|
+
storage.close();
|
251
|
+
process.exit(0);
|
252
252
|
})
|
253
253
|
.catch(err => console.error(err));
|
254
254
|
});
|
@@ -97,16 +97,12 @@ for (let idx = 0; idx < isSocket.length; idx++) {
|
|
97
97
|
* If the code in these change handlers fail then the change is also rolled back and not executed and an error is
|
98
98
|
* reported back to the controller.
|
99
99
|
*/
|
100
|
-
|
101
|
-
|
102
|
-
|
103
|
-
|
104
|
-
|
105
|
-
|
106
|
-
} else if (value === 0) {
|
107
|
-
isIdentifying = false;
|
108
|
-
console.log(`OnOff ${i}: Stop identify logic ...`);
|
109
|
-
}
|
100
|
+
endpoint.events.identify.startIdentifying.on(() => {
|
101
|
+
console.log(`Run identify logic for sub device ${i}, ideally blink a light every 0.5s ...`);
|
102
|
+
});
|
103
|
+
|
104
|
+
endpoint.events.identify.stopIdentifying.on(() => {
|
105
|
+
console.log(`Stop identify logic for sub device ${i}...`);
|
110
106
|
});
|
111
107
|
|
112
108
|
endpoint.events.onOff.onOff$Change.on(value => {
|
@@ -152,9 +148,9 @@ async function getConfiguration() {
|
|
152
148
|
|
153
149
|
const isSocket = Array<boolean>();
|
154
150
|
const numDevices = environment.vars.number("num") || 2;
|
155
|
-
if (deviceStorage.has("isSocket")) {
|
151
|
+
if (await deviceStorage.has("isSocket")) {
|
156
152
|
console.log(`Device types found in storage. --type parameter is ignored.`);
|
157
|
-
deviceStorage.get<Array<boolean>>("isSocket").forEach(type => isSocket.push(type));
|
153
|
+
(await deviceStorage.get<Array<boolean>>("isSocket")).forEach(type => isSocket.push(type));
|
158
154
|
}
|
159
155
|
for (let i = 1; i < numDevices; i++) {
|
160
156
|
if (isSocket[i - 1] !== undefined) continue;
|
@@ -163,24 +159,27 @@ async function getConfiguration() {
|
|
163
159
|
|
164
160
|
const deviceName = "Matter test device";
|
165
161
|
const vendorName = "matter-node.js";
|
166
|
-
const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
|
167
|
-
const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
|
162
|
+
const passcode = environment.vars.number("passcode") ?? (await deviceStorage.get("passcode", 20202021));
|
163
|
+
const discriminator = environment.vars.number("discriminator") ?? (await deviceStorage.get("discriminator", 3840));
|
168
164
|
// product name / id and vendor id should match what is in the device certificate
|
169
|
-
const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 0xfff1);
|
165
|
+
const vendorId = environment.vars.number("vendorid") ?? (await deviceStorage.get("vendorid", 0xfff1));
|
170
166
|
const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
|
171
|
-
const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 0x8000);
|
167
|
+
const productId = environment.vars.number("productid") ?? (await deviceStorage.get("productid", 0x8000));
|
172
168
|
|
173
169
|
const port = environment.vars.number("port") ?? 5540;
|
174
170
|
|
175
|
-
const uniqueId =
|
171
|
+
const uniqueId =
|
172
|
+
environment.vars.string("uniqueid") ?? (await deviceStorage.get("uniqueid", Time.nowMs().toString()));
|
176
173
|
|
177
174
|
// Persist basic data to keep them also on restart
|
178
|
-
deviceStorage.set(
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
175
|
+
await deviceStorage.set({
|
176
|
+
passcode,
|
177
|
+
discriminator,
|
178
|
+
vendorid: vendorId,
|
179
|
+
productid: productId,
|
180
|
+
isSocket,
|
181
|
+
uniqueid: uniqueId,
|
182
|
+
});
|
184
183
|
|
185
184
|
return {
|
186
185
|
isSocket,
|
@@ -124,12 +124,14 @@ class ComposedDevice {
|
|
124
124
|
|
125
125
|
const uniqueId = getIntParameter("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs());
|
126
126
|
|
127
|
-
deviceStorage.set(
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
127
|
+
deviceStorage.set({
|
128
|
+
passcode,
|
129
|
+
discriminator,
|
130
|
+
vendorid: vendorId,
|
131
|
+
productid: productId,
|
132
|
+
isSocket,
|
133
|
+
uniqueid: uniqueId,
|
134
|
+
});
|
133
135
|
|
134
136
|
/**
|
135
137
|
* Create Matter Server and CommissioningServer Node
|
@@ -243,10 +245,8 @@ process.on("SIGINT", () => {
|
|
243
245
|
.stop()
|
244
246
|
.then(() => {
|
245
247
|
// Pragmatic way to make sure the storage is correctly closed before the process ends.
|
246
|
-
storage
|
247
|
-
|
248
|
-
.then(() => process.exit(0))
|
249
|
-
.catch(err => console.error(err));
|
248
|
+
storage.close();
|
249
|
+
process.exit(0);
|
250
250
|
})
|
251
251
|
.catch(err => console.error(err));
|
252
252
|
});
|