@project-chip/matter-node.js-examples 0.7.5-alpha.0-20240222-8696097f → 0.8.0-alpha.0-20240309-64eaef67

Sign up to get free protection for your applications and to get access to all the features.
Files changed (74) hide show
  1. package/README.md +44 -0
  2. package/dist/esm/examples/BridgedDeviceNode.js +147 -0
  3. package/dist/esm/examples/BridgedDeviceNode.js.map +7 -0
  4. package/dist/esm/examples/{BridgedDevicesNode.js → BridgedDevicesNodeLegacy.js} +2 -2
  5. package/dist/esm/examples/BridgedDevicesNodeLegacy.js.map +7 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js +116 -127
  7. package/dist/esm/examples/ComposedDeviceNode.js.map +3 -3
  8. package/dist/esm/examples/ComposedDeviceNodeLegacy.js +138 -0
  9. package/dist/esm/examples/ComposedDeviceNodeLegacy.js.map +7 -0
  10. package/dist/esm/examples/ControllerNode.js +24 -20
  11. package/dist/esm/examples/ControllerNode.js.map +2 -2
  12. package/dist/esm/examples/ControllerNodeLegacy.js +227 -0
  13. package/dist/esm/examples/ControllerNodeLegacy.js.map +7 -0
  14. package/dist/esm/examples/DeviceNode.js +118 -159
  15. package/dist/esm/examples/DeviceNode.js.map +2 -2
  16. package/dist/esm/examples/DeviceNodeFull.js +253 -0
  17. package/dist/esm/examples/DeviceNodeFull.js.map +7 -0
  18. package/dist/esm/examples/DeviceNodeFullLegacy.js +171 -0
  19. package/dist/esm/examples/DeviceNodeFullLegacy.js.map +7 -0
  20. package/dist/esm/examples/IlluminatedRollerShade.js +85 -0
  21. package/dist/esm/examples/IlluminatedRollerShade.js.map +7 -0
  22. package/dist/esm/examples/LightDevice.js +34 -0
  23. package/dist/esm/examples/LightDevice.js.map +7 -0
  24. package/dist/esm/examples/MultiDeviceNode.js +133 -134
  25. package/dist/esm/examples/MultiDeviceNode.js.map +3 -3
  26. package/dist/esm/examples/MultiDeviceNodeLegacy.js +146 -0
  27. package/dist/esm/examples/MultiDeviceNodeLegacy.js.map +7 -0
  28. package/dist/esm/examples/SensorDeviceNode.js +167 -0
  29. package/dist/esm/examples/SensorDeviceNode.js.map +7 -0
  30. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +115 -0
  31. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +7 -0
  32. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +115 -0
  33. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +7 -0
  34. package/dist/esm/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.js → DummyWifiNetworkCommissioningServerLegacy.js} +16 -14
  35. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServerLegacy.js.map +7 -0
  36. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +110 -0
  37. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +7 -0
  38. package/dist/esm/tutorial/example01.js +5 -0
  39. package/dist/esm/tutorial/example01.js.map +7 -0
  40. package/dist/esm/tutorial/example02.js +7 -0
  41. package/dist/esm/tutorial/example02.js.map +7 -0
  42. package/dist/esm/tutorial/example03.js +15 -0
  43. package/dist/esm/tutorial/example03.js.map +7 -0
  44. package/dist/esm/tutorial/example04.js +10 -0
  45. package/dist/esm/tutorial/example04.js.map +7 -0
  46. package/dist/esm/tutorial/example05.js +14 -0
  47. package/dist/esm/tutorial/example05.js.map +7 -0
  48. package/package.json +9 -6
  49. package/src/examples/BridgedDeviceNode.ts +260 -0
  50. package/src/examples/{BridgedDevicesNode.ts → BridgedDevicesNodeLegacy.ts} +6 -1
  51. package/src/examples/ComposedDeviceNode.ts +173 -223
  52. package/src/examples/ComposedDeviceNodeLegacy.ts +252 -0
  53. package/src/examples/ControllerNode.ts +28 -22
  54. package/src/examples/ControllerNodeLegacy.ts +354 -0
  55. package/src/examples/DeviceNode.ts +173 -273
  56. package/src/examples/DeviceNodeFull.ts +440 -0
  57. package/src/examples/DeviceNodeFullLegacy.ts +307 -0
  58. package/src/examples/IlluminatedRollerShade.ts +130 -0
  59. package/src/examples/LightDevice.ts +60 -0
  60. package/src/examples/MultiDeviceNode.ts +184 -236
  61. package/src/examples/MultiDeviceNodeLegacy.ts +267 -0
  62. package/src/examples/SensorDeviceNode.ts +236 -0
  63. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +156 -0
  64. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +153 -0
  65. package/src/examples/cluster/{DummyWifiNetworkCommissioningClusterServer.ts → DummyWifiNetworkCommissioningServerLegacy.ts} +16 -13
  66. package/src/examples/cluster/MyFancyOwnFunctionality.ts +185 -0
  67. package/src/tsconfig.json +9 -1
  68. package/src/tutorial/example01.ts +6 -0
  69. package/src/tutorial/example02.ts +9 -0
  70. package/src/tutorial/example03.ts +19 -0
  71. package/src/tutorial/example04.ts +13 -0
  72. package/src/tutorial/example05.ts +19 -0
  73. package/dist/esm/examples/BridgedDevicesNode.js.map +0 -7
  74. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningClusterServer.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/examples/DeviceNode.ts"],
