@matter/examples 0.11.0-alpha.0-20241005-e3e4e4a7a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +274 -0
  3. package/dist/esm/examples/BridgedDevicesNode.js +138 -0
  4. package/dist/esm/examples/BridgedDevicesNode.js.map +6 -0
  5. package/dist/esm/examples/ComposedDeviceNode.js +118 -0
  6. package/dist/esm/examples/ComposedDeviceNode.js.map +6 -0
  7. package/dist/esm/examples/ControllerNode.js +191 -0
  8. package/dist/esm/examples/ControllerNode.js.map +6 -0
  9. package/dist/esm/examples/DeviceNode.js +130 -0
  10. package/dist/esm/examples/DeviceNode.js.map +6 -0
  11. package/dist/esm/examples/DeviceNodeFull.js +259 -0
  12. package/dist/esm/examples/DeviceNodeFull.js.map +6 -0
  13. package/dist/esm/examples/IlluminatedRollerShade.js +56 -0
  14. package/dist/esm/examples/IlluminatedRollerShade.js.map +6 -0
  15. package/dist/esm/examples/LightDevice.js +34 -0
  16. package/dist/esm/examples/LightDevice.js.map +6 -0
  17. package/dist/esm/examples/MultiDeviceNode.js +143 -0
  18. package/dist/esm/examples/MultiDeviceNode.js.map +6 -0
  19. package/dist/esm/examples/SensorDeviceNode.js +170 -0
  20. package/dist/esm/examples/SensorDeviceNode.js.map +6 -0
  21. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js +121 -0
  22. package/dist/esm/examples/cluster/DummyThreadNetworkCommissioningServer.js.map +6 -0
  23. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js +121 -0
  24. package/dist/esm/examples/cluster/DummyWifiNetworkCommissioningServer.js.map +6 -0
  25. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js +113 -0
  26. package/dist/esm/examples/cluster/MyFancyOwnFunctionality.js.map +6 -0
  27. package/dist/esm/package.json +3 -0
  28. package/dist/esm/tutorial/example01.js +4 -0
  29. package/dist/esm/tutorial/example01.js.map +6 -0
  30. package/dist/esm/tutorial/example02.js +6 -0
  31. package/dist/esm/tutorial/example02.js.map +6 -0
  32. package/dist/esm/tutorial/example03.js +14 -0
  33. package/dist/esm/tutorial/example03.js.map +6 -0
  34. package/dist/esm/tutorial/example04.js +9 -0
  35. package/dist/esm/tutorial/example04.js.map +6 -0
  36. package/dist/esm/tutorial/example05.js +13 -0
  37. package/dist/esm/tutorial/example05.js.map +6 -0
  38. package/package.json +70 -0
  39. package/src/examples/BridgedDevicesNode.ts +247 -0
  40. package/src/examples/ComposedDeviceNode.ts +185 -0
  41. package/src/examples/ControllerNode.ts +305 -0
  42. package/src/examples/DeviceNode.ts +198 -0
  43. package/src/examples/DeviceNodeFull.ts +440 -0
  44. package/src/examples/IlluminatedRollerShade.ts +89 -0
  45. package/src/examples/LightDevice.ts +58 -0
  46. package/src/examples/MultiDeviceNode.ts +205 -0
  47. package/src/examples/SensorDeviceNode.ts +236 -0
  48. package/src/examples/cluster/DummyThreadNetworkCommissioningServer.ts +162 -0
  49. package/src/examples/cluster/DummyWifiNetworkCommissioningServer.ts +160 -0
  50. package/src/examples/cluster/MyFancyOwnFunctionality.ts +188 -0
  51. package/src/tsconfig.json +13 -0
  52. package/src/tsconfig.tsbuildinfo +1 -0
  53. package/src/tutorial/example01.ts +5 -0
  54. package/src/tutorial/example02.ts +8 -0
  55. package/src/tutorial/example03.ts +18 -0
  56. package/src/tutorial/example04.ts +12 -0
  57. package/src/tutorial/example05.ts +18 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,274 @@