4
- "sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022 The node-matter Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * This example shows how to create a simple on-off Matter device.\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/DummyWifiNetworkCommissioningClusterServer.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(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"isSocket\", isSocket);\n deviceStorage.set(\"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 softAccessPoint: false,\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\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;AAeA,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,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;AAAO,aAAO,SAAS,OAAO;AACzD;AAEA,IAAI,aAAa,KAAK,GAAG;AAErB,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,gBAAgB,YAAY;AAAA,IACvC,CAAC;AAAA,EACT;AACJ;AAEA,MAAM,kBAAkB,aAAa,OAAO,KAAK;AACjD,MAAM,U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D;AASA,WAAO,KAAK,WAAW;AACvB,QAAI,CAAC,oBAAoB,eAAe,GAAG;AACvC,YAAM,cAAc,oBAAoB,eAAe;AAAA,QACnD,KAAK,aAAa,KAAK;AAAA,QACvB,iBAAiB;AAAA,QACjB,aAAa;AAAA,MACjB,CAAC;AAED,YAAM,EAAE,eAAe,kBAAkB,IAAI;AAE7C,cAAQ,IAAI,OAAO,IAAI,aAAa,CAAC;AACrC,aAAO;AAAA,QACH,gFAAgF,aAAa;AAAA,MACjG;AACA,aAAO,KAAK,wBAAwB,iBAAiB,EAAE;AAAA,IAC3D,OAAO;AACH,aAAO,KAAK,wEAAwE;AAAA,IACxF;AAAA,EACJ;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,YACK,MAAM,EACN,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,EAC1B,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AAAA,EACxC,CAAC,EACA,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
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 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 * 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 { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { execSync } from \"child_process\";\n\nrequireMinNodeVersion(16);\n\nasync function main() {\n /** Initialize configuration values */\n const {\n isSocket,\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(isSocket ? OnOffPlugInUnitDevice.deviceType : OnOffLightDevice.deviceType),\n },\n\n // Provide defaults for the BasicInformation cluster on the Root endpoint\n // Optional: If Omitted some development defaults are used\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `matterjs-${uniqueId}`,\n uniqueId,\n },\n });\n\n /**\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 const endpoint = new Endpoint(isSocket ? OnOffPlugInUnitDevice : OnOffLightDevice, { id: \"onoff\" });\n await server.add(endpoint);\n\n /**\n * Register state change handlers of the node for identify and onoff states to react to the commands.\n * If the code in these change handlers fail then the change is also rolled back and not executed and an error is\n * reported back to the controller.\n */\n let isIdentifying = false;\n endpoint.events.identify.identifyTime$Change.on(value => {\n // identifyTime is set when an identify command is called and then decreased every second while indentify logic runs.\n if (value > 0 && !isIdentifying) {\n isIdentifying = true;\n console.log(`Run identify logic, ideally blink a light every 0.5s ...`);\n } else if (value === 0) {\n isIdentifying = false;\n console.log(`Stop identify logic ...`);\n }\n });\n\n endpoint.events.onOff.onOff$Change.on(value => {\n executeCommand(value ? \"on\" : \"off\");\n console.log(`OnOff is now ${value ? \"ON\" : \"OFF\"}`);\n });\n\n /**\n * Log the endpoint structure for debugging reasons and to allow to verify anything is correct\n */\n logEndpoint(EndpointServer.forEndpoint(server));\n\n /**\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. */\nfunction executeCommand(scriptParamName: string) {\n const script = Environment.default.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\nasync function getConfiguration() {\n /**\n * Collect all needed data\n *\n * This block collects all needed data from cli, environment or storage. Replace this with where ever your data come from.\n *\n * Note: This example uses the matter.js process storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own storage contexts\n * (so maybe better not do it ;-)).\n */\n const environment = Environment.default;\n\n const storageService = environment.get(StorageService);\n console.log(`Storage location: ${storageService.location} (Directory)`);\n console.log(\n 'Use the parameter \"--storage-path=NAME-OR-PATH\" to specify a different storage location in this directory, use --storage-clear to start with an empty storage.',\n );\n const deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\n const isSocket = deviceStorage.get(\"isSocket\", environment.vars.get(\"type\") === \"socket\");\n if (deviceStorage.has(\"isSocket\")) {\n console.log(`Device type ${isSocket ? \"socket\" : \"light\"} found in storage. --type parameter is ignored.`);\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 ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = environment.vars.number(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const port = environment.vars.number(\"port\") ?? 5540;\n\n const uniqueId = environment.vars.string(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs().toString());\n\n // Persist basic data to keep them also on restart\n deviceStorage.set(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"isSocket\", isSocket);\n deviceStorage.set(\"uniqueid\", uniqueId);\n\n return {\n isSocket,\n deviceName,\n vendorName,\n passcode,\n discriminator,\n vendorId,\n productName,\n productId,\n port,\n uniqueId,\n };\n}\n"],
5
+ "mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,OAAO;AAEP,SAAS,6BAA6B;AACtC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AACrB,SAAS,gBAAgB;AAEzB,sBAAs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gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,iBAAiB,aAAa;AAChD,gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,aAAa,SAAS;AACxC,gBAAc,IAAI,YAAY,QAAQ;AACtC,gBAAc,IAAI,YAAY,QAAQ;AAEtC,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACJ;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2022-2024 Matter.js Authors
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import "@project-chip/matter-node.js";
7
+ import { BleNode } from "@project-chip/matter-node-ble.js/ble";
8
+ import { createFileLogger } from "@project-chip/matter-node.js/log";
9
+ import { requireMinNodeVersion } from "@project-chip/matter-node.js/util";
10
+ import { NetworkCommissioningServer } from "@project-chip/matter.js/behavior/definitions/network-commissioning";
11
+ import { OnOffServer } from "@project-chip/matter.js/behavior/definitions/on-off";
12
+ import { Ble } from "@project-chip/matter.js/ble";
13
+ import { NetworkCommissioning } from "@project-chip/matter.js/cluster";
14
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
15
+ import { logEndpoint } from "@project-chip/matter.js/device";
16
+ import { OnOffLightDevice } from "@project-chip/matter.js/devices/OnOffLightDevice";
17
+ import { OnOffPlugInUnitDevice } from "@project-chip/matter.js/devices/OnOffPlugInUnitDevice";
18
+ import { Endpoint, EndpointServer } from "@project-chip/matter.js/endpoint";
19
+ import { RootRequirements } from "@project-chip/matter.js/endpoint/definitions";
20
+ import { Environment, StorageService } from "@project-chip/matter.js/environment";
21
+ import { FabricAction } from "@project-chip/matter.js/fabric";
22
+ import { Level, Logger, levelFromString } from "@project-chip/matter.js/log";
23
+ import { ServerNode } from "@project-chip/matter.js/node";
24
+ import { QrCode } from "@project-chip/matter.js/schema";
25
+ import { Time } from "@project-chip/matter.js/time";
26
+ import { ByteArray, singleton } from "@project-chip/matter.js/util";
27
+ import { execSync } from "child_process";
28
+ import { DummyThreadNetworkCommissioningServer } from "./cluster/DummyThreadNetworkCommissioningServer.js";
29
+ import { DummyWifiNetworkCommissioningServer } from "./cluster/DummyWifiNetworkCommissioningServer.js";
30
+ import {
31
+ MyFancyOwnFunctionalityBehavior
32
+ } from "./cluster/MyFancyOwnFunctionality.js";
33
+ requireMinNodeVersion(16);
34
+ const environment = Environment.default;
35
+ if (environment.vars.get("ble.enable")) {
36
+ Ble.get = singleton(
37
+ () => new BleNode({
38
+ hciId: environment.vars.number("ble.hciId")
39
+ })
40
+ );
41
+ }
42
+ function executeCommand(scriptParamName) {
43
+ const script = environment.vars.string(scriptParamName);
44
+ if (script === void 0)
45
+ return void 0;
46
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
47
+ }
48
+ const logFile = environment.vars.string("logfile.filename");
49
+ if (logFile !== void 0) {
50
+ Logger.addLogger("filelogger", await createFileLogger(logFile), {
51
+ defaultLogLevel: levelFromString(environment.vars.string("logfile.loglevel")) ?? Level.DEBUG
52
+ });
53
+ }
54
+ const storageService = environment.get(StorageService);
55
+ console.log(`Storage location: ${storageService.location} (Directory)`);
56
+ console.log(
57
+ '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.'
58
+ );
59
+ const deviceStorage = (await storageService.open("device")).createContext("data");
60
+ if (deviceStorage.has("isSocket")) {
61
+ console.log("Device type found in storage. --type parameter is ignored.");
62
+ }
63
+ const isSocket = deviceStorage.get("isSocket", environment.vars.string("type") === "socket");
64
+ const deviceName = "Matter test device";
65
+ const vendorName = "matter-node.js";
66
+ const passcode = environment.vars.number("passcode") ?? deviceStorage.get("passcode", 20202021);
67
+ const discriminator = environment.vars.number("discriminator") ?? deviceStorage.get("discriminator", 3840);
68
+ const vendorId = environment.vars.number("vendorid") ?? deviceStorage.get("vendorid", 65521);
69
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
70
+ const productId = environment.vars.number("productid") ?? deviceStorage.get("productid", 32768);
71
+ const port = environment.vars.number("port") ?? 5540;
72
+ const uniqueId = environment.vars.string("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs().toString());
73
+ deviceStorage.set("passcode", passcode);
74
+ deviceStorage.set("discriminator", discriminator);
75
+ deviceStorage.set("vendorid", vendorId);
76
+ deviceStorage.set("productid", productId);
77
+ deviceStorage.set("isSocket", isSocket);
78
+ deviceStorage.set("uniqueid", uniqueId);
79
+ class OnOffShellExecServer extends OnOffServer {
80
+ // Intercept the "on" command to the Matter On/Off cluster to print a log message.
81
+ on() {
82
+ executeCommand("on");
83
+ super.on();
84
+ }
85
+ // This is the functional inverse of on() above.
86
+ //
87
+ // For demonstration purposes we update state ourselves rather than deferring to matter.js's default "off" handler
88
+ // via super.off().
89
+ off() {
90
+ executeCommand("off");
91
+ this.state.onOff = false;
92
+ }
93
+ // Use event handlers to log on/off state reactively, after it changes.
94
+ initialize() {
95
+ this.events.onOff$Change.on((value) => {
96
+ console.log(`Light is now ${value ? "ON" : "OFF"}`);
97
+ });
98
+ }
99
+ }
100
+ class TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {
101
+ initialize() {
102
+ this.state.testEventTriggersEnabled = true;
103
+ super.initialize();
104
+ }
105
+ testEventTrigger({ enableKey, eventTrigger }) {
106
+ console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);
107
+ }
108
+ }
109
+ class MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {
110
+ /** We return the incoming value and store the length of the string in our attribute and send it out as event */
111
+ myFancyCommand(request) {
112
+ const { value } = request;
113
+ this.state.myFancyValue = value.length;
114
+ this.events.myFancyEvent.emit({ eventValue: value }, this.context);
115
+ return { response: value };
116
+ }
117
+ initialize() {
118
+ this.state.myFancyValue = -1;
119
+ }
120
+ }
121
+ const OnOffDevice = isSocket ? vendorId === 65524 ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer) : OnOffPlugInUnitDevice.with(OnOffShellExecServer) : vendorId === 65524 ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer) : OnOffLightDevice.with(OnOffShellExecServer);
122
+ let RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);
123
+ let wifiOrThreadAdded = false;
124
+ if (Ble.enabled) {
125
+ if (environment.vars.has("ble.wifi.fake")) {
126
+ RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);
127
+ wifiOrThreadAdded = true;
128
+ } else if (environment.vars.has("ble.thread.fake")) {
129
+ RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);
130
+ wifiOrThreadAdded = true;
131
+ }
132
+ } else {
133
+ RootEndpoint = RootEndpoint.with(
134
+ NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface)
135
+ );
136
+ }
137
+ const networkId = new ByteArray(32);
138
+ const server = await ServerNode.create(RootEndpoint, {
139
+ id: uniqueId,
140
+ network: {
141
+ port,
142
+ discoveryCapabilities: {
143
+ onIpNetwork: !environment.vars.has("ble.enable"),
144
+ ble: environment.vars.has("ble.enable")
145
+ },
146
+ ble: environment.vars.has("ble.enable")
147
+ // TODO remove when state init is fixed
148
+ },
149
+ commissioning: {
150
+ passcode,
151
+ discriminator
152
+ },
153
+ productDescription: {
154
+ name: deviceName,
155
+ deviceType: DeviceTypeId(OnOffDevice.deviceType)
156
+ },
157
+ basicInformation: {
158
+ vendorName,
159
+ vendorId: VendorId(vendorId),
160
+ nodeLabel: productName,
161
+ productName,
162
+ productLabel: productName,
163
+ productId,
164
+ serialNumber: `node-matter-${uniqueId}`,
165
+ uniqueId
166
+ },
167
+ // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally
168
+ networkCommissioning: {
169
+ maxNetworks: 1,
170
+ interfaceEnabled: true,
171
+ lastConnectErrorValue: 0,
172
+ lastNetworkId: wifiOrThreadAdded ? null : networkId,
173
+ lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,
174
+ networks: [{ networkId, connected: !wifiOrThreadAdded }],
175
+ scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : void 0,
176
+ connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : void 0
177
+ },
178
+ myFancyFunctionality: {
179
+ myFancyValue: 0
180
+ }
181
+ });
182
+ const endpoint = new Endpoint(OnOffDevice, { id: "onoff" });
183
+ await server.add(endpoint);
184
+ server.lifecycle.commissioned.on(() => console.log("Server was initially commissioned successfully!"));
185
+ server.lifecycle.decommissioned.on(() => console.log("Server was fully decommissioned successfully!"));
186
+ server.lifecycle.online.on(() => console.log("Server is online"));
187
+ server.lifecycle.offline.on(() => console.log("Server is offline"));
188
+ server.events.commissioning.commissionedFabricsChanged.on((fabricIndex, fabricAction) => {
189
+ let action = "";
190
+ switch (fabricAction) {
191
+ case FabricAction.Added:
192
+ action = "added";
193
+ break;
194
+ case FabricAction.Removed:
195
+ action = "removed";
196
+ break;
197
+ case FabricAction.Updated:
198
+ action = "updated";
199
+ break;
200
+ }
201
+ console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);
202
+ console.log(server.state.operationalCredentials.fabrics);
203
+ });
204
+ server.events.sessions.opened.on((session) => console.log(`Session opened`, session));
205
+ server.events.sessions.closed.on((session) => console.log(`Session closed`, session));
206
+ server.events.sessions.subscriptionsChanged.on((session) => {
207
+ console.log(`Session subscriptions changed`, session);
208
+ console.log(`Status of all sessions`, server.state.sessions.sessions);
209
+ });
210
+ let isIdentifying = false;
211
+ endpoint.events.identify.identifyTime$Change.on((value) => {
212
+ if (value > 0 && !isIdentifying) {
213
+ isIdentifying = true;
214
+ console.log(`Run identify logic, ideally blink a light every 0.5s ...`);
215
+ } else if (value === 0) {
216
+ isIdentifying = false;
217
+ console.log(`Stop identify logic ...`);
218
+ }
219
+ });
220
+ logEndpoint(EndpointServer.forEndpoint(server));
221
+ await server.bringOnline();
222
+ console.log("Initial Fabrics", server.state.operationalCredentials.fabrics);
223
+ if (!server.lifecycle.isCommissioned) {
224
+ const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;
225
+ console.log(QrCode.get(qrPairingCode));
226
+ console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);
227
+ console.log(`Manual pairing code: ${manualPairingCode}`);
228
+ } else {
229
+ console.log("Device is already commissioned. Waiting for controllers to connect ...");
230
+ const onOffValue = endpoint.state.onOff.onOff;
231
+ console.log(`current OnOff attribute: ${onOffValue}`);
232
+ if (vendorId === 65524) {
233
+ await endpoint.set({
234
+ onOff: {
235
+ onOff: !onOffValue
236
+ },
237
+ // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.
238
+ myFancyOwnFunctionality: {
239
+ myFancyValue: 36
240
+ }
241
+ });
242
+ } else {
243
+ await endpoint.set({
244
+ onOff: {
245
+ onOff: !onOffValue
246
+ }
247
+ });
248
+ }
249
+ }
250
+ process.on("SIGINT", () => {
251
+ server.close().then(() => process.exit(0)).catch((err) => console.error(err));
252
+ });
253
+ //# sourceMappingURL=DeviceNodeFull.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/DeviceNodeFull.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 is not optimized for simplicity, but to show all the advanced use cases for matter.js.\n * If you want to see a simple minimalistic and more standard example please look at DeviceNode.ts or the other examples.\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 * Additional to this it shows the following:\n * * How to modify the existing clusters on Root and also Device Endpoints\n * * How to add own Cluster implementations for Standard clusters\n * * How to add a custom Cluster to an Endpoint\n * * Which events are available to get status information from the Node aon commissioning and session/subscription changes\n * * How to get cluster state values\n * * How to set one or multiple state values in a transaction.\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 { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { createFileLogger } from \"@project-chip/matter-node.js/log\";\nimport { requireMinNodeVersion } from \"@project-chip/matter-node.js/util\";\nimport { TestEventTriggerRequest } from \"@project-chip/matter.js/behavior/definitions/general-diagnostics\";\nimport { NetworkCommissioningServer } from \"@project-chip/matter.js/behavior/definitions/network-commissioning\";\nimport { OnOffServer } from \"@project-chip/matter.js/behavior/definitions/on-off\";\nimport { Ble } from \"@project-chip/matter.js/ble\";\nimport { NetworkCommissioning } from \"@project-chip/matter.js/cluster\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport { logEndpoint } from \"@project-chip/matter.js/device\";\nimport { OnOffLightDevice } from \"@project-chip/matter.js/devices/OnOffLightDevice\";\nimport { OnOffPlugInUnitDevice } from \"@project-chip/matter.js/devices/OnOffPlugInUnitDevice\";\nimport { Endpoint, EndpointServer } from \"@project-chip/matter.js/endpoint\";\nimport { RootRequirements } from \"@project-chip/matter.js/endpoint/definitions\";\nimport { Environment, StorageService } from \"@project-chip/matter.js/environment\";\nimport { FabricAction } from \"@project-chip/matter.js/fabric\";\nimport { Level, Logger, levelFromString } from \"@project-chip/matter.js/log\";\nimport { ServerNode } from \"@project-chip/matter.js/node\";\nimport { QrCode } from \"@project-chip/matter.js/schema\";\nimport { Time } from \"@project-chip/matter.js/time\";\nimport { ByteArray, singleton } from \"@project-chip/matter.js/util\";\nimport { execSync } from \"child_process\";\nimport { DummyThreadNetworkCommissioningServer } from \"./cluster/DummyThreadNetworkCommissioningServer.js\";\nimport { DummyWifiNetworkCommissioningServer } from \"./cluster/DummyWifiNetworkCommissioningServer.js\";\nimport {\n MyFancyCommandRequest,\n MyFancyCommandResponse,\n MyFancyOwnFunctionalityBehavior,\n} from \"./cluster/MyFancyOwnFunctionality.js\";\n\n/**\n * The following code brings some convenience to the CLI script. It allows to set the log level and format via\n * command line parameters. It also initializes the BLE stack if the `--ble` parameter is present.\n * Some of these parameters can also be replaced by generically accepted parameters or even environment variables. See the comments in the relevant places for information.\n * When using this code as basis for your own device node implementation, you can remove this part or hard code it.\n */\n\nrequireMinNodeVersion(16);\n\n// To configure Logging use\n// * \"--log-level\" or environment variable \"MATTER_LOG_LEVEL\" or \"environment.vars.set('log.level', Level.DEBUG)\"\n// Allowed values are: Level.FATAL, Level.ERROR, Level.WARN, Level.NOTICE, Level.INFO, Level.DEBUG\n// * \"--log-format\" or environment variable \"MATTER_LOG_FORMAT\" or \"environment.vars.set('log.format', Format.PLAIN)\"\n// Allowed values are: Format.PLAIN, Format.HTML, Format.ANSI,\n\nconst environment = Environment.default;\n\n// Alternatively \"--ble-enable\" or environment variable \"BLE_ENABLED\"\n// Alternatively \"--ble-hciId\" or environment variable \"BLE_HCIID\"\nif (environment.vars.get(\"ble.enable\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: environment.vars.number(\"ble.hciId\"),\n }),\n );\n}\n\nfunction executeCommand(scriptParamName: string) {\n const script = environment.vars.string(scriptParamName);\n if (script === undefined) return undefined;\n console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);\n}\n\n/**\n * Collect all needed data\n *\n * This block collects all needed data from cli 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\nconst logFile = environment.vars.string(\"logfile.filename\");\nif (logFile !== undefined) {\n Logger.addLogger(\"filelogger\", await createFileLogger(logFile), {\n defaultLogLevel: levelFromString(environment.vars.string(\"logfile.loglevel\")) ?? Level.DEBUG,\n });\n}\n\nconst storageService = environment.get(StorageService);\nconsole.log(`Storage location: ${storageService.location} (Directory)`);\nconsole.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\nconst deviceStorage = (await storageService.open(\"device\")).createContext(\"data\");\n\nif (deviceStorage.has(\"isSocket\")) {\n console.log(\"Device type found in storage. --type parameter is ignored.\");\n}\nconst isSocket = deviceStorage.get(\"isSocket\", environment.vars.string(\"type\") === \"socket\");\nconst deviceName = \"Matter test device\";\nconst vendorName = \"matter-node.js\";\nconst passcode = environment.vars.number(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\nconst discriminator = environment.vars.number(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n// product name / id and vendor id should match what is in the device certificate\nconst vendorId = environment.vars.number(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\nconst productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\nconst productId = environment.vars.number(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\nconst port = environment.vars.number(\"port\") ?? 5540;\n\nconst uniqueId = environment.vars.string(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs().toString());\n\ndeviceStorage.set(\"passcode\", passcode);\ndeviceStorage.set(\"discriminator\", discriminator);\ndeviceStorage.set(\"vendorid\", vendorId);\ndeviceStorage.set(\"productid\", productId);\ndeviceStorage.set(\"isSocket\", isSocket);\ndeviceStorage.set(\"uniqueid\", uniqueId);\n\n// Matter exposes functionality in groups called \"clusters\". For this example device we override the matter.js \"On/Off\"\n// cluster implementation to print status to the console.\nclass OnOffShellExecServer extends OnOffServer {\n // Intercept the \"on\" command to the Matter On/Off cluster to print a log message.\n override on() {\n executeCommand(\"on\");\n super.on();\n }\n\n // This is the functional inverse of on() above.\n //\n // For demonstration purposes we update state ourselves rather than deferring to matter.js's default \"off\" handler\n // via super.off().\n override off() {\n executeCommand(\"off\");\n this.state.onOff = false;\n }\n\n // Use event handlers to log on/off state reactively, after it changes.\n override initialize() {\n this.events.onOff$Change.on(value => {\n console.log(`Light is now ${value ? \"ON\" : \"OFF\"}`);\n });\n }\n}\n\nclass TestGeneralDiagnosticsServer extends RootRequirements.GeneralDiagnosticsServer {\n override initialize() {\n this.state.testEventTriggersEnabled = true; // set to true if you support test triggers ...\n super.initialize();\n }\n\n override testEventTrigger({ enableKey, eventTrigger }: TestEventTriggerRequest) {\n console.log(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`);\n }\n}\n\nclass MyFancyOwnFunctionalityServer extends MyFancyOwnFunctionalityBehavior {\n /** We return the incoming value and store the length of the string in our attribute and send it out as event */\n override myFancyCommand(request: MyFancyCommandRequest): MyFancyCommandResponse {\n const { value } = request;\n this.state.myFancyValue = value.length;\n\n this.events.myFancyEvent.emit({ eventValue: value }, this.context);\n\n return { response: value };\n }\n\n override initialize() {\n this.state.myFancyValue = -1; // Always initialize with -1\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// Devices are compositions of behaviors like OnOffServer above. To extend an existing device you use builder methods.\n//\n// In this case we are using with() to install our On/Off cluster behavior.\n// .with(\"LevelControlForLighting\") not needed because we always have it in by default because we have default implementation\nconst OnOffDevice = isSocket\n ? vendorId === 0xfff4\n ? OnOffPlugInUnitDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffPlugInUnitDevice.with(OnOffShellExecServer)\n : vendorId === 0xfff4\n ? OnOffLightDevice.with(OnOffShellExecServer, MyFancyOwnFunctionalityServer)\n : OnOffLightDevice.with(OnOffShellExecServer);\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// We use the Basic Root Endpoint without a NetworkCommissioning cluster\nlet RootEndpoint = ServerNode.RootEndpoint.with(TestGeneralDiagnosticsServer);\n\nlet wifiOrThreadAdded = false;\nif (Ble.enabled) {\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 if (environment.vars.has(\"ble.wifi.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyWifiNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n } else if (environment.vars.has(\"ble.thread.fake\")) {\n RootEndpoint = RootEndpoint.with(DummyThreadNetworkCommissioningServer);\n wifiOrThreadAdded = true;\n }\n} else {\n RootEndpoint = RootEndpoint.with(\n NetworkCommissioningServer.with(NetworkCommissioning.Feature.EthernetNetworkInterface),\n );\n}\n\nconst networkId = new ByteArray(32);\n// Physical devices appear as \"nodes\" on a Matter network. As a device implementer you use a NodeServer to bring a\n// device online.\n//\n// Note there are a large number of options to NodeServer that we are allowing to take default values here. See\n// CompositeWindowCovering.ts for a more detailed example.\nconst server = await ServerNode.create(RootEndpoint, {\n id: uniqueId,\n network: {\n port,\n discoveryCapabilities: {\n onIpNetwork: !environment.vars.has(\"ble.enable\"),\n ble: environment.vars.has(\"ble.enable\"),\n },\n ble: environment.vars.has(\"ble.enable\"), // TODO remove when state init is fixed\n },\n commissioning: {\n passcode,\n discriminator,\n },\n productDescription: {\n name: deviceName,\n deviceType: DeviceTypeId(OnOffDevice.deviceType),\n },\n basicInformation: {\n vendorName,\n vendorId: VendorId(vendorId),\n nodeLabel: productName,\n productName,\n productLabel: productName,\n productId,\n serialNumber: `node-matter-${uniqueId}`,\n uniqueId,\n },\n\n // @ts-expect-error ... TS do not see the types because both next clusters was added conditionally\n networkCommissioning: {\n maxNetworks: 1,\n interfaceEnabled: true,\n lastConnectErrorValue: 0,\n lastNetworkId: wifiOrThreadAdded ? null : networkId,\n lastNetworkingStatus: wifiOrThreadAdded ? null : NetworkCommissioning.NetworkCommissioningStatus.Success,\n networks: [{ networkId: networkId, connected: !wifiOrThreadAdded }],\n scanMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n connectMaxTimeSeconds: wifiOrThreadAdded ? 3 : undefined,\n },\n myFancyFunctionality: {\n myFancyValue: 0,\n },\n});\n\n// Nodes are a composition of endpoints. Add a single endpoint to the node, our example light device.\nconst endpoint = new Endpoint(OnOffDevice, { id: \"onoff\" });\nawait server.add(endpoint);\n\n/**\n * This event is triggered when the device is initially commissioned successfully.\n * This means: It is added to the first fabric.\n */\nserver.lifecycle.commissioned.on(() => console.log(\"Server was initially commissioned successfully!\"));\n\n/** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */\nserver.lifecycle.decommissioned.on(() => console.log(\"Server was fully decommissioned successfully!\"));\n\n/** This event is triggered when the device went online. This means that it is discoverable in the network. */\nserver.lifecycle.online.on(() => console.log(\"Server is online\"));\n\n/** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */\nserver.lifecycle.offline.on(() => console.log(\"Server is offline\"));\n\n/**\n * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular\n * information is needed.\n */\nserver.events.commissioning.commissionedFabricsChanged.on((fabricIndex, fabricAction) => {\n let action = \"\";\n switch (fabricAction) {\n case FabricAction.Added:\n action = \"added\";\n break;\n case FabricAction.Removed:\n action = \"removed\";\n break;\n case FabricAction.Updated:\n action = \"updated\";\n break;\n }\n console.log(`Commissioned Fabrics changed event (${action}) for ${fabricIndex} triggered`);\n console.log(server.state.operationalCredentials.fabrics);\n});\n\n/**\n * This event is triggered when an operative new session was opened by a Controller.\n * It is not triggered for the initial commissioning process, just afterwards for real connections.\n */\nserver.events.sessions.opened.on(session => console.log(`Session opened`, session));\n\n/**\n * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.\n */\nserver.events.sessions.closed.on(session => console.log(`Session closed`, session));\n\n/** This event is triggered when a subscription gets added or removed on an operative session. */\nserver.events.sessions.subscriptionsChanged.on(session => {\n console.log(`Session subscriptions changed`, session);\n console.log(`Status of all sessions`, server.state.sessions.sessions);\n});\n\n// React on a change of identificationTime to do Identify stuff for the own device\nlet isIdentifying = false;\nendpoint.events.identify.identifyTime$Change.on(value => {\n if (value > 0 && !isIdentifying) {\n isIdentifying = true;\n console.log(`Run identify logic, ideally blink a light every 0.5s ...`);\n } else if (value === 0) {\n isIdentifying = false;\n console.log(`Stop identify logic ...`);\n }\n});\n\n// Our device is now built and we can bring the node online.\n//\n// Note that you may serve multiple nodes from a single process. We only have one, however, so we can use the run()\n// method of the node.\n\nlogEndpoint(EndpointServer.forEndpoint(server));\n\n/**\n * In order to start the node and announce it into the network we start the node. This method resolves when the Matter\n * node enters his online state. Alternatively, we could also use `await server.run()` which\n * resolves when the node goes offline again, but we want to execute code afterwards, so we use start() here\n */\nawait server.bringOnline();\n\nconsole.log(\"Initial Fabrics\", server.state.operationalCredentials.fabrics);\n\n/**\n * If the node is not commissioned already we display the QR code on console. The QR code is also logged\n */\nif (!server.lifecycle.isCommissioned) {\n const { qrPairingCode, manualPairingCode } = server.state.commissioning.pairingCodes;\n\n console.log(QrCode.get(qrPairingCode));\n console.log(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);\n console.log(`Manual pairing code: ${manualPairingCode}`);\n} else {\n console.log(\"Device is already commissioned. Waiting for controllers to connect ...\");\n\n /**\n * Sometimes reading or writing attributes is required. The following code shows how this works.\n * For read it is basically `endpoint.state.clustername.attributename`.\n * The set method allows to set one or multiple values via the structure of also clustername.attributename. When multiple values are set they are considered being one transaction which would be rolled back completely if one value fails to be set.\n */\n\n // Read onOff attribute from onOff cluster\n const onOffValue = endpoint.state.onOff.onOff;\n console.log(`current OnOff attribute: ${onOffValue}`);\n\n if (vendorId === 0xfff4) {\n // Set onOff attribute from OnOff cluster AND the myFancyValue of the MyFancyOwnFunctionality cluster together\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n // @ts-expect-error Needed because the Fancy cluster is added conditionally, so TS do not get that it's there.\n myFancyOwnFunctionality: {\n myFancyValue: 36,\n },\n });\n } else {\n // Set onOff attribute from OnOff cluster only\n await endpoint.set({\n onOff: {\n onOff: !onOffValue,\n },\n });\n }\n}\n\n/**\n * To correctly tear down the now we can use server[Symbol.asyncDispose]().\n */\nprocess.on(\"SIGINT\", () => {\n // Clean up on CTRL-C\n server\n .close()\n .then(() => process.exit(0))\n .catch(err => console.error(err));\n});\n"],
5
+ "mappings": "AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,OAAO;AAEP,SAAS,eAAe;AACxB,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AAEtC,SAAS,kCAAkC;AAC3C,SAAS,mBAAmB;AAC5B,SAAS,WAAW;AACpB,SAAS,4BAA4B;AACrC,SAAS,cAAc,gBAAgB;AACvC,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AACtC,SAAS,UAAU,sBAAsB;AACzC,SAAS,wBAAwB;AACjC,SAAS,aAAa,sBAAsB;AAC5C,SAAS,oBAAoB;AAC7B,SAAS,OAAO,QAAQ,uBAAuB;AAC/C,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,WAAW,iBAAiB;AACrC,SAAS,gBAAgB;AACzB,SAAS,6CAA6C;AACtD,SAAS,2CAA2C;AACpD;AAAA,EAGI;AAAA,OACG;AASP,sBA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K,CAAC,CAAC,EAC1B,MAAM,SAAO,QAAQ,MAAM,GAAG,CAAC;AACxC,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @license
4
+ * Copyright 2022-2024 Matter.js Authors
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ import { CommissioningServer, MatterServer } from "@project-chip/matter-node.js";
8
+ import { BleNode } from "@project-chip/matter-node-ble.js/ble";
9
+ import { Ble } from "@project-chip/matter-node.js/ble";
10
+ import { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from "@project-chip/matter-node.js/device";
11
+ import { Format, Level, Logger } from "@project-chip/matter-node.js/log";
12
+ import { QrCode } from "@project-chip/matter-node.js/schema";
13
+ import { StorageBackendDisk, StorageManager } from "@project-chip/matter-node.js/storage";
14
+ import { Time } from "@project-chip/matter-node.js/time";
15
+ import {
16
+ commandExecutor,
17
+ getIntParameter,
18
+ getParameter,
19
+ hasParameter,
20
+ requireMinNodeVersion,
21
+ singleton
22
+ } from "@project-chip/matter-node.js/util";
23
+ import { DeviceTypeId, VendorId } from "@project-chip/matter.js/datatype";
24
+ import DummyWifiNetworkCommissioningClusterServer from "./cluster/DummyWifiNetworkCommissioningServerLegacy.js";
25
+ const logger = Logger.get("Device");
26
+ requireMinNodeVersion(16);
27
+ switch (getParameter("loglevel")) {
28
+ case "fatal":
29
+ Logger.defaultLogLevel = Level.FATAL;
30
+ break;
31
+ case "error":
32
+ Logger.defaultLogLevel = Level.ERROR;
33
+ break;
34
+ case "warn":
35
+ Logger.defaultLogLevel = Level.WARN;
36
+ break;
37
+ case "info":
38
+ Logger.defaultLogLevel = Level.INFO;
39
+ break;
40
+ }
41
+ switch (getParameter("logformat")) {
42
+ case "plain":
43
+ Logger.format = Format.PLAIN;
44
+ break;
45
+ case "html":
46
+ Logger.format = Format.HTML;
47
+ break;
48
+ default:
49
+ if (process.stdin?.isTTY)
50
+ Logger.format = Format.ANSI;
51
+ }
52
+ if (hasParameter("ble")) {
53
+ Ble.get = singleton(
54
+ () => new BleNode({
55
+ hciId: getIntParameter("ble-hci-id")
56
+ })
57
+ );
58
+ }
59
+ const storageLocation = getParameter("store") ?? ".device-node";
60
+ const storage = new StorageBackendDisk(storageLocation, hasParameter("clearstorage"));
61
+ logger.info(`Storage location: ${storageLocation} (Directory)`);
62
+ logger.info(
63
+ 'Use the parameter "-store NAME" to specify a different storage location, use -clearstorage to start with an empty storage.'
64
+ );
65
+ class Device {
66
+ async start() {
67
+ logger.info(`node-matter`);
68
+ const storageManager = new StorageManager(storage);
69
+ await storageManager.initialize();
70
+ const deviceStorage = storageManager.createContext("Device");
71
+ if (deviceStorage.has("isSocket")) {
72
+ logger.info("Device type found in storage. -type parameter is ignored.");
73
+ }
74
+ const isSocket = deviceStorage.get("isSocket", getParameter("type") === "socket");
75
+ const deviceName = "Matter test device";
76
+ const vendorName = "matter-node.js";
77
+ const passcode = getIntParameter("passcode") ?? deviceStorage.get("passcode", 20202021);
78
+ const discriminator = getIntParameter("discriminator") ?? deviceStorage.get("discriminator", 3840);
79
+ const vendorId = getIntParameter("vendorid") ?? deviceStorage.get("vendorid", 65521);
80
+ const productName = `node-matter OnOff ${isSocket ? "Socket" : "Light"}`;
81
+ const productId = getIntParameter("productid") ?? deviceStorage.get("productid", 32768);
82
+ const netInterface = getParameter("netinterface");
83
+ const port = getIntParameter("port") ?? 5540;
84
+ const uniqueId = getIntParameter("uniqueid") ?? deviceStorage.get("uniqueid", Time.nowMs());
85
+ deviceStorage.set("passcode", passcode);
86
+ deviceStorage.set("discriminator", discriminator);
87
+ deviceStorage.set("vendorid", vendorId);
88
+ deviceStorage.set("productid", productId);
89
+ deviceStorage.set("isSocket", isSocket);
90
+ deviceStorage.set("uniqueid", uniqueId);
91
+ const onOffDevice = isSocket ? new OnOffPluginUnitDevice() : new OnOffLightDevice();
92
+ onOffDevice.addOnOffListener((on) => commandExecutor(on ? "on" : "off")?.());
93
+ onOffDevice.addCommandHandler(
94
+ "identify",
95
+ async ({ request: { identifyTime } }) => logger.info(`Identify called for OnOffDevice: ${identifyTime}`)
96
+ );
97
+ this.matterServer = new MatterServer(storageManager, { mdnsInterface: netInterface });
98
+ const commissioningServer = new CommissioningServer({
99
+ port,
100
+ deviceName,
101
+ deviceType: DeviceTypeId(onOffDevice.deviceType),
102
+ passcode,
103
+ discriminator,
104
+ basicInformation: {
105
+ vendorName,
106
+ vendorId: VendorId(vendorId),
107
+ nodeLabel: productName,
108
+ productName,
109
+ productLabel: productName,
110
+ productId,
111
+ serialNumber: `node-matter-${uniqueId}`
112
+ },
113
+ delayedAnnouncement: hasParameter("ble"),
114
+ // Delay announcement when BLE is used to show how limited advertisement works
115
+ activeSessionsChangedCallback: (fabricIndex) => {
116
+ console.log(
117
+ `activeSessionsChangedCallback: Active sessions changed on Fabric ${fabricIndex}`,
118
+ commissioningServer.getActiveSessionInformation(fabricIndex)
119
+ );
120
+ },
121
+ commissioningChangedCallback: (fabricIndex) => {
122
+ console.log(
123
+ `commissioningChangedCallback: Commissioning changed on Fabric ${fabricIndex}`,
124
+ commissioningServer.getCommissionedFabricInformation(fabricIndex)[0]
125
+ );
126
+ }
127
+ });
128
+ commissioningServer.addCommandHandler(
129
+ "testEventTrigger",
130
+ async ({ request: { enableKey, eventTrigger } }) => logger.info(`testEventTrigger called on GeneralDiagnostic cluster: ${enableKey} ${eventTrigger}`)
131
+ );
132
+ if (hasParameter("ble")) {
133
+ commissioningServer.addRootClusterServer(DummyWifiNetworkCommissioningClusterServer);
134
+ }
135
+ commissioningServer.addDevice(onOffDevice);
136
+ await this.matterServer.addCommissioningServer(commissioningServer);
137
+ await this.matterServer.start();
138
+ logEndpoint(commissioningServer.getRootEndpoint());
139
+ if (hasParameter("ble")) {
140
+ await commissioningServer.advertise({ ble: true });
141
+ }
142
+ logger.info("Listening");
143
+ if (!commissioningServer.isCommissioned()) {
144
+ const pairingData = commissioningServer.getPairingCode({
145
+ ble: hasParameter("ble"),
146
+ softAccessPoint: false,
147
+ onIpNetwork: false
148
+ });
149
+ const { qrPairingCode, manualPairingCode } = pairingData;
150
+ console.log(QrCode.get(qrPairingCode));
151
+ logger.info(
152
+ `QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`
153
+ );
154
+ logger.info(`Manual pairing code: ${manualPairingCode}`);
155
+ } else {
156
+ logger.info("Device is already commissioned. Waiting for controllers to connect ...");
157
+ }
158
+ }
159
+ async stop() {
160
+ await this.matterServer?.close();
161
+ }
162
+ }
163
+ const device = new Device();
164
+ device.start().then(() => {
165
+ }).catch((err) => console.error(err));
166
+ process.on("SIGINT", () => {
167
+ device.stop().then(() => {
168
+ storage.close().then(() => process.exit(0)).catch((err) => console.error(err));
169
+ }).catch((err) => console.error(err));
170
+ });
171
+ //# sourceMappingURL=DeviceNodeFullLegacy.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/DeviceNodeFullLegacy.ts"],
4
+ "sourcesContent": ["#!/usr/bin/env node\n/**\n * @license\n * Copyright 2022-2024 Matter.js Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * IMPORTANT: This example uses a Legacy API which will be deprecated in the future.\n * It is just still here to support developers in converting their code to the new API!\n */\n\n/**\n * This example shows how to create a simple on-off Matter device as a light or as a socket.\n * It can be used as CLI script and starting point for your own device node implementation.\n */\n\n/**\n * Import needed modules from @project-chip/matter-node.js\n */\n// Include this first to auto-register Crypto, Network and Time Node.js implementations\nimport { CommissioningServer, MatterServer } from \"@project-chip/matter-node.js\";\n\nimport { BleNode } from \"@project-chip/matter-node-ble.js/ble\";\nimport { Ble } from \"@project-chip/matter-node.js/ble\";\nimport { OnOffLightDevice, OnOffPluginUnitDevice, logEndpoint } from \"@project-chip/matter-node.js/device\";\nimport { Format, Level, Logger } from \"@project-chip/matter-node.js/log\";\nimport { QrCode } from \"@project-chip/matter-node.js/schema\";\nimport { StorageBackendDisk, StorageManager } from \"@project-chip/matter-node.js/storage\";\nimport { Time } from \"@project-chip/matter-node.js/time\";\nimport {\n commandExecutor,\n getIntParameter,\n getParameter,\n hasParameter,\n requireMinNodeVersion,\n singleton,\n} from \"@project-chip/matter-node.js/util\";\nimport { DeviceTypeId, VendorId } from \"@project-chip/matter.js/datatype\";\nimport DummyWifiNetworkCommissioningClusterServer from \"./cluster/DummyWifiNetworkCommissioningServerLegacy.js\";\n\nconst logger = Logger.get(\"Device\");\n\nrequireMinNodeVersion(16);\n\n/** Configure logging */\nswitch (getParameter(\"loglevel\")) {\n case \"fatal\":\n Logger.defaultLogLevel = Level.FATAL;\n break;\n case \"error\":\n Logger.defaultLogLevel = Level.ERROR;\n break;\n case \"warn\":\n Logger.defaultLogLevel = Level.WARN;\n break;\n case \"info\":\n Logger.defaultLogLevel = Level.INFO;\n break;\n}\n\nswitch (getParameter(\"logformat\")) {\n case \"plain\":\n Logger.format = Format.PLAIN;\n break;\n case \"html\":\n Logger.format = Format.HTML;\n break;\n default:\n if (process.stdin?.isTTY) Logger.format = Format.ANSI;\n}\n\nif (hasParameter(\"ble\")) {\n // Initialize Ble\n Ble.get = singleton(\n () =>\n new BleNode({\n hciId: getIntParameter(\"ble-hci-id\"),\n }),\n );\n}\n\nconst storageLocation = getParameter(\"store\") ?? \".device-node\";\nconst storage = new StorageBackendDisk(storageLocation, hasParameter(\"clearstorage\"));\nlogger.info(`Storage location: ${storageLocation} (Directory)`);\nlogger.info(\n 'Use the parameter \"-store NAME\" to specify a different storage location, use -clearstorage to start with an empty storage.',\n);\n\nclass Device {\n private matterServer: MatterServer | undefined;\n\n async start() {\n logger.info(`node-matter`);\n\n /**\n * Initialize the storage system.\n *\n * The storage manager is then also used by the Matter server, so this code block in general is required,\n * but you can choose a different storage backend as long as it implements the required API.\n */\n\n const storageManager = new StorageManager(storage);\n await storageManager.initialize();\n\n /**\n * Collect all needed data\n *\n * This block makes sure to collect all needed data from cli or storage. Replace this with where ever your data\n * come from.\n *\n * Note: This example also uses the initialized storage system to store the device parameter data for convenience\n * and easy reuse. When you also do that be careful to not overlap with Matter-Server own contexts\n * (so maybe better not ;-)).\n */\n\n const deviceStorage = storageManager.createContext(\"Device\");\n\n if (deviceStorage.has(\"isSocket\")) {\n logger.info(\"Device type found in storage. -type parameter is ignored.\");\n }\n const isSocket = deviceStorage.get(\"isSocket\", getParameter(\"type\") === \"socket\");\n const deviceName = \"Matter test device\";\n const vendorName = \"matter-node.js\";\n const passcode = getIntParameter(\"passcode\") ?? deviceStorage.get(\"passcode\", 20202021);\n const discriminator = getIntParameter(\"discriminator\") ?? deviceStorage.get(\"discriminator\", 3840);\n // product name / id and vendor id should match what is in the device certificate\n const vendorId = getIntParameter(\"vendorid\") ?? deviceStorage.get(\"vendorid\", 0xfff1);\n const productName = `node-matter OnOff ${isSocket ? \"Socket\" : \"Light\"}`;\n const productId = getIntParameter(\"productid\") ?? deviceStorage.get(\"productid\", 0x8000);\n\n const netInterface = getParameter(\"netinterface\");\n const port = getIntParameter(\"port\") ?? 5540;\n\n const uniqueId = getIntParameter(\"uniqueid\") ?? deviceStorage.get(\"uniqueid\", Time.nowMs());\n\n deviceStorage.set(\"passcode\", passcode);\n deviceStorage.set(\"discriminator\", discriminator);\n deviceStorage.set(\"vendorid\", vendorId);\n deviceStorage.set(\"productid\", productId);\n deviceStorage.set(\"isSocket\", isSocket);\n deviceStorage.set(\"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 softAccessPoint: false,\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\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;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,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;AAAO,aAAO,SAAS,OAAO;AACzD;AAEA,IAAI,aAAa,KAAK,GAAG;AAErB,MAAI,MAAM;AAAA,IACN,MACI,IAAI,QAAQ;AAAA,MACR,OAAO,gBAAgB,YAAY;AAAA,IACvC,CAAC;AAAA,EACT;AACJ;AAEA,MA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