1
+ # matter-node.js-examples
2
+
3
+ [![license](https://img.shields.io/badge/license-Apache2-green.svg?style=flat)](https://raw.githubusercontent.com/mfucci/node-matter/master/LICENSE)
4
+
5
+ This project provides a set of reference implementations to show several types of Matter device nodes or also a controller implementation.
6
+
7
+ > This package supports all Node.js LTS versions starting with 18.x
8
+
9
+ # matter-node.js Usage examples / Reference implementations
10
+
11
+ To better show how to use the library we provide some reference implementations in the examples directory. They are usable as CLI scripts without changes in the first place but are very simple. They are meant to be used as a starting point for your own implementation, or to experiment with Matter at all in a first place.
12
+
13
+ For BLE usage please also see the [matter-node-ble.js README.md](../matter-node-ble.js/README.md) for prerequisites and limitations!
14
+
15
+ ## Examples Overview
16
+ The examples provided by this repository show different use cases demonstrating how to build different device types and show various ways to implement and interact with the matter.js structures. This section gives an overview regarding what the different examples demonstrate.
17
+
18
+ > [!IMPORTANT]
19
+ > With matter.js 0.8 we introduced a new API that is not compatible with the old API. The new API is more flexible and allows for more complex use cases. The old API is still supported but will be removed in a future release. The examples for the old API are available in the NPM package @project-chip/matter-node.js-examples.
20
+
21
+ ## Device Examples
22
+ Some command line parameters, for example those used to set the level of logging or the MDNS interface are now included in the new environment processing. These can be set by generic command line arguments or by using environment variables. These parameters are processed automatically so are no longer handled by the new example code directly. These are:
23
+
24
+ * `--log-level=...` or environment variable `MATTER_LOG_LEVEL` or in code `environment.vars.set('log.level', Level.DEBUG)`. Allowed values are: Level.FATAL ("fatal"), Level.ERROR ("error"), Level.WARN ("warn"), Level.NOTICE ("notice"), Level.INFO ("info"), Level.DEBUG ("debug")
25
+ * `--log-format=...` or environment variable `MATTER_LOG_FORMAT` or `environment.vars.set('log.format', Format.PLAIN)`. Allowed values are: Format.PLAIN ("plain"), Format.HTML ("html"), Format.ANSI ("ansi")
26
+ * `--storage-path=...` or environment variable `MATTER_STORAGE_PATH` or `environment.vars.set('storage.path', "...")` allows to set the storage location. By default, it will be stored in the users home directory in `.matter/...`. If specified, the given path will be used relative to the current working directory.
27
+ * `--storage-clear` or environment variable `MATTER_STORAGE_CLEAR=1` or `environment.vars.set('storage.clear', true)` allows to define if the storage is reset on startup.
28
+ * `--mdns-networkinterface=...` or environment variable `MATTER_MDNS_NETWORKINTERFACE` or `environment.vars.set('mdns.networkInterface', "...")` allows to limit the DNS announcements and scanning to one network interface. By default, all available interfaces are used.
29
+ Additionally, all command line parameters now require to start with two dashes!
30
+
31
+ * **BridgedDevicesNode**: This example shows how to build a Matter-Bridge that offers multiple OnOff lights and sockets as a bridge. It can be configured via command line and allows for specifications of shell commands to be executed when on and off commands are received at the numbered devices. For more details see below.
32
+ * **ComposedDeviceNode**: This example shows how to build a "simple" composed device where multiple OnOff lights and sockets are combined as a single device. The devices are all added at the root level, so no bridge is used. It can be configured via command line and allows for specifications of shell commands to be executed when on and off commands are received at the numbered devices. For more details see below.
33
+ * **DeviceNode**: This example shows how to build a simple minimalistic DeviceNode with just one socket or light endpoint. The shell commands to be executed by on/off commands can be configured via CLI.
34
+ * **DeviceNodeFull**: This example shows how to build a simple Device node with just one socket or light endpoint. The shell commands to be executed by on/off commands can be configured via CLI. Additionally, this example also shows the following use cases:
35
+ * it shows how to enable BLE for a device node and tweaks the announcement so that BLE is only announced in the beginning.
36
+ * it includes a dummy WifiNetworkCommissioning and a dummy ThreadNetworkCommissioning implementation that simulates Wi-Fi/Thread logic for the commissioner and logs the Wi-Fi/Thread credentials the commissioner sends to the device.
37
+ * it enhances the GeneralDiagnostics and OnOff cluster to implement some commands with its own logic.
38
+ * it defines the ["My Fancy Functionality" custom cluster](./src/examples/cluster/MyFancyOwnFunctionality.ts) and adds this to the OnOff endpoint as additional cluster when the chosen vendorId is set to 0xfff4 (65524)
39
+ * it implements the callbacks where developers can get information on commissioning changes and session/connection changes to better know the status of the node.
40
+ * **MultiDeviceNode**: This example shows how to start multiple Matter nodes on one MatterServer where each node is run on its own Port, but share a single MDNS broadcaster and scanner in order to optimize resources. Each node can be configured via CLI to be an onoff socket or a light. CLI. Options also allow specification of shell commands to be executed for on and off commands.
41
+ * * **SensorDeviceNode**: This example shows how to build a simple Sensor device with a temperature (default) or humidity (`--type humidity`) sensor. The sensor values are updated by default every 60 seconds, or the number of seconds specified via the CLI parameter `--interval`. The value can be defined by the output of a CLI script provided via parameter `--value` or, if no command is specified, are randomly set in the interval -50..+50. To read the Temperature of a Raspberry Pi as example use `--value ="echo \$((\$(</sys/class/thermal/thermal_zone0/temp)/10))"` or to read temperature of your location `--value="curl -s 'wttr.in/?format=%t\&m' | sed 's/°C//'| awk '{print \$1*100}'"` (or use `?format=%h` for humidity).
42
+
43
+ Additionally, these two examples are not directly configurable by CLI and mainly show how to implement different combinations of devices:
44
+ * **IlluminatedRollerShade**: This example implements the Window Covering cluster server logic and also overrides a OnOff cluster server to build a composed devices with a window covering nd a light.
45
+ * **LightDevice**: This example shows how to run a Light device which is not configurable via CLI and only logs changes, so it is the most minimalistic example. It shows how to enhance the OnOff cluster server with own logic.
46
+
47
+ ## Controller example
48
+ * **ControllerNode**: This example shows basically how a controller could be implemented by showing pairing and connections to a paired device. When there is an OnOff Endpoint with ID 1 then this is controlled and toggled.
49
+
50
+ ## Installation
51
+
52
+ ### From NPM
53
+
54
+ ```bash
55
+ npm i -g @matter/examples
56
+ ```
57
+
58
+ ### Use from Cloned Matter.js Repository
59
+
60
+ When you clone the matter.js repository you can also use matter-node.js. To do this you need to execute `npm install` in the matter.js root directory once to install all dependencies and build all packages.
61
+
62
+ Then after `cd packages/examples` you can use `npm run matter-device` to run the matter-node.js server. Please see the next section for more details.
63
+
64
+ ### Bundling
65
+
66
+ For production environments where space and/or CPU is at a premium, you might consider using a bundler to distribute your application. This project includes an example demonstrating how to create such a bundle using [esbuild](https://esbuild.github.io/).
67
+
68
+ To run the example, first install as described in [From NPM](#from-npm) or [Use from Cloned Matter.js Repository](#use-from-cloned-matterjs-repository).
69
+
70
+ Then in the `matter-node.js-examples` installation directory, run:
71
+
72
+ ```bash
73
+ npm run bundle-device
74
+ ```
75
+
76
+ This creates a single JavaScript file containing the application and dependencies.
77
+
78
+ To view the example commands for bundling and running, see scripts `bundle-device` and `matter-device-bundled` in [package.json](package.json).
79
+
80
+ Note that you cannot include native dependencies in this way so those will still need to be installed locally using NPM. In this example, those are the dependencies flagged as `--external` in the `esbuild` command line.
81
+
82
+ ## CLI usage
83
+
84
+ ### Common CLI parameter for all examples
85
+ The following CLI parameters are the same for all examples:
86
+
87
+ * -clearstorage: the storage location will be reset on start of the process. The sorage location is set via parameter "-store" (see concrete examples below)
88
+ * -loglevel: the log level to use (default: debug, possible values: fatal, error, warn, info, debug)
89
+ * -logformat: the log format to use (default: ansi (if executed in a shell/tty), else plain, possible values: ansi, plain, html)
90
+
91
+ ### Start a simple Matter Device Node
92
+
93
+ > The code for this example is in [src/examples/DeviceNode.ts](./src/examples/DeviceNode.ts).
94
+
95
+ To run from the build files:
96
+
97
+ ```bash
98
+ matter-device
99
+ ```
100
+
101
+ To run directly from Typescript files with on the fly compilation:
102
+
103
+ ```bash
104
+ npm run matter-device
105
+ ```
106
+
107
+ This starts a MatterServer (DeviceNode) server listening on port 5540 and announce it as socket device.
108
+
109
+ This first version only includes the OnOff cluster (on/off smart thing, like a plug or a bulb).
110
+ You can use -on and -off parameter to run a script to control something.
111
+ For instance, on a Raspberry Pi, this will turn on / off the red LED:
112
+
113
+ ```bash
114
+ matter-device --type socket --on="echo 255 > /sys/class/leds/led1/brightness" --off="echo 0 > /sys/class/leds/led1/brightness"
115
+ ```
116
+
117
+ or when starting from TS files:
118
+
119
+ ```bash
120
+ npm run matter-device -- --type socket --on="echo 255 > /sys/class/leds/led1/brightness" --off="echo 0 > /sys/class/leds/led1/brightness"
121
+ ```
122
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
123
+
124
+ **If you want to start multiple parallel processes please make sure to use different storage locations, different network port and ideally also different passcodes for each process!**
125
+
126
+ The following parameters are available:
127
+ * --passcode: the passcode to use for pairing (default: 20202021)
128
+ * --discriminator: the discriminator to use for pairing (default: 3840, value between 0 and 4095)
129
+ * --vendorid: the vendor ID as number to use for pairing (default: 65521 (0xFFF1))
130
+ * --productid: the product ID as number to use for pairing (default: 32768 (0x8000))
131
+ * --uniqueid: a unique ID for this device to be used in naming and to store structure information (default: ms time now)
132
+ * --type: the device type to use for pairing (default: light, alternative value is "socket")
133
+ * --netinterface: limit mdns announcements and scanning to the provided network interface, e.g. "en0" (default: all interfaces available)
134
+ * --ble: enable BLE support (default: false) If this is enabled the device will announce itself _only_ via BLE if not commissioned and also presents a "Wifi only" device for commissioning to show this feature!
135
+ * --ble-hci-id: Optionally, HCI ID to use (Linux only, default 0)
136
+ * --port: the port to listen on for the device (default: 5540)
137
+ * --store: the storage location (directory) to use for storing the pairing information (default: .device-node). Ideally use names starting with a ".". Delete the directory or provide an alternative name to reset the device
138
+ * --on: the command to run when the device is turned on (see example above)
139
+ * --off: the command to run when the device is turned off (see example above)
140
+
141
+ Additionally, there are some Testing parameters:
142
+ * --ble-wifi-scan-ssid: The Wi-Fi SSID returned by the "ScanNetworks" call of the Wifi Network commissioning cluster used when using BLE commissioning (default: "TestSSID"). Ideally use a really existing SSID that also the commissioner (Apple, Alexa, ...) knows to make it easier to commission. Else you could get errors while commissioning.
143
+ * --ble-wifi-scan-bssid: The Wi-Fi BSSID returned by the "ScanNetworks" call of the Wifi Network commissioning cluster used when using BLE commissioning (default: "00:00:00:00:00:00").
144
+
145
+ ### Start a Matter Bridge
146
+
147
+ > The code for this example is in [src/examples/BridgedDevicesNode.ts](./src/examples/BridgedDevicesNode.ts).
148
+
149
+ A Bridge is used to expose multiple devices at once.
150
+
151
+ The usage and parameter are comparable to above, but the bridge adds support for multiple types and on/off commands:
152
+
153
+ **If you want to start multiple parallel processes please make sure to use different storage locations, different network port and ideally also different passcodes for each process!**
154
+
155
+ The usage is as above but with modified parameters:
156
+ * --num=X: number of devices to expose (default 2)
157
+ * --typeX=socket: type of the devices to expose as device number X (default Light bulb)
158
+ * --onX "script": script to run when the device number X is turned on
159
+ * --offX "script": script to run when the device number X is turned off
160
+
161
+ **Please especially use the --uniqueidX parameters to assign unique own IDs to the single deices in order to remember their structure in the bridge. Such an ID should never be reused if you ever remove or add new devices! If you do not use --uniqueidX then the order you added them here is not allowed to ever change.**
162
+
163
+ ```bash
164
+ matter-bridge --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
165
+ ```
166
+
167
+ or when starting from TS files:
168
+
169
+ ```bash
170
+ npm run matter-bridge -- --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
171
+ ```
172
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
173
+
174
+ The above command exposes two devices under the bridge, one as light, one as socket and executes the respective commands when the devices are turned on or off.
175
+
176
+ ### Start a Matter Composed Device
177
+
178
+ > The code for this example is in [src/examples/ComposedDeviceNode.ts](./src/examples/ComposedDeviceNode.ts).
179
+
180
+ A composed device is one device with multiple different device types combined. This is useful for devices that have multiple functions, e.g. a light bulb with a temperature sensor.
181
+
182
+ The parameters are like with the bridge but with an added "-type light/socket" parameter to define the type of the composed device itself.
183
+
184
+ ```bash
185
+ matter-composeddevice --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
186
+ ```
187
+
188
+ or when starting from TS files:
189
+
190
+ ```bash
191
+ npm run matter-composeddevice -- --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
192
+ ```
193
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
194
+
195
+ The above command exposes a composed device with a socket and a light device and executes the respective commands when the devices are turned on or off.
196
+
197
+ ### Start multiple Matter Devices in one process
198
+
199
+ > The code for this example is in [src/examples/MultiDeviceNode.ts](./src/examples/MultiDeviceNode.ts).
200
+
201
+ matter.js also allows it to start multiple devices in one process. With this especially the MDNS functionalities are shared between these processes and it should use less resources. How many devices you acn add in one process depends on the load they produce and how many devices run in the single Node.js thread.
202
+
203
+ The parameters are like with the composed device or bridge.
204
+
205
+ ```bash
206
+ matter-multidevice --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
207
+ ```
208
+
209
+ or when starting from TS files:
210
+
211
+ ```bash
212
+ npm run matter-multidevice -- --type=socket --num=2 --on1="echo 255 > /sys/class/leds/led1/brightness" --off1="echo 0 > /sys/class/leds/led1/brightness" --type2=socket --on2="echo 255 > /sys/class/leds/led2/brightness" --off2="echo 0 > /sys/class/leds/led2/brightness"
213
+ ```
214
+ (Please note the "--" to separate commandline parameters between the npm run and the executed script.
215
+
216
+ The above command exposes two single light devices (one socket and on light) and executes the respective commands when the devices are turned on or off.
217
+
218
+ **If you want to start multiple parallel processes please make sure to use different storage locations, different network port and ideally also different passcodes for each process!**
219
+
220
+ ### Start a Matter Controller
221
+
222
+ > The code for this example is in [src/examples/ControllerNode.ts](./src/examples/ControllerNode.ts).
223
+
224
+ **Experimental**
225
+ The current controller implementation is no CLI tool, but shows the pairing of devices and resuming the connection and also showcase the existing low-level controller API. It is just intended to be used for debugging, during development! The code contains some commented-out examples of how to use the low level controller API.
226
+ Please **do not** use this for production, we will replace the API soon!
227
+
228
+ The controller currently is not discovering the device to pair, but directly connects to the IP/port defined bin the command line parameters.
229
+
230
+ To run from the build files:
231
+
232
+ ```bash
233
+ matter-controller -pairingcode 12345678901
234
+ ```
235
+
236
+ To run directly from Typescript files with on the fly compilation:
237
+
238
+ ```bash
239
+ npm run matter-controller -- -pairingcode 12345678901
240
+ ```
241
+
242
+ This will commission a MatterServer device (for debugging/capability showing purpose only for now).
243
+
244
+ The following parameters are available and used to initially commission a device (they can be omitted after this):
245
+ * If the IP and Port of the device is known (should be only the case in testing cases) you can use the following parameters:
246
+ * -ip: the IP address of the device to commission (can be used but discovery via pairingcode or discriminator or also just pin (passode) is most likely better)
247
+ * -port the port of the device to commission (default: 5540)
248
+ * Device identification options:
249
+ * -pairingcode: code to use for pairing (-longDiscriminator and -pin will be ignored) - usually the code below the QR Code on the device or displayed in the app!
250
+ * -longDiscriminator: the discriminator to use for pairing (default: 3840, value between 0 and 4095)
251
+ * -pin: the pin to use for pairing (default: 20202021)
252
+ * When the device to commission is not already in the IP network and also not an Ethernet device commission can be done via ble. In this case the following parameters are used:
253
+ * -ble: enable BLE support (default: false) If this is enabled the controller will try to connect via BLE first (15s timeout) and then via IP if not commissioned yet!
254
+ * -ble-hci-id: Optionally, HCI ID to use (Linux only, default 0)
255
+ * -ble-wifi-ssid: SSID/Name of the Wifi network to connect to - The device will scan especially for this network and commissioning will fail if not found
256
+ * -ble-wifi-credentials: Credentials for the Wifi network to connect to
257
+ * -ble-thread-networkname: Name of the Thread network to connect to - The device will verify that a thread network with this name is reachable by the device and commissioning will fail if not found
258
+ * -ble-thread-operationaldataset: Operational dataset as hex string to use for commissioning (of using OTBR use `ot-ctl dataset active -x` to get the value)
259
+ * Storage configuration parameter
260
+ * -store: the storage location (directory) to use for storing the pairing information (default: .controller-node). Ideally use names with "." at the beginning. Delete the directory or provide an alternative name to reset the controller
261
+ * -clearstorage: the storage location will be reset on start of the process
262
+
263
+ ## Development on basis of the examples
264
+
265
+ The code of the examples is written so that you can use them as basis for your own scripts also outside of this library in your own package. If you import from `@matter/main` then matter.js loads platform extensions such as those for node.js automatically. If you import directly from our other packages then you should add a dependency on `@matter/nodejs`. The examples use `@matter/main` imports to ease adoption.
266
+
267
+ ### Development Device/Composed-device/Bridge
268
+
269
+ The code is structured by comment blocks to better see what belongs to what. It always has code which is just collecting relevant information and data, then the code which is setting up the device and then the code which is starting the device.
270
+
271
+ ## Building
272
+
273
+ * `npm run build`: Build all code and create CommonJS and ES6 variants in dist directory. This will built incrementally and only build the changed files.
274
+ * `npm run build-clean`: Clean the dist directory and build all code from scratch
@@ -0,0 +1,138 @@
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 { Endpoint, EndpointServer, Environment, ServerNode, StorageService, Time, VendorId } from "@matter/main";
8
+ import { BridgedDeviceBasicInformationServer } from "@matter/main/behaviors/bridged-device-basic-information";
9
+ import { OnOffLightDevice } from "@matter/main/devices/on-off-light";
10
+ import { OnOffPlugInUnitDevice } from "@matter/main/devices/on-off-plug-in-unit";
11
+ import { AggregatorEndpoint } from "@matter/main/endpoints/aggregator";
12
+ import { logEndpoint } from "@matter/protocol";
13
+ import { execSync } from "child_process";
14
+ const { isSocket, deviceName, vendorName, passcode, discriminator, vendorId, productName, productId, port, uniqueId } = await getConfiguration();
15
+ const server = await ServerNode.create({
16
+ // Required: Give the Node a unique ID which is used to store the state of this node
17
+ id: uniqueId,
18
+ // Provide Network relevant configuration like the port
19
+ // Optional when operating only one device on a host, Default port is 5540
20
+ network: {
21
+ port
22
+ },
23
+ // Provide Commissioning relevant settings
24
+ // Optional for development/testing purposes
25
+ commissioning: {
26
+ passcode,
27
+ discriminator
28
+ },
29
+ // Provide Node announcement settings
30
+ // Optional: If Ommitted some development defaults are used
31
+ productDescription: {
32
+ name: deviceName,
33
+ deviceType: AggregatorEndpoint.deviceType
34
+ },
35
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
36
+ // Optional: If Omitted some development defaults are used
37
+ basicInformation: {
38
+ vendorName,
39
+ vendorId: VendorId(vendorId),
40
+ nodeLabel: productName,
41
+ productName,
42
+ productLabel: productName,
43
+ productId,
44
+ serialNumber: `matterjs-${uniqueId}`,
45
+ uniqueId
46
+ }
47
+ });
48
+ const aggregator = new Endpoint(AggregatorEndpoint, { id: "aggregator" });
49
+ await server.add(aggregator);
50
+ for (let idx = 0; idx < isSocket.length; idx++) {
51
+ const i = idx + 1;
52
+ const isASocket = isSocket[idx];
53
+ const name = `OnOff ${isASocket ? "Socket" : "Light"} ${i}`;
54
+ const endpoint = new Endpoint(
55
+ isASocket ? (
56
+ // For a Bridged Device we need to add a BridgedDeviceBasicInformation cluster as server
57
+ OnOffPlugInUnitDevice.with(BridgedDeviceBasicInformationServer)
58
+ ) : OnOffLightDevice.with(BridgedDeviceBasicInformationServer),
59
+ {
60
+ id: `onoff-${i}`,
61
+ bridgedDeviceBasicInformation: {
62
+ nodeLabel: name,
63
+ // Main end user name for the device
64
+ productName: name,
65
+ productLabel: name,
66
+ serialNumber: `node-matter-${uniqueId}-${i}`,
67
+ reachable: true
68
+ }
69
+ }
70
+ );
71
+ await aggregator.add(endpoint);
72
+ endpoint.events.identify.startIdentifying.on(() => {
73
+ console.log(`Run identify logic for ${name}, ideally blink a light every 0.5s ...`);
74
+ });
75
+ endpoint.events.identify.stopIdentifying.on(() => {
76
+ console.log(`Stop identify logic for ${name} ...`);
77
+ });
78
+ endpoint.events.onOff.onOff$Changed.on((value) => {
79
+ executeCommand(value ? `on${i}` : `off${i}`);
80
+ console.log(`${name} is now ${value ? "ON" : "OFF"}`);
81
+ });
82
+ }
83
+ await server.start();
84
+ logEndpoint(EndpointServer.forEndpoint(server));
85
+ function executeCommand(scriptParamName) {
86
+ const script = Environment.default.vars.string(scriptParamName);
87
+ if (script === void 0) return void 0;
88
+ console.log(`${scriptParamName}: ${execSync(script).toString().slice(0, -1)}`);
89
+ }
90
+ async function getConfiguration() {
91
+ const environment = Environment.default;
92
+ const storageService = environment.get(StorageService);
93
+ console.log(`Storage location: ${storageService.location} (Directory)`);
94
+ console.log(
95
+ '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.'
96
+ );
97
+ const deviceStorage = (await storageService.open("device")).createContext("data");
98
+ const isSocket2 = Array();
99
+ const numDevices = environment.vars.number("num") || 2;
100
+ if (await deviceStorage.has("isSocket")) {
101
+ console.log(`Device types found in storage. --type parameter is ignored.`);
102
+ (await deviceStorage.get("isSocket")).forEach((type) => isSocket2.push(type));
103
+ }
104
+ for (let i = 1; i <= numDevices; i++) {
105
+ if (isSocket2[i - 1] !== void 0) continue;
106
+ isSocket2.push(environment.vars.string(`type${i}`) === "socket");
107
+ }
108
+ const deviceName2 = "Matter test device";
109
+ const vendorName2 = "matter-node.js";
110
+ const passcode2 = environment.vars.number("passcode") ?? await deviceStorage.get("passcode", 20202021);
111
+ const discriminator2 = environment.vars.number("discriminator") ?? await deviceStorage.get("discriminator", 3840);
112
+ const vendorId2 = environment.vars.number("vendorid") ?? await deviceStorage.get("vendorid", 65521);
113
+ const productName2 = `node-matter OnOff ${isSocket2 ? "Socket" : "Light"}`;
114
+ const productId2 = environment.vars.number("productid") ?? await deviceStorage.get("productid", 32768);
115
+ const port2 = environment.vars.number("port") ?? 5540;
116
+ const uniqueId2 = environment.vars.string("uniqueid") ?? await deviceStorage.get("uniqueid", Time.nowMs().toString());
117
+ await deviceStorage.set({
118
+ passcode: passcode2,
119
+ discriminator: discriminator2,
120
+ vendorid: vendorId2,
121
+ productid: productId2,
122
+ isSocket: isSocket2,
123
+ uniqueid: uniqueId2
124
+ });
125
+ return {
126
+ isSocket: isSocket2,
127
+ deviceName: deviceName2,
128
+ vendorName: vendorName2,
129
+ passcode: passcode2,
130
+ discriminator: discriminator2,
131
+ vendorId: vendorId2,
132
+ productName: productName2,
133
+ productId: productId2,
134
+ port: port2,
135
+ uniqueId: uniqueId2
136
+ };
137
+ }
138
+ //# sourceMappingURL=BridgedDevicesNode.js.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/examples/BridgedDevicesNode.ts"],
4
+ "mappings": ";AACA;AAAA;AAAA;AAAA;AAAA;AAaA,SAAS,UAAU,gBAAgB,aAAa,YAAY,gBAAgB,MAAM,gBAAgB;AAClG,SAAS,2CAA2C;AACpD,SAAS,wBAAwB;A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,IAAI,CAAC,MAAM,OAAW;AACnC,IAAAA,UAAS,KAAK,YAAY,KAAK,OAAO,OAAO,CAAC,EAAE,MAAM,QAAQ;AAAA,EAClE;AAEA,QAAMC,cAAa;AACnB,QAAMC,cAAa;AACnB,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,QAAQ;AACrG,QAAMC,iBAAgB,YAAY,KAAK,OAAO,eAAe,KAAM,MAAM,cAAc,IAAI,iBAAiB,IAAI;AAEhH,QAAMC,YAAW,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAM;AACnG,QAAMC,eAAc,qBAAqBN,YAAW,WAAW,OAAO;AACtE,QAAMO,aAAY,YAAY,KAAK,OAAO,WAAW,KAAM,MAAM,cAAc,IAAI,aAAa,KAAM;AAEtG,QAAMC,QAAO,YAAY,KAAK,OAAO,MAAM,KAAK;AAEhD,QAAMC,YACF,YAAY,KAAK,OAAO,UAAU,KAAM,MAAM,cAAc,IAAI,YAAY,KAAK,MAAM,EAAE,SAAS,CAAC;AAGvG,QAAM,cAAc,IAAI;AAAA,IACpB,UAAAN;AAAA,IACA,eAAAC;AAAA,IACA,UAAUC;AAAA,IACV,WAAWE;AAAA,IACX,UAAAP;AAAA,IACA,UAAUS;AAAA,EACd,CAAC;AAED,SAAO;AAAA,IACH,UAAAT;AAAA,IACA,YAAAC;AAAA,IACA,YAAAC;AAAA,IACA,UAAAC;AAAA,IACA,eAAAC;AAAA,IACA,UAAAC;AAAA,IACA,aAAAC;AAAA,IACA,WAAAC;AAAA,IACA,MAAAC;AAAA,IACA,UAAAC;AAAA,EACJ;AACJ;",
5
+ "names": ["isSocket", "deviceName", "vendorName", "passcode", "discriminator", "vendorId", "productName", "productId", "port", "uniqueId"]
6
+ }