├── .eslintrc.json
├── .github
└── FUNDING.yml
├── .gitignore
├── LICENSE
├── README.md
├── config.schema.json
├── homebridge-shelly-ng.png
├── jest.config.js
├── package-lock.json
├── package.json
├── src
├── abilities
│ ├── accessory-information.ts
│ ├── base.ts
│ ├── cover.ts
│ ├── index.ts
│ ├── outlet.ts
│ ├── power-meter.ts
│ ├── readonly-switch.ts
│ ├── service-label.ts
│ ├── stateless-programmable-switch.ts
│ └── switch.ts
├── accessory.ts
├── config.ts
├── device-delegates
│ ├── base.ts
│ ├── index.ts
│ ├── shelly-plus-1-pm.ts
│ ├── shelly-plus-1.ts
│ ├── shelly-plus-2-pm.ts
│ ├── shelly-plus-i4.ts
│ ├── shelly-plus-plug-us.ts
│ ├── shelly-pro-1-pm.ts
│ ├── shelly-pro-1.ts
│ ├── shelly-pro-2-pm.ts
│ ├── shelly-pro-2.ts
│ ├── shelly-pro-3.ts
│ └── shelly-pro-4-pm.ts
├── index.ts
├── platform.ts
└── utils
│ ├── characteristics.ts
│ ├── device-cache.ts
│ ├── device-logger.ts
│ └── services.ts
└── tsconfig.json
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": [
3 | "eslint:recommended",
4 | "plugin:@typescript-eslint/eslint-recommended",
5 | "plugin:@typescript-eslint/recommended"
6 | ],
7 | "ignorePatterns": [
8 | "dist"
9 | ],
10 | "parser": "@typescript-eslint/parser",
11 | "parserOptions": {
12 | "ecmaVersion": 2018,
13 | "sourceType": "module"
14 | },
15 | "plugins": [
16 | "@typescript-eslint"
17 | ],
18 | "rules": {
19 | "quotes": ["warn", "single"],
20 | "indent": ["warn", 2, { "SwitchCase": 1 }],
21 | "semi": ["off"],
22 | "comma-dangle": ["warn", "always-multiline"],
23 | "dot-notation": "off",
24 | "eqeqeq": "warn",
25 | "curly": ["warn", "all"],
26 | "brace-style": ["warn"],
27 | "prefer-arrow-callback": ["warn"],
28 | "max-len": ["warn", 140],
29 | "no-console": ["warn"],
30 | "no-non-null-assertion": ["off"],
31 | "comma-spacing": ["error"],
32 | "no-multi-spaces": ["warn", { "ignoreEOLComments": true }],
33 | "no-trailing-spaces": ["error"],
34 | "lines-between-class-members": ["warn", "always", {"exceptAfterSingleLine": true}],
35 | "@typescript-eslint/explicit-function-return-type": "off",
36 | "@typescript-eslint/no-non-null-assertion": "off",
37 | "@typescript-eslint/explicit-module-boundary-types": "off",
38 | "@typescript-eslint/semi": ["warn"],
39 | "@typescript-eslint/member-delimiter-style": ["warn"]
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | ko_fi: alexryd
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | dist
2 | node_modules
3 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # homebridge-shelly-ng
4 | [](https://www.npmjs.com/package/homebridge-shelly-ng)
5 | [](https://github.com/homebridge/homebridge/wiki/Verified-Plugins)
6 |
7 | [Homebridge](https://homebridge.io) plugin for [Shelly](https://shelly.cloud),
8 | enabling HomeKit support for the next generation of Shelly devices.
9 |
10 | For the first generation, see [homebridge-shelly](https://github.com/alexryd/homebridge-shelly).
11 |
12 | ## Supported devices
13 |
14 | * [Shelly Plus 1](https://shelly.cloud/shelly-plus-1/)
15 | * [Shelly Plus 1 PM](https://shelly.cloud/shelly-plus-1pm/)
16 | * [Shelly Plus 2 PM](https://shelly.cloud/shelly-plus-2pm/)
17 | * [Shelly Plus I4](https://shelly.cloud/shelly-plus-i4/)
18 | * [Shelly Plus Plug US](https://shelly.cloud/shelly-plus-plug-us/)
19 | * [Shelly Pro 1](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
20 | * [Shelly Pro 1 PM](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
21 | * [Shelly Pro 2](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
22 | * [Shelly Pro 2 PM](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
23 | * [Shelly Pro 3](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
24 | * [Shelly Pro 4 PM](https://shelly.cloud/shelly-pro-smart-home-automation-solution/)
25 |
26 | ## Installation
27 |
28 | Either install this plugin through [Homebridge Config UI X](https://github.com/oznu/homebridge-config-ui-x)
29 | or manually by following these instructions:
30 |
31 | 1. Install Homebridge by [following the instructions](https://github.com/homebridge/homebridge/wiki).
32 | 2. Install this plugin by running `npm install -g homebridge-shelly-ng`.
33 | 3. Add this plugin to the Homebridge config.json:
34 | ```
35 | "platforms": [
36 | {
37 | "platform": "ShellyNG",
38 | "name": "Shelly NG"
39 | }
40 | ]
41 | ```
42 |
43 | By default, devices will be discovered on your local network using mDNS and
44 | WebSockets will then be used to communicate with them.
45 |
46 | ## Configuration
47 |
48 | The following configuration options are available. Note that they are all optional.
49 |
50 | ```
51 | {
52 | "devices": [
53 | {
54 | "id": "e.g. shellyplus1-abcdef123456",
55 | "name": "My Device",
56 | "exclude": false,
57 | "hostname": "e.g. 192.168.1.200",
58 | "password": "pa$$word",
59 | "switch:0": {
60 | "exclude": false,
61 | "type": "switch"
62 | },
63 | "switch:1": {
64 | "exclude": false,
65 | "type": "outlet"
66 | },
67 | "switch:2": {
68 | "exclude": false,
69 | "type": "switch"
70 | },
71 | "switch:3": {
72 | "exclude": false,
73 | "type": "switch"
74 | },
75 | "cover:0": {
76 | "exclude": false,
77 | "type": "windowCovering"
78 | }
79 | }
80 | ],
81 | "mdns": {
82 | "enable": true,
83 | "interface": "e.g. eth0 or 192.168.1.100"
84 | },
85 | "websocket": {
86 | "requestTimeout": 10,
87 | "pingInterval": 60,
88 | "reconnectInterval": [ 5, 10, 30, 60, 300, 600 ]
89 | }
90 | }
91 | ```
92 |
93 | See below for descriptions of each configuration option.
94 |
95 | | Option | Description |
96 | | --- | --- |
97 | | `devices` | An array of one or more objects with options for specific devices. |
98 | | `devices. id` | The device ID. [Here's how to find it](https://github.com/alexryd/homebridge-shelly-ng/wiki/Finding-a-device-ID). |
99 | | `devices. name` | The name of the device. This will be shown in the homebridge log and will be used as the default name when the device is added to HomeKit. Note though that setting this value after the device has been added will not change the name in HomeKit. If no name is specified, this plugin will use the device name set in the Shelly app, or the name of the device model. |
100 | | `devices. exclude` | Set this option to `true` to make this plugin ignore this device. |
101 | | `devices. hostname` | The IP address or hostname of the device. Set this value if your device can't be discovered automatically. |
102 | | `devices. password` | The password to use if authentication has been enabled for the device. |
103 | | `devices. switch:0-3.exclude` | Set this option to `true` to prevent the switch with the specified index number from being added to HomeKit. |
104 | | `devices. switch:0-3.type` | The type of accessory used to represent the switch with the specified index number. Available options are `"outlet"` and `"switch"` (default).
105 | | `devices. cover:0.exclude` | Set this option to `true` to prevent this cover from being added to HomeKit. |
106 | | `devices. cover:0.type` | Only available for devices in cover mode. The type of accessory used to represent the cover. Available options are `"door"`, `"window"` (default) and `"windowCovering"`.
107 | | `mdns` | Settings for the mDNS device discovery service. |
108 | | `mdns. enable` | Set this option to `false` to disable automatic device discovery using mDNS. |
109 | | `mdns. interface` | The network interface to use when sending and receiving mDNS packets. You probably don't need to use this setting unless you know what you're doing. If not specified, all available network interfaces will be used. |
110 | | `websocket. requestTimeout` | The time, in seconds, to wait for a response before a request is aborted. |
111 | | `websocket. pingInterval` | The interval, in seconds, at which ping requests should be made to verify that the connection is open. Set to `0` to disable. |
112 | | `websocket. reconnectInterval` | The interval, in seconds, at which a connection attempt should be made after a socket has been closed. If an array or a comma-separated list of numbers is specified, the first value will be used for the first connection attempt, the second value for the second attempt and so on. When the last value has been reached, it will be used for all subsequent connection attempts; unless the value is `0`, in which case no more attempts will be made. Set to `0` to disable. |
113 |
--------------------------------------------------------------------------------
/config.schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "pluginAlias": "ShellyNG",
3 | "pluginType": "platform",
4 | "singular": true,
5 | "schema": {
6 | "type": "object",
7 | "properties": {
8 | "name": {
9 | "title": "Name",
10 | "type": "string",
11 | "required": true,
12 | "default": "Shelly NG"
13 | },
14 | "mdns": {
15 | "type": "object",
16 | "properties": {
17 | "enable": {
18 | "title": "Enable",
19 | "description": "Whether devices should be automatically discovered using mDNS.",
20 | "type": "boolean",
21 | "default": true
22 | },
23 | "interface": {
24 | "title": "Network interface",
25 | "description": "The network interface to use when sending and receiving mDNS packets. You probably don't need to use this setting unless you know what you're doing. If not specified, all available network interfaces will be used.",
26 | "type": "string",
27 | "placeholder": "e.g. eth0 or 192.168.1.100"
28 | }
29 | }
30 | },
31 | "websocket": {
32 | "type": "object",
33 | "properties": {
34 | "requestTimeout": {
35 | "title": "Request timeout",
36 | "type": "integer",
37 | "placeholder": "10",
38 | "description": "The time, in seconds, to wait for a response before a request is aborted."
39 | },
40 | "pingInterval": {
41 | "title": "Ping interval",
42 | "type": "integer",
43 | "placeholder": "60",
44 | "description": "The interval, in seconds, at which ping requests should be made to verify that the connection is open. Set to 0 to disable."
45 | },
46 | "reconnectInterval": {
47 | "title": "Reconnect intervals",
48 | "type": "string",
49 | "placeholder": "5,10,30,60,300,600",
50 | "description": "The interval, in seconds, at which a connection attempt should be made after a socket has been closed. Multiple intervals can be specified as a comma-separated list of numbers. Set to 0 to disable."
51 | }
52 | }
53 | },
54 | "devices": {
55 | "type": "array",
56 | "items": {
57 | "title": "Device",
58 | "type": "object",
59 | "properties": {
60 | "id": {
61 | "title": "Device ID",
62 | "description": "See this page for instructions on how to find your device's ID.",
63 | "type": "string",
64 | "placeholder": "e.g. shellyplus1-abcdef123456",
65 | "required": true
66 | },
67 | "name": {
68 | "title": "Name",
69 | "description": "This name will be shown in the homebridge log and will be used as the default name when the device is added to HomeKit. Note though that setting this value after the device has been added will not change the name in HomeKit.",
70 | "type": "string"
71 | },
72 | "exclude": {
73 | "title": "Exclude this device",
74 | "type": "boolean",
75 | "default": false
76 | },
77 | "hostname": {
78 | "title": "IP address or hostname",
79 | "description": "Set this value if your device can't be discovered automatically.",
80 | "type": "string",
81 | "placeholder": "e.g. 192.168.1.100"
82 | },
83 | "password": {
84 | "title": "Password",
85 | "type": "string",
86 | "description": "The password to use if the Shelly device requires authentication."
87 | },
88 | "switch:0": {
89 | "title": "Switch 1",
90 | "type": "object",
91 | "properties": {
92 | "exclude": {
93 | "title": "Exclude this switch",
94 | "type": "boolean",
95 | "default": false
96 | },
97 | "type": {
98 | "title": "Type",
99 | "description": "The type of accessory used to represent the switch.",
100 | "type": "string",
101 | "oneOf": [
102 | { "title": "Outlet", "enum": [ "outlet" ] },
103 | { "title": "Switch", "enum": [ "switch" ] }
104 | ],
105 | "default": "switch"
106 | }
107 | }
108 | },
109 | "switch:1": {
110 | "title": "Switch 2",
111 | "type": "object",
112 | "properties": {
113 | "exclude": {
114 | "title": "Exclude this switch",
115 | "type": "boolean",
116 | "default": false
117 | },
118 | "type": {
119 | "title": "Type",
120 | "description": "The type of accessory used to represent the switch.",
121 | "type": "string",
122 | "oneOf": [
123 | { "title": "Outlet", "enum": [ "outlet" ] },
124 | { "title": "Switch", "enum": [ "switch" ] }
125 | ],
126 | "default": "switch"
127 | }
128 | }
129 | },
130 | "switch:2": {
131 | "title": "Switch 3",
132 | "type": "object",
133 | "properties": {
134 | "exclude": {
135 | "title": "Exclude this switch",
136 | "type": "boolean",
137 | "default": false
138 | },
139 | "type": {
140 | "title": "Type",
141 | "description": "The type of accessory used to represent the switch.",
142 | "type": "string",
143 | "oneOf": [
144 | { "title": "Outlet", "enum": [ "outlet" ] },
145 | { "title": "Switch", "enum": [ "switch" ] }
146 | ],
147 | "default": "switch"
148 | }
149 | }
150 | },
151 | "switch:3": {
152 | "title": "Switch 4",
153 | "type": "object",
154 | "properties": {
155 | "exclude": {
156 | "title": "Exclude this switch",
157 | "type": "boolean",
158 | "default": false
159 | },
160 | "type": {
161 | "title": "Type",
162 | "description": "The type of accessory used to represent the switch.",
163 | "type": "string",
164 | "oneOf": [
165 | { "title": "Outlet", "enum": [ "outlet" ] },
166 | { "title": "Switch", "enum": [ "switch" ] }
167 | ],
168 | "default": "switch"
169 | }
170 | }
171 | },
172 | "cover:0": {
173 | "title": "Cover",
174 | "type": "object",
175 | "properties": {
176 | "exclude": {
177 | "title": "Exclude this cover",
178 | "type": "boolean",
179 | "default": false
180 | },
181 | "type": {
182 | "title": "Type",
183 | "description": "The type of accessory used to represent the cover. This setting apply only when the device is in cover mode.",
184 | "type": "string",
185 | "oneOf": [
186 | { "title": "Door", "enum": [ "door" ] },
187 | { "title": "Window", "enum": [ "window" ] },
188 | { "title": "Window Covering", "enum": [ "windowCovering" ] }
189 | ],
190 | "default": "window"
191 | }
192 | }
193 | }
194 | }
195 | }
196 | }
197 | }
198 | },
199 | "layout": [
200 | "name",
201 | {
202 | "key": "devices",
203 | "type": "array",
204 | "title": "Devices",
205 | "description": "Use these settings to configure individual devices. Note though that unless your devices can't be discovered using mDNS, you don't necessarily have to add them here manually.",
206 | "items": [
207 | "devices[].id",
208 | "devices[].exclude",
209 | {
210 | "key": "devices[].name",
211 | "condition": {
212 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude"
213 | }
214 | },
215 | {
216 | "key": "devices[].hostname",
217 | "condition": {
218 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude"
219 | }
220 | },
221 | {
222 | "key": "devices[].password",
223 | "condition": {
224 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude"
225 | }
226 | },
227 | {
228 | "key": "devices[].switch:0",
229 | "condition": {
230 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude && model.devices[arrayIndices[0]].id && model.devices[arrayIndices[0]].id.match(/^\\s*(?:shellyplus1|shellyplus1pm|shellyplus2pm|shellyplusplug|shellyplusplugus|shellypro1|shellypro1pm|shellypro2|shellypro2pm|shellypro3|shellypro4pm)-/i) !== null"
231 | },
232 | "items": [
233 | "devices[].switch:0.exclude",
234 | "devices[].switch:0.type"
235 | ]
236 | },
237 | {
238 | "key": "devices[].switch:1",
239 | "condition": {
240 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude && model.devices[arrayIndices[0]].id && model.devices[arrayIndices[0]].id.match(/^\\s*(?:shellyplus2pm|shellypro2|shellypro2pm|shellypro3|shellypro4pm)-/i) !== null"
241 | },
242 | "items": [
243 | "devices[].switch:1.exclude",
244 | "devices[].switch:1.type"
245 | ]
246 | },
247 | {
248 | "key": "devices[].switch:2",
249 | "condition": {
250 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude && model.devices[arrayIndices[0]].id && model.devices[arrayIndices[0]].id.match(/^\\s*(?:shellypro3|shellypro4pm)-/i) !== null"
251 | },
252 | "items": [
253 | "devices[].switch:2.exclude",
254 | "devices[].switch:2.type"
255 | ]
256 | },
257 | {
258 | "key": "devices[].switch:3",
259 | "condition": {
260 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude && model.devices[arrayIndices[0]].id && model.devices[arrayIndices[0]].id.match(/^\\s*(?:shellypro4pm)-/i) !== null"
261 | },
262 | "items": [
263 | "devices[].switch:3.exclude",
264 | "devices[].switch:3.type"
265 | ]
266 | },
267 | {
268 | "key": "devices[].cover:0",
269 | "condition": {
270 | "functionBody": "return model.devices && !model.devices[arrayIndices[0]].exclude && model.devices[arrayIndices[0]].id && model.devices[arrayIndices[0]].id.match(/\\s*(?:shellyplus2pm|shellypro2pm)-/i) !== null"
271 | },
272 | "items": [
273 | "devices[].cover:0.exclude",
274 | "devices[].cover:0.type"
275 | ]
276 | }
277 | ]
278 | },
279 | {
280 | "type": "fieldset",
281 | "expandable": true,
282 | "title": "mDNS device discovery",
283 | "items": [
284 | "mdns.enable",
285 | {
286 | "key": "mdns.interface",
287 | "condition": "mdns.enable"
288 | }
289 | ]
290 | },
291 | {
292 | "type": "fieldset",
293 | "expandable": true,
294 | "title": "WebSocket connections",
295 | "items": [
296 | "websocket.requestTimeout",
297 | "websocket.pingInterval",
298 | "websocket.reconnectInterval"
299 | ]
300 | }
301 | ]
302 | }
303 |
--------------------------------------------------------------------------------
/homebridge-shelly-ng.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/alexryd/homebridge-shelly-ng/1da481054a089dbdd2260e6c88cd7cff92143cd1/homebridge-shelly-ng.png
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
3 | module.exports = {
4 | preset: 'ts-jest',
5 | testEnvironment: 'node',
6 | };
7 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "homebridge-shelly-ng",
3 | "version": "1.6.0",
4 | "description": "Homebridge plugin for the next generation of Shelly devices",
5 | "main": "dist/index.js",
6 | "scripts": {
7 | "build": "rimraf ./dist && tsc",
8 | "lint": "eslint ./src --ext .ts,.js --max-warnings=0",
9 | "test": "jest",
10 | "preversion": "npm run build && npm run lint",
11 | "postversion": "git push && git push --tags"
12 | },
13 | "engines": {
14 | "node": ">=14.18.3",
15 | "homebridge": ">=1.3.5"
16 | },
17 | "repository": {
18 | "type": "git",
19 | "url": "git+https://github.com/alexryd/homebridge-shelly-ng.git"
20 | },
21 | "keywords": [
22 | "homebridge",
23 | "homebridge-plugin",
24 | "shelly"
25 | ],
26 | "author": "Alexander Rydén",
27 | "license": "GPL-3.0",
28 | "bugs": {
29 | "url": "https://github.com/alexryd/homebridge-shelly-ng/issues"
30 | },
31 | "homepage": "https://github.com/alexryd/homebridge-shelly-ng#readme",
32 | "funding": {
33 | "type": "kofi",
34 | "url": "https://ko-fi.com/alexryd"
35 | },
36 | "devDependencies": {
37 | "@types/jest": "^28.1.2",
38 | "@types/node": "^18.0.0",
39 | "@typescript-eslint/eslint-plugin": "^5.28.0",
40 | "@typescript-eslint/parser": "^5.28.0",
41 | "eslint": "^8.18.0",
42 | "homebridge": "^1.5.0",
43 | "jest": "^28.1.1",
44 | "rimraf": "^3.0.2",
45 | "ts-jest": "^28.0.5",
46 | "typescript": "^4.7.4"
47 | },
48 | "dependencies": {
49 | "shellies-ng": "^1.5.1"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/abilities/accessory-information.ts:
--------------------------------------------------------------------------------
1 | import { Device } from 'shellies-ng';
2 |
3 | import { Ability, ServiceClass } from './base';
4 |
5 | /**
6 | * Handles the AccessoryInformation service.
7 | */
8 | export class AccessoryInformationAbility extends Ability {
9 | /**
10 | * @param device - The associated device.
11 | */
12 | constructor(readonly device: Device) {
13 | super();
14 | }
15 |
16 | protected get serviceClass(): ServiceClass {
17 | return this.Service.AccessoryInformation;
18 | }
19 |
20 | protected initialize() {
21 | this.service
22 | .setCharacteristic(this.Characteristic.Name, this.platformAccessory.displayName)
23 | .setCharacteristic(this.Characteristic.Manufacturer, 'Allterco')
24 | .setCharacteristic(this.Characteristic.Model, this.device.modelName)
25 | .setCharacteristic(this.Characteristic.SerialNumber, this.device.macAddress)
26 | .setCharacteristic(this.Characteristic.FirmwareRevision, this.device.firmware.version || '1.0.0');
27 | }
28 |
29 | detach() {
30 | // no event handlers
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/abilities/base.ts:
--------------------------------------------------------------------------------
1 | import {
2 | API,
3 | Characteristic,
4 | PlatformAccessory,
5 | Service,
6 | WithUUID,
7 | } from 'homebridge';
8 |
9 | import { CustomCharacteristics } from '../utils/characteristics';
10 | import { CustomServices } from '../utils/services';
11 | import { DeviceLogger } from '../utils/device-logger';
12 | import { ShellyPlatform } from '../platform';
13 |
14 | export type ServiceClass = WithUUID;
15 |
16 | /**
17 | * Base class for all abilities.
18 | * An ability is roughly equivalent to a HomeKit service.
19 | */
20 | export abstract class Ability {
21 | private _platformAccessory: PlatformAccessory | null = null;
22 |
23 | /**
24 | * The associated platform accessory.
25 | */
26 | get platformAccessory(): PlatformAccessory {
27 | if (this._platformAccessory === null) {
28 | throw new Error('Ability has not yet been setup');
29 | }
30 | return this._platformAccessory;
31 | }
32 |
33 | private _platform: ShellyPlatform | null = null;
34 |
35 | /**
36 | * A reference to the platform.
37 | */
38 | protected get platform(): ShellyPlatform {
39 | if (this._platform === null) {
40 | throw new Error('Ability has not yet been setup');
41 | }
42 | return this._platform;
43 | }
44 |
45 | /**
46 | * A reference to the homebridge API.
47 | */
48 | protected get api(): API {
49 | return this.platform.api;
50 | }
51 |
52 | /**
53 | * Shorthand property.
54 | */
55 | protected get Characteristic(): typeof Characteristic {
56 | return this.platform.api.hap.Characteristic;
57 | }
58 |
59 | /**
60 | * Shorthand property.
61 | */
62 | protected get Service(): typeof Service {
63 | return this.platform.api.hap.Service;
64 | }
65 |
66 | /**
67 | * Shorthand property.
68 | */
69 | protected get customCharacteristics(): CustomCharacteristics {
70 | return this.platform.customCharacteristics;
71 | }
72 |
73 | /**
74 | * Shorthand property.
75 | */
76 | protected get customServices(): CustomServices {
77 | return this.platform.customServices;
78 | }
79 |
80 | private _log: DeviceLogger | null = null;
81 |
82 | /**
83 | * The logging device to use.
84 | */
85 | protected get log(): DeviceLogger {
86 | if (this._log === null) {
87 | throw new Error('Ability has not yet been setup');
88 | }
89 | return this._log;
90 | }
91 |
92 | private _service: Service | null = null;
93 |
94 | /**
95 | * The HomeKit service that this ability uses.
96 | */
97 | protected get service(): Service {
98 | if (this._service === null) {
99 | throw new Error('Ability has not yet been setup');
100 | }
101 | return this._service;
102 | }
103 |
104 | private _active = true;
105 |
106 | /**
107 | * Whether this ability is active.
108 | * Setting an ability to inactive will remove its HomeKit service.
109 | */
110 | get active(): boolean {
111 | return this._active;
112 | }
113 |
114 | set active(value) {
115 | if (value === this._active) {
116 | return;
117 | }
118 |
119 | this._active = value;
120 | this.update();
121 | }
122 |
123 | /**
124 | * @param serviceName - A name of the service.
125 | * @param serviceSubtype - A unique identifier for the service.
126 | */
127 | constructor(
128 | protected readonly serviceName?: string,
129 | protected readonly serviceSubtype?: string,
130 | ) {}
131 |
132 | /**
133 | * Sets up this ability.
134 | * This method is called by the parent accessory every time it becomes active.
135 | * @param platformAccessory - The homebridge platform accessory to use.
136 | * @param platform - A reference to the platform.
137 | * @param log - The logger to use.
138 | */
139 | setup(platformAccessory: PlatformAccessory, platform: ShellyPlatform, log: DeviceLogger) {
140 | this._platformAccessory = platformAccessory;
141 | this._platform = platform;
142 | this._log = log;
143 |
144 | this.update();
145 | }
146 |
147 | /**
148 | * Sets `active` to the given value.
149 | * This method can be used when chaining calls, as it returns a reference to `this`.
150 | * @param value - Whether the ability should be active.
151 | */
152 | setActive(value: boolean): this {
153 | this.active = value;
154 | return this;
155 | }
156 |
157 | /**
158 | * Determines whether this ability is active.
159 | * The default implementation simply returns the value of the `active` property.
160 | * Subclasses can override this method to add more conditions.
161 | */
162 | protected isActive(): boolean {
163 | return this.active;
164 | }
165 |
166 | /**
167 | * Updates this ability based on whether it is active.
168 | * If active, its service will be added and initialized.
169 | * If inactive, its service will be removed.
170 | */
171 | protected update() {
172 | if (this._platformAccessory === null) {
173 | // abort if setup() hasn't been called yet
174 | return;
175 | }
176 |
177 | if (this.isActive()) {
178 | // we're active, add and initialize our service
179 | if (this._service === null) {
180 | this._service = this.addService();
181 | this.initialize();
182 | }
183 | } else {
184 | // we're inactive, detach from and remove our service
185 | if (this._service !== null) {
186 | this.detach();
187 | }
188 |
189 | this.removeService();
190 | this._service = null;
191 | }
192 | }
193 |
194 | /**
195 | * Returns a service for this ability.
196 | * If the platform accessory has a matching service, it will be returned. Otherwise, the service will be added.
197 | */
198 | protected addService(): Service {
199 | if (this.serviceName && this.serviceSubtype) {
200 | return this.platformAccessory.getService(this.serviceName)
201 | || this.platformAccessory.addService(this.serviceClass, this.serviceName, this.serviceSubtype);
202 | }
203 |
204 | return this.platformAccessory.getService(this.serviceClass)
205 | || this.platformAccessory.addService(this.serviceClass);
206 | }
207 |
208 | /**
209 | * Removes this ability's service from the platform accessory.
210 | */
211 | protected removeService() {
212 | let service: Service | undefined;
213 |
214 | // since the platform accessory may have been loaded from cache with a service created previously,
215 | // we can't just rely on the _service property here
216 | if (this._service !== null) {
217 | service = this._service;
218 | } else if (this.serviceName && this.serviceSubtype) {
219 | service = this.platformAccessory.getService(this.serviceName);
220 | } else {
221 | service = this.platformAccessory.getService(this.serviceClass);
222 | }
223 |
224 | if (service) {
225 | this.platformAccessory.removeService(service);
226 | }
227 | }
228 |
229 | /**
230 | * Helper method that removes a characteristic based on its class (Service.removeCharacteristic()
231 | * only accepts an instance).
232 | * @param characteristic - The characteristic to remove.
233 | */
234 | protected removeCharacteristic(characteristic: WithUUID Characteristic> & WithUUID) {
235 | const s = this.service;
236 |
237 | // getCharacteristic() will add the characteristic if it doesn't exist, so we need to use testCharacteristic() to avoid
238 | // adding and then immediately removing it
239 | if (s.testCharacteristic(characteristic)) {
240 | s.removeCharacteristic(s.getCharacteristic(characteristic));
241 | }
242 | }
243 |
244 | /**
245 | * Subclasses should implement this method to return the HomeKit service type to use.
246 | */
247 | protected abstract get serviceClass(): ServiceClass;
248 |
249 | /**
250 | * Subclasses should use this method to initialize the service and attach their event listeners.
251 | */
252 | protected abstract initialize();
253 |
254 | /**
255 | * Subclasses should use this method to remove their event listeners.
256 | */
257 | abstract detach();
258 |
259 | /**
260 | * Removes all event listeners and all references to the platform accessory.
261 | * This method is called by the parent accessory every time it becomes inactive.
262 | * Note that this method doesn't remove the service from the platform accessory as it is assumed that
263 | * the entire platform accessory is about to be unregistered and discarded.
264 | */
265 | destroy() {
266 | this.detach();
267 |
268 | this._platformAccessory = null;
269 | this._platform = null;
270 | this._log = null;
271 | this._service = null;
272 | }
273 | }
274 |
--------------------------------------------------------------------------------
/src/abilities/cover.ts:
--------------------------------------------------------------------------------
1 | import { CharacteristicValue } from 'homebridge';
2 | import { Cover } from 'shellies-ng';
3 |
4 | import { Ability, ServiceClass } from './base';
5 |
6 | const names = {
7 | 'door': 'Door',
8 | 'window': 'Window',
9 | 'windowCovering': 'Window Covering',
10 | };
11 |
12 | export class CoverAbility extends Ability {
13 | /**
14 | * @param component - The cover component to control.
15 | */
16 | constructor(readonly component: Cover, readonly type: 'door' | 'window' | 'windowCovering' = 'window') {
17 | super(
18 | `${names[type]} ${component.id + 1}`,
19 | `${type}-${component.id}`,
20 | );
21 | }
22 |
23 | protected get serviceClass(): ServiceClass {
24 | if (this.type === 'door') {
25 | return this.Service.Door;
26 | } else if (this.type === 'windowCovering') {
27 | return this.Service.WindowCovering;
28 | }
29 | return this.Service.Window;
30 | }
31 |
32 | /**
33 | * The current state of the cover.
34 | */
35 | protected get positionState(): number {
36 | const state = this.component.state;
37 |
38 | if (state === 'opening') {
39 | return this.Characteristic.PositionState.INCREASING;
40 | } else if (state === 'closing') {
41 | return this.Characteristic.PositionState.DECREASING;
42 | }
43 |
44 | return this.Characteristic.PositionState.STOPPED;
45 | }
46 |
47 | /**
48 | * The current position of the cover.
49 | */
50 | protected get currentPosition(): number {
51 | return this.component.current_pos ?? 0;
52 | }
53 |
54 | /**
55 | * The target position that the cover is moving towards.
56 | */
57 | protected get targetPosition(): number {
58 | return this.component.target_pos ?? this.currentPosition;
59 | }
60 |
61 | protected initialize() {
62 | // abort if this cover hasn't been calibrated
63 | if (this.component.pos_control !== true) {
64 | this.log.warn('Only calibrated covers are supported.');
65 | return;
66 | }
67 |
68 | // set the initial values
69 | this.service
70 | .setCharacteristic(this.Characteristic.PositionState, this.positionState)
71 | .setCharacteristic(this.Characteristic.CurrentPosition, this.currentPosition)
72 | .setCharacteristic(this.Characteristic.TargetPosition, this.targetPosition);
73 |
74 | // listen for commands from HomeKit
75 | this.service.getCharacteristic(this.Characteristic.TargetPosition)
76 | .onSet(this.targetPositionSetHandler.bind(this));
77 |
78 | // listen for updates from the device
79 | this.component
80 | .on('change:state', this.stateChangeHandler, this)
81 | .on('change:current_pos', this.currentPosChangeHandler, this)
82 | .on('change:target_pos', this.targetPosChangeHandler, this);
83 | }
84 |
85 | detach() {
86 | this.component
87 | .off('change:state', this.stateChangeHandler, this)
88 | .off('change:current_pos', this.currentPosChangeHandler, this)
89 | .off('change:target_pos', this.targetPosChangeHandler, this);
90 | }
91 |
92 | /**
93 | * Handles changes to the TargetPosition characteristic.
94 | */
95 | protected async targetPositionSetHandler(value: CharacteristicValue) {
96 | if (value === this.component.target_pos) {
97 | return;
98 | }
99 |
100 | try {
101 | await this.component.goToPosition(value as number);
102 | } catch (e) {
103 | this.log.error(
104 | 'Failed to set target position:',
105 | e instanceof Error ? e.message : e,
106 | );
107 | throw this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE;
108 | }
109 | }
110 |
111 | /**
112 | * Handles changes to the `state` property.
113 | */
114 | protected stateChangeHandler() {
115 | this.service.getCharacteristic(this.Characteristic.PositionState)
116 | .updateValue(this.positionState);
117 | }
118 |
119 | /**
120 | * Handles changes to the `current_pos` property.
121 | */
122 | protected currentPosChangeHandler() {
123 | this.service.getCharacteristic(this.Characteristic.CurrentPosition)
124 | .updateValue(this.currentPosition);
125 | }
126 |
127 | /**
128 | * Handles changes to the `target_pos` property.
129 | */
130 | protected targetPosChangeHandler() {
131 | this.service.getCharacteristic(this.Characteristic.TargetPosition)
132 | .updateValue(this.targetPosition);
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/abilities/index.ts:
--------------------------------------------------------------------------------
1 | export * from './base';
2 |
3 | export * from './accessory-information';
4 | export * from './cover';
5 | export * from './outlet';
6 | export * from './power-meter';
7 | export * from './readonly-switch';
8 | export * from './service-label';
9 | export * from './stateless-programmable-switch';
10 | export * from './switch';
11 |
--------------------------------------------------------------------------------
/src/abilities/outlet.ts:
--------------------------------------------------------------------------------
1 | import { CharacteristicValue } from 'homebridge';
2 | import { CharacteristicValue as ShelliesCharacteristicValue, Switch } from 'shellies-ng';
3 |
4 | import { Ability, ServiceClass } from './base';
5 |
6 | export class OutletAbility extends Ability {
7 | /**
8 | * @param component - The switch component to control.
9 | */
10 | constructor(readonly component: Switch) {
11 | super(
12 | `Outlet ${component.id + 1}`,
13 | `outlet-${component.id}`,
14 | );
15 | }
16 |
17 | protected get serviceClass(): ServiceClass {
18 | return this.Service.Outlet;
19 | }
20 |
21 | protected initialize() {
22 | // set the initial values
23 | this.service
24 | .setCharacteristic(
25 | this.Characteristic.On,
26 | this.component.output,
27 | ).setCharacteristic(
28 | this.Characteristic.OutletInUse,
29 | this.component.apower !== undefined && this.component.apower !== 0,
30 | );
31 |
32 | // listen for commands from HomeKit
33 | this.service.getCharacteristic(this.Characteristic.On)
34 | .onSet(this.onSetHandler.bind(this));
35 |
36 | // listen for updates from the device
37 | this.component
38 | .on('change:output', this.outputChangeHandler, this)
39 | .on('change:apower', this.apowerChangeHandler, this);
40 | }
41 |
42 | detach() {
43 | this.component
44 | .off('change:output', this.outputChangeHandler, this)
45 | .off('change:apower', this.apowerChangeHandler, this);
46 | }
47 |
48 | /**
49 | * Handles changes to the Outlet.On characteristic.
50 | */
51 | protected async onSetHandler(value: CharacteristicValue) {
52 | if (value === this.component.output) {
53 | return;
54 | }
55 |
56 | try {
57 | await this.component.set(value as boolean);
58 | } catch (e) {
59 | this.log.error(
60 | 'Failed to set switch:',
61 | e instanceof Error ? e.message : e,
62 | );
63 | throw this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE;
64 | }
65 | }
66 |
67 | /**
68 | * Handles changes to the `output` property.
69 | */
70 | protected outputChangeHandler(value: ShelliesCharacteristicValue) {
71 | this.service.getCharacteristic(this.Characteristic.On)
72 | .updateValue(value as boolean);
73 | }
74 |
75 | /**
76 | * Handles changes to the `apower` property.
77 | */
78 | protected apowerChangeHandler(value: ShelliesCharacteristicValue) {
79 | this.service.getCharacteristic(this.Characteristic.OutletInUse)
80 | .updateValue(value as number);
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/src/abilities/power-meter.ts:
--------------------------------------------------------------------------------
1 | import {
2 | CharacteristicValue as ShelliesCharacteristicValue,
3 | Cover,
4 | Switch,
5 | SwitchEnergyCounterAttributes,
6 | } from 'shellies-ng';
7 |
8 | import { Ability, ServiceClass } from './base';
9 |
10 | /**
11 | * This ability sets up a custom service that reports power meter readings.
12 | */
13 | export class PowerMeterAbility extends Ability {
14 | /**
15 | * @param component - The switch or cover component to get readings from.
16 | */
17 | constructor(readonly component: Switch | Cover) {
18 | super(
19 | `Power Meter ${component.id + 1}`,
20 | `power-meter-${component.id}`,
21 | );
22 | }
23 |
24 | protected get serviceClass(): ServiceClass {
25 | return this.customServices.PowerMeter;
26 | }
27 |
28 | protected initialize() {
29 | const s = this.service;
30 | const c = this.component;
31 | const cc = this.customCharacteristics;
32 |
33 | // setup Current Consumption
34 | s.setCharacteristic(
35 | cc.CurrentConsumption,
36 | c.apower ?? 0,
37 | );
38 |
39 | c.on('change:apower', this.apowerChangeHandler, this);
40 |
41 | // setup Voltage
42 | if (c.voltage !== undefined) {
43 | s.setCharacteristic(
44 | cc.Voltage,
45 | c.voltage,
46 | );
47 |
48 | c.on('change:voltage', this.voltageChangeHandler, this);
49 | } else {
50 | this.removeCharacteristic(cc.Voltage);
51 | }
52 |
53 | // setup Electric Current
54 | if (c.current !== undefined) {
55 | s.setCharacteristic(
56 | cc.ElectricCurrent,
57 | c.current,
58 | );
59 |
60 | c.on('change:current', this.currentChangeHandler, this);
61 | } else {
62 | this.removeCharacteristic(cc.ElectricCurrent);
63 | }
64 |
65 | // setup Total Consumption
66 | if (c.aenergy !== undefined) {
67 | s.setCharacteristic(
68 | cc.TotalConsumption,
69 | c.aenergy.total / 1000,
70 | );
71 |
72 | c.on('change:aenergy', this.aenergyChangeHandler, this);
73 | } else {
74 | this.removeCharacteristic(cc.TotalConsumption);
75 | }
76 | }
77 |
78 | detach() {
79 | this.component
80 | .off('change:apower', this.apowerChangeHandler, this)
81 | .off('change:voltage', this.voltageChangeHandler, this)
82 | .off('change:current', this.currentChangeHandler, this)
83 | .off('change:aenergy', this.aenergyChangeHandler, this);
84 | }
85 |
86 | /**
87 | * Handles changes to the `apower` property.
88 | */
89 | protected apowerChangeHandler(value: ShelliesCharacteristicValue) {
90 | this.service.updateCharacteristic(
91 | this.customCharacteristics.CurrentConsumption,
92 | value as number,
93 | );
94 | }
95 |
96 | /**
97 | * Handles changes to the `voltage` property.
98 | */
99 | protected voltageChangeHandler(value: ShelliesCharacteristicValue) {
100 | this.service.updateCharacteristic(
101 | this.customCharacteristics.Voltage,
102 | value as number,
103 | );
104 | }
105 |
106 | /**
107 | * Handles changes to the `current` property.
108 | */
109 | protected currentChangeHandler(value: ShelliesCharacteristicValue) {
110 | this.service.updateCharacteristic(
111 | this.customCharacteristics.ElectricCurrent,
112 | value as number,
113 | );
114 | }
115 |
116 | /**
117 | * Handles changes to the `aenergy` property.
118 | */
119 | protected aenergyChangeHandler(value: ShelliesCharacteristicValue) {
120 | const attr = (value as unknown) as SwitchEnergyCounterAttributes;
121 |
122 | this.service.updateCharacteristic(
123 | this.customCharacteristics.TotalConsumption,
124 | attr.total / 1000,
125 | );
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/abilities/readonly-switch.ts:
--------------------------------------------------------------------------------
1 | import { Perms } from 'homebridge';
2 | import { CharacteristicValue as ShelliesCharacteristicValue, Input } from 'shellies-ng';
3 |
4 | import { Ability, ServiceClass } from './base';
5 |
6 | /**
7 | * This ability creates a switch that can't be controlled from HomeKit, it only reflects
8 | * the device's input state.
9 | */
10 | export class ReadonlySwitchAbility extends Ability {
11 | /**
12 | * @param component - The input component to represent.
13 | */
14 | constructor(readonly component: Input) {
15 | super(
16 | `Switch ${component.id + 1}`,
17 | `readonly-switch-${component.id}`,
18 | );
19 | }
20 |
21 | protected get serviceClass(): ServiceClass {
22 | return this.Service.Switch;
23 | }
24 |
25 | protected initialize() {
26 | this.service.getCharacteristic(this.Characteristic.On)
27 | // remove the write permissions
28 | .setProps({
29 | perms: [Perms.NOTIFY, Perms.PAIRED_READ],
30 | })
31 | // set the initial value
32 | .setValue(this.component.state ?? false);
33 |
34 | // listen for updates from the device
35 | this.component.on('change:state', this.stateChangeHandler, this);
36 | }
37 |
38 | detach() {
39 | this.component.off('change:state', this.stateChangeHandler, this);
40 | }
41 |
42 | /**
43 | * Handles changes to the `state` property.
44 | */
45 | protected stateChangeHandler(value: ShelliesCharacteristicValue) {
46 | const v: boolean = value === null ? false : value as boolean;
47 |
48 | this.service.getCharacteristic(this.Characteristic.On)
49 | .updateValue(v);
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/abilities/service-label.ts:
--------------------------------------------------------------------------------
1 | import { Ability, ServiceClass } from './base';
2 |
3 | export class ServiceLabelAbility extends Ability {
4 | /**
5 | * @param namespace - The naming schema for the accessory.
6 | */
7 | constructor(readonly namespace: 'dots' | 'arabicNumerals' = 'arabicNumerals') {
8 | super();
9 | }
10 |
11 | protected get serviceClass(): ServiceClass {
12 | return this.Service.ServiceLabel;
13 | }
14 |
15 | protected initialize() {
16 | const SLN = this.Characteristic.ServiceLabelNamespace;
17 |
18 | // set the namespace
19 | this.service.setCharacteristic(
20 | SLN,
21 | this.namespace === 'dots' ? SLN.DOTS : SLN.ARABIC_NUMERALS,
22 | );
23 | }
24 |
25 | detach() {
26 | // nothing to detach
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/abilities/stateless-programmable-switch.ts:
--------------------------------------------------------------------------------
1 | import { Input } from 'shellies-ng';
2 |
3 | import { Ability, ServiceClass } from './base';
4 |
5 | enum ButtonPress {
6 | Single = 'single',
7 | Double = 'double',
8 | Long = 'long',
9 | }
10 |
11 | export class StatelessProgrammableSwitchAbility extends Ability {
12 | /**
13 | * @param component - The input component to control.
14 | */
15 | constructor(readonly component: Input) {
16 | super(
17 | `Button ${component.id + 1}`,
18 | `stateless-programmable-switch-${component.id}`,
19 | );
20 | }
21 |
22 | protected get serviceClass(): ServiceClass {
23 | return this.Service.StatelessProgrammableSwitch;
24 | }
25 |
26 | protected initialize() {
27 | // set the index number for this switch
28 | this.service.setCharacteristic(
29 | this.Characteristic.ServiceLabelIndex,
30 | this.component.id + 1,
31 | );
32 |
33 | // listen for button press events
34 | this.component
35 | .on('singlePush', this.singlePushHandler, this)
36 | .on('doublePush', this.doublePushHandler, this)
37 | .on('longPush', this.longPushHandler, this);
38 | }
39 |
40 | detach() {
41 | this.component
42 | .off('singlePush', this.singlePushHandler, this)
43 | .off('doublePush', this.doublePushHandler, this)
44 | .off('longPush', this.longPushHandler, this);
45 | }
46 |
47 | /**
48 | * Triggers a button press event.
49 | * @param type - The type of button press to trigger.
50 | */
51 | protected triggerPress(type: ButtonPress) {
52 | this.log.debug(`Input ${this.component.id}: ${type} press`);
53 |
54 | const PSE = this.Characteristic.ProgrammableSwitchEvent;
55 | let value: number;
56 |
57 | // get the corresponding characteristic value
58 | switch (type) {
59 | case ButtonPress.Single:
60 | value = PSE.SINGLE_PRESS;
61 | break;
62 |
63 | case ButtonPress.Double:
64 | value = PSE.DOUBLE_PRESS;
65 | break;
66 |
67 | case ButtonPress.Long:
68 | value = PSE.LONG_PRESS;
69 | break;
70 | }
71 |
72 | // update the characteristic
73 | this.service.getCharacteristic(this.Characteristic.ProgrammableSwitchEvent)
74 | .updateValue(value);
75 | }
76 |
77 | /**
78 | * Handles 'singlePush' events from our input component.
79 | */
80 | protected singlePushHandler() {
81 | this.triggerPress(ButtonPress.Single);
82 | }
83 |
84 | /**
85 | * Handles 'doublePush' events from our input component.
86 | */
87 | protected doublePushHandler() {
88 | this.triggerPress(ButtonPress.Double);
89 | }
90 |
91 | /**
92 | * Handles 'longPush' events from our input component.
93 | */
94 | protected longPushHandler() {
95 | this.triggerPress(ButtonPress.Long);
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/abilities/switch.ts:
--------------------------------------------------------------------------------
1 | import { CharacteristicValue } from 'homebridge';
2 | import { CharacteristicValue as ShelliesCharacteristicValue, Switch } from 'shellies-ng';
3 |
4 | import { Ability, ServiceClass } from './base';
5 |
6 | export class SwitchAbility extends Ability {
7 | /**
8 | * @param component - The switch component to control.
9 | */
10 | constructor(readonly component: Switch) {
11 | super(
12 | `Switch ${component.id + 1}`,
13 | `switch-${component.id}`,
14 | );
15 | }
16 |
17 | protected get serviceClass(): ServiceClass {
18 | return this.Service.Switch;
19 | }
20 |
21 | protected initialize() {
22 | // set the initial value
23 | this.service.setCharacteristic(
24 | this.Characteristic.On,
25 | this.component.output,
26 | );
27 |
28 | // listen for commands from HomeKit
29 | this.service.getCharacteristic(this.Characteristic.On)
30 | .onSet(this.onSetHandler.bind(this));
31 |
32 | // listen for updates from the device
33 | this.component.on('change:output', this.outputChangeHandler, this);
34 | }
35 |
36 | detach() {
37 | this.component.off('change:output', this.outputChangeHandler, this);
38 | }
39 |
40 | /**
41 | * Handles changes to the Switch.On characteristic.
42 | */
43 | protected async onSetHandler(value: CharacteristicValue) {
44 | if (value === this.component.output) {
45 | return;
46 | }
47 |
48 | try {
49 | await this.component.set(value as boolean);
50 | } catch (e) {
51 | this.log.error(
52 | 'Failed to set switch:',
53 | e instanceof Error ? e.message : e,
54 | );
55 | throw this.api.hap.HAPStatus.SERVICE_COMMUNICATION_FAILURE;
56 | }
57 | }
58 |
59 | /**
60 | * Handles changes to the `output` property.
61 | */
62 | protected outputChangeHandler(value: ShelliesCharacteristicValue) {
63 | this.service.getCharacteristic(this.Characteristic.On)
64 | .updateValue(value as boolean);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/accessory.ts:
--------------------------------------------------------------------------------
1 | import { DeviceId } from 'shellies-ng';
2 | import { PlatformAccessory } from 'homebridge';
3 |
4 | import { Ability } from './abilities';
5 | import { DeviceLogger } from './utils/device-logger';
6 | import { ShellyPlatform } from './platform';
7 |
8 | export type AccessoryId = string;
9 | export type AccessoryUuid = string;
10 |
11 | /**
12 | * Represents a HomeKit accessory.
13 | */
14 | export class Accessory {
15 | /**
16 | * The UUID used to identify this accessory with HomeKit.
17 | */
18 | readonly uuid: AccessoryUuid;
19 |
20 | protected _platformAccessory: PlatformAccessory | null;
21 |
22 | /**
23 | * The underlying homebridge platform accessory.
24 | * This property will be `null` when the accessory is inactive.
25 | */
26 | get platformAccessory(): PlatformAccessory | null {
27 | return this._platformAccessory;
28 | }
29 |
30 | /**
31 | * Holds this accessory's abilities.
32 | */
33 | readonly abilities: Ability[];
34 |
35 | private _active = true;
36 |
37 | /**
38 | * Whether this accessory is active.
39 | * Setting an accessory to inactive will remove it from HoneKit.
40 | */
41 | get active(): boolean {
42 | return this._active;
43 | }
44 |
45 | set active(value) {
46 | if (value === this._active) {
47 | return;
48 | }
49 |
50 | this._active = value;
51 | this.update();
52 | }
53 |
54 | /**
55 | * Timeout used to delay calls to `update()`.
56 | */
57 | protected updateTimeout: ReturnType | null = null;
58 |
59 | /**
60 | * @param id - The accessory ID.
61 | * @param deviceId - The associated device ID.
62 | * @param name - A user-friendly name of the accessory.
63 | * @param platform - A reference to the homebridge platform.
64 | * @param log - The logger to use.
65 | * @param abilities - The abilities that this accessory has.
66 | */
67 | constructor(
68 | readonly id: AccessoryId,
69 | readonly deviceId: DeviceId,
70 | readonly name: string,
71 | readonly platform: ShellyPlatform,
72 | readonly log: DeviceLogger,
73 | ...abilities: Ability[]) {
74 | this.uuid = platform.api.hap.uuid.generate(`${deviceId}-${id}`);
75 | this.abilities = abilities;
76 |
77 | // try to load the platform accessory from cache
78 | this._platformAccessory = platform.getAccessory(this.uuid) || null;
79 | if (this._platformAccessory !== null) {
80 | log.debug(`Accessory loaded from cache (ID: ${id})`);
81 | }
82 |
83 | this.update();
84 | }
85 |
86 | /**
87 | * Sets `active` to the given value.
88 | * This method can be used when chaining calls, as it returns a reference to `this`.
89 | * @param value - Whether the accessory should be active.
90 | */
91 | setActive(value: boolean): this {
92 | this.active = value;
93 | return this;
94 | }
95 |
96 | /**
97 | * Updates this accessory based on whether it is active.
98 | */
99 | protected update() {
100 | // clear any running timeout
101 | if (this.updateTimeout !== null) {
102 | clearTimeout(this.updateTimeout);
103 | }
104 |
105 | // call either activate() or deactivate() depending on whether the accessory is active
106 | // these calls are made after a short timeout to avoid unnecessary activations when an
107 | // accessory is deactivated immediately after construction
108 | this.updateTimeout = setTimeout(() => {
109 | this.updateTimeout = null;
110 |
111 | if (this.active) {
112 | this.activate();
113 | } else {
114 | this.deactivate();
115 | }
116 | }, 0);
117 | }
118 |
119 | /**
120 | * Activates this accessory, by creating a platform accessory and setting up all abilities.
121 | */
122 | protected activate() {
123 | if (this._platformAccessory === null) {
124 | // create a new platform accessory
125 | this._platformAccessory = this.createPlatformAccessory();
126 |
127 | this.log.debug(`Accessory activated (ID: ${this.id})`);
128 | }
129 |
130 | // setup all abilities
131 | for (const a of this.abilities) {
132 | try {
133 | a.setup(this._platformAccessory, this.platform, this.log);
134 | } catch (e) {
135 | this.log.error('Failed to setup ability:', e instanceof Error ? e.message : e);
136 | this.log.debug('Accessory ID:', this.id);
137 | if (e instanceof Error && e.stack) {
138 | this.log.debug(e.stack);
139 | }
140 | }
141 | }
142 |
143 | // register the platform accessory
144 | this.platform.addAccessory(this._platformAccessory);
145 | }
146 |
147 | /**
148 | * Deactivates this accessory, by destroying all abilities and the platform accessory.
149 | */
150 | protected deactivate() {
151 | // destroy all abilities
152 | for (const a of this.abilities) {
153 | try {
154 | a.destroy();
155 | } catch (e) {
156 | this.log.error('Failed to destroy ability:', e instanceof Error ? e.message : e);
157 | this.log.debug('Accessory ID:', this.id);
158 | if (e instanceof Error && e.stack) {
159 | this.log.debug(e.stack);
160 | }
161 | }
162 | }
163 |
164 | if (this._platformAccessory !== null) {
165 | // unregister the platform accessory
166 | this.platform.removeAccessory(this._platformAccessory);
167 | this._platformAccessory = null;
168 |
169 | this.log.debug(`Accessory deactivated (ID: ${this.id})`);
170 | }
171 | }
172 |
173 | /**
174 | * Creates a new platform accessory for this accessory.
175 | */
176 | protected createPlatformAccessory(): PlatformAccessory {
177 | // create a new accessory
178 | const pa = new this.platform.api.platformAccessory(
179 | this.name,
180 | this.uuid,
181 | );
182 |
183 | // store info in the context
184 | pa.context.device = {
185 | id: this.deviceId,
186 | };
187 |
188 | return pa;
189 | }
190 |
191 | /**
192 | * Removes all event listeners from this accessory.
193 | */
194 | detach() {
195 | // abort any pending update
196 | if (this.updateTimeout !== null) {
197 | clearTimeout(this.updateTimeout);
198 | this.updateTimeout = null;
199 | }
200 |
201 | // invoke detach() on all abilities
202 | for (const a of this.abilities) {
203 | try {
204 | a.detach();
205 | } catch (e) {
206 | this.log.error('Failed to detach ability:', e instanceof Error ? e.message : e);
207 | this.log.debug('Accessory ID:', this.id);
208 | if (e instanceof Error && e.stack) {
209 | this.log.debug(e.stack);
210 | }
211 | }
212 | }
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/src/config.ts:
--------------------------------------------------------------------------------
1 | import { PlatformConfig } from 'homebridge';
2 |
3 | import { DeviceId } from 'shellies-ng';
4 |
5 | export interface MdnsOptions {
6 | /**
7 | * Whether device discovery using mDNS should be enabled.
8 | */
9 | enable: boolean;
10 | /**
11 | * The network interface to use. If none is specified, all available
12 | * interfaces will be used.
13 | */
14 | interface?: string;
15 | }
16 |
17 | const DEFAULT_MDNS_OPTIONS: Readonly = {
18 | enable: true,
19 | };
20 |
21 | export interface WebSocketOptions {
22 | /**
23 | * The time, in seconds, to wait for a response before a request is aborted.
24 | */
25 | requestTimeout: number;
26 | /**
27 | * The interval, in seconds, at which ping requests should be made to verify that the connection is open.
28 | * Set to `0` to disable.
29 | */
30 | pingInterval: number;
31 | /**
32 | * The interval, in seconds, at which a connection attempt should be made after a socket has been closed.
33 | * If an array is specified, the first value of the array will be used for the first connection attempt, the second
34 | * value for the second attempt and so on. When the last item in the array has been reached, it will be used for
35 | * all subsequent connection attempts; unless the value is `0`, in which case no more attempts will be made.
36 | * Set to `0` or an empty array to disable.
37 | */
38 | reconnectInterval: number | number[];
39 | }
40 |
41 | const DEFAULT_WEB_SOCKET_OPTIONS: Readonly = {
42 | requestTimeout: 10,
43 | pingInterval: 60,
44 | reconnectInterval: [
45 | 5,
46 | 10,
47 | 30,
48 | 60,
49 | 5 * 60, // 5 minutes
50 | 10 * 60, // 10 minutes
51 | ],
52 | };
53 |
54 | export interface SwitchOptions {
55 | /**
56 | * Whether this switch should be excluded.
57 | */
58 | exclude?: boolean;
59 | /**
60 | * The type of accessory used to represent the switch.
61 | */
62 | type?: 'outlet' | 'switch';
63 | }
64 |
65 | export interface CoverOptions {
66 | /**
67 | * Whether this cover should be excluded.
68 | */
69 | exclude?: boolean;
70 | /**
71 | * The type of accessory used to represent the cover.
72 | */
73 | type?: 'door' | 'window' | 'windowCovering';
74 | }
75 |
76 | export interface DeviceOptions {
77 | /**
78 | * The name of the device.
79 | */
80 | name?: string;
81 | /**
82 | * Whether the device should be excluded.
83 | */
84 | exclude: boolean;
85 | /**
86 | * The protocol to use when communicating with the device.
87 | */
88 | protocol: 'websocket';
89 | /**
90 | * The IP address or hostname of the device.
91 | */
92 | hostname?: string;
93 | /**
94 | * The password to use if the Shelly device requires authentication.
95 | */
96 | password?: string;
97 | /**
98 | * Options for devices that have one or more switch.
99 | */
100 | [ 'switch:0' ]?: SwitchOptions;
101 | /**
102 | * Options for devices that have multiple switches.
103 | */
104 | [ 'switch:1' ]?: SwitchOptions;
105 | /**
106 | * Options for devices that have multiple switches.
107 | */
108 | [ 'switch:2' ]?: SwitchOptions;
109 | /**
110 | * Options for devices that have multiple switches.
111 | */
112 | [ 'switch:3' ]?: SwitchOptions;
113 | /**
114 | * Options for devices that have a cover.
115 | */
116 | [ 'cover:0' ]?: CoverOptions;
117 | }
118 |
119 | const DEFAULT_DEVICE_OPTIONS: Readonly = {
120 | exclude: false,
121 | protocol: 'websocket',
122 | };
123 |
124 | /**
125 | * Handles configuration options for the platform.
126 | */
127 | export class PlatformOptions {
128 | /**
129 | * Options for the mDNS device discoverer.
130 | */
131 | readonly mdns: MdnsOptions;
132 | /**
133 | * Options for WebSocket connections.
134 | */
135 | readonly websocket: WebSocketOptions;
136 | /**
137 | * Device specific configuration options.
138 | */
139 | readonly deviceOptions: Map = new Map();
140 |
141 | /**
142 | * @param config - The platform configuration.
143 | */
144 | constructor(config: PlatformConfig) {
145 | // store the mDNS options (with default values)
146 | this.mdns = { ...DEFAULT_MDNS_OPTIONS, ...config.mdns };
147 |
148 | // allow websocket.reconnectInterval to be a string of comma-separated numbers
149 | if (typeof config.websocket?.reconnectInterval === 'string') {
150 | const intervals: number[] = [];
151 |
152 | for (const i of config.websocket.reconnectInterval.split(',')) {
153 | intervals.push(parseInt(i, 10));
154 | }
155 |
156 | config.websocket.reconnectInterval = intervals;
157 | }
158 |
159 | // store the WebSocket options (with default values)
160 | this.websocket = { ...DEFAULT_WEB_SOCKET_OPTIONS, ...config.websocket };
161 |
162 | // store the device options
163 | if (Array.isArray(config.devices)) {
164 | // loop through each item and add default values
165 | for (const d of config.devices) {
166 | if (d && typeof d.id === 'string') {
167 | this.deviceOptions.set(d.id.toLowerCase(), { ...DEFAULT_DEVICE_OPTIONS, ...d });
168 | }
169 | }
170 | }
171 | }
172 |
173 | /**
174 | * Return the configuration options for the device with the given ID.
175 | * If no options have been specified, default values will be returned.
176 | * @param deviceId - The device ID.
177 | */
178 | getDeviceOptions(deviceId: DeviceId): DeviceOptions {
179 | return this.deviceOptions.get(deviceId) || DEFAULT_DEVICE_OPTIONS;
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/src/device-delegates/base.ts:
--------------------------------------------------------------------------------
1 | import { ComponentLike, Cover, Device, Switch } from 'shellies-ng';
2 | import { PlatformAccessory } from 'homebridge';
3 |
4 | import {
5 | Ability,
6 | AccessoryInformationAbility,
7 | CoverAbility,
8 | OutletAbility,
9 | PowerMeterAbility,
10 | SwitchAbility,
11 | } from '../abilities';
12 | import { Accessory, AccessoryId } from '../accessory';
13 | import { DeviceLogger } from '../utils/device-logger';
14 | import { CoverOptions, DeviceOptions, SwitchOptions } from '../config';
15 | import { ShellyPlatform } from '../platform';
16 |
17 | /**
18 | * Describes a device delegate class.
19 | */
20 | export interface DeviceDelegateClass {
21 | new (device: Device, options: DeviceOptions, platform: ShellyPlatform): DeviceDelegate;
22 | }
23 |
24 | /**
25 | * Describes a device class.
26 | */
27 | export interface DeviceClass {
28 | model: string;
29 | }
30 |
31 | export interface AddSwitchOptions {
32 | /**
33 | * Whether the accessory should be active.
34 | */
35 | active: boolean;
36 | /**
37 | * Whether the device has a single switch.
38 | */
39 | single: boolean;
40 | }
41 |
42 | export interface AddCoverOptions {
43 | /**
44 | * Whether the accessory should be active.
45 | */
46 | active: boolean;
47 | }
48 |
49 | /**
50 | * A DeviceDelegate manages accessories for a device.
51 | */
52 | export abstract class DeviceDelegate {
53 | /**
54 | * Holds all registered delegates.
55 | */
56 | private static readonly delegates: Map = new Map();
57 |
58 | /**
59 | * Registers a device delegate, so that it can later be found based on a device class or model
60 | * using the `DeviceDelegate.getDelegate()` method.
61 | * @param delegate - A subclass of `DeviceDelegate`.
62 | * @param deviceClasses - One or more subclasses of `Device`.
63 | */
64 | static registerDelegate(delegate: DeviceDelegateClass, ...deviceClasses: DeviceClass[]) {
65 | for (const deviceCls of deviceClasses) {
66 | const mdl = deviceCls.model.toUpperCase();
67 |
68 | // make sure it's not already registered
69 | if (DeviceDelegate.delegates.has(mdl)) {
70 | throw new Error(`A device delegate for ${deviceCls.model} has already been registered`);
71 | }
72 |
73 | // add it to the list
74 | DeviceDelegate.delegates.set(mdl, delegate);
75 | }
76 | }
77 |
78 | /**
79 | * Returns the device delegate for the given device class or model, if one has been registered.
80 | * @param deviceClsOrModel - The device class or model ID to lookup.
81 | */
82 | static getDelegate(deviceClsOrModel: DeviceClass | string): DeviceDelegateClass | undefined {
83 | const mdl = typeof deviceClsOrModel === 'string' ? deviceClsOrModel : deviceClsOrModel.model;
84 | return DeviceDelegate.delegates.get(mdl.toUpperCase());
85 | }
86 |
87 | /**
88 | * Holds all accessories for this device.
89 | */
90 | protected readonly accessories: Map = new Map();
91 |
92 | /**
93 | * Logger specific for this device.
94 | */
95 | readonly log: DeviceLogger;
96 |
97 | /**
98 | * Used to keep track of whether a connection had been established when the 'disconnect' event is emitted by our RPC handler.
99 | */
100 | protected connected: boolean;
101 |
102 | /**
103 | * @param device - The device to handle.
104 | * @param options - Configuration options for the device.
105 | * @param platform - A reference to the homebridge platform.
106 | */
107 | constructor(readonly device: Device, readonly options: DeviceOptions, readonly platform: ShellyPlatform) {
108 | this.log = new DeviceLogger(device, options.name, platform.log);
109 | this.log.info('Device added');
110 |
111 | this.log.debug(device.rpcHandler.connected ? 'Device is connected' : 'Device is disconnected');
112 |
113 | this.connected = device.rpcHandler.connected;
114 |
115 | device.rpcHandler
116 | .on('connect', this.handleConnect, this)
117 | .on('disconnect', this.handleDisconnect, this)
118 | .on('request', this.handleRequest, this);
119 |
120 | this.setup();
121 | }
122 |
123 | /**
124 | * Subclasses should override this method to setup the device delegate and create their
125 | * accessories.
126 | */
127 | protected abstract setup();
128 |
129 | /**
130 | * Retrieves configuration options for the given component from the device options.
131 | * @param component - The component.
132 | * @returns A set of options, if found.
133 | */
134 | protected getComponentOptions(component: ComponentLike): T | undefined {
135 | return this.options?.[component.key] as T;
136 | }
137 |
138 | /**
139 | * Creates an accessory with the given ID.
140 | * If a matching platform accessory is not found in cache, a new one will be created.
141 | * @param id - A unique identifier for this accessory.
142 | * @param nameSuffix - A string to append to the name of this accessory.
143 | * @param abilities - The abilities to add to this accessory.
144 | */
145 | protected createAccessory(id: AccessoryId, nameSuffix: string | null, ...abilities: Ability[]): Accessory {
146 | // make sure the given ID is unique
147 | if (this.accessories.has(id)) {
148 | throw new Error(`An accessory with ID '${id}' already exists`);
149 | }
150 |
151 | let name = this.options.name || this.device.modelName;
152 | if (nameSuffix) {
153 | name += ' ' + nameSuffix;
154 | }
155 |
156 | // create an accessory
157 | const accessory = new Accessory(
158 | id,
159 | this.device.id,
160 | name,
161 | this.platform,
162 | this.log,
163 | new AccessoryInformationAbility(this.device),
164 | ...abilities,
165 | );
166 |
167 | // store the accessory
168 | this.accessories.set(id, accessory);
169 |
170 | return accessory;
171 | }
172 |
173 | /**
174 | * Creates an accessory for a switch component.
175 | * @param swtch - The switch component to use.
176 | * @param opts - Options for the switch.
177 | */
178 | protected addSwitch(swtch: Switch, opts?: Partial): Accessory {
179 | const o = opts ?? {};
180 |
181 | // get the config options for this switch
182 | const switchOpts = this.getComponentOptions(swtch) ?? {};
183 |
184 | // determine the switch tyoe
185 | const type = typeof switchOpts.type === 'string' ? switchOpts.type.toLowerCase() : 'switch';
186 | const isOutlet = type === 'outlet';
187 |
188 | const id = o.single === true ? 'switch' : `switch-${swtch.id}`;
189 | const nameSuffix = o.single === true ? null : `Switch ${swtch.id + 1}`;
190 |
191 | return this.createAccessory(
192 | id,
193 | nameSuffix,
194 | new OutletAbility(swtch).setActive(isOutlet),
195 | new SwitchAbility(swtch).setActive(!isOutlet),
196 | // use the apower property to determine whether power metering is available
197 | new PowerMeterAbility(swtch).setActive(swtch.apower !== undefined),
198 | ).setActive(switchOpts.exclude !== true && o.active !== false);
199 | }
200 |
201 | /**
202 | * Creates an accessory for a cover component.
203 | * @param cover - The cover component to use.
204 | * @param opts - Options for the cover.
205 | */
206 | protected addCover(cover: Cover, opts?: Partial): Accessory {
207 | const o = opts ?? {};
208 |
209 | // get the config options for this cover
210 | const coverOpts = this.getComponentOptions(cover) ?? {};
211 |
212 | // determine the cover tyoe
213 | const type = typeof coverOpts.type === 'string' ? coverOpts.type.toLowerCase() : 'window';
214 | const isDoor = type === 'door';
215 | const isWindowCovering = type === 'windowcovering';
216 |
217 | return this.createAccessory(
218 | 'cover',
219 | 'Cover',
220 | new CoverAbility(cover, 'door').setActive(isDoor),
221 | new CoverAbility(cover, 'windowCovering').setActive(isWindowCovering),
222 | new CoverAbility(cover, 'window').setActive(!isDoor && !isWindowCovering),
223 | new PowerMeterAbility(cover),
224 | ).setActive(coverOpts.exclude !== true && o.active !== false);
225 | }
226 |
227 | /**
228 | * Handles 'connect' events from the RPC handler.
229 | */
230 | protected handleConnect() {
231 | this.log.info('Device connected');
232 | this.connected = true;
233 | }
234 |
235 | /**
236 | * Handles 'disconnect' events from the RPC handler.
237 | */
238 | protected handleDisconnect(code: number, reason: string, reconnectIn: number | null) {
239 | const details = reason.length > 0 ? 'reason: ' + reason : 'code: ' + code;
240 | this.log.warn((this.connected ? 'Device disconnected' : 'Connection failed') + ' (' + details + ')');
241 |
242 | if (reconnectIn !== null) {
243 | let msg = 'Reconnecting in ';
244 |
245 | if (reconnectIn < 60 * 1000) {
246 | msg += Math.floor(reconnectIn / 1000) + ' second(s)';
247 | } else if (reconnectIn < 60 * 60 * 1000) {
248 | msg += Math.floor(reconnectIn / (60 * 1000)) + ' minute(s)';
249 | } else {
250 | msg += Math.floor(reconnectIn / (60 * 60 * 1000)) + ' hour(s)';
251 | }
252 |
253 | this.log.info(msg);
254 | }
255 |
256 | this.connected = false;
257 | }
258 |
259 | /**
260 | * Handles 'request' events from the RPC handler.
261 | */
262 | protected handleRequest(method: string) {
263 | this.log.debug('WebSocket:', method);
264 | }
265 |
266 | /**
267 | * Removes all event listeners from this device.
268 | */
269 | detach() {
270 | this.device.rpcHandler
271 | .off('connect', this.handleConnect, this)
272 | .off('disconnect', this.handleDisconnect, this)
273 | .off('request', this.handleRequest, this);
274 |
275 | // invoke detach() on all accessories
276 | for (const a of this.accessories.values()) {
277 | a.detach();
278 | }
279 | }
280 |
281 | /**
282 | * Destroys this device delegate, removing all event listeners and unregistering all accessories.
283 | */
284 | destroy() {
285 | this.detach();
286 |
287 | // find all platform accessories
288 | const pas = Array.from(this.accessories.values())
289 | .map(a => a.platformAccessory)
290 | .filter(a => a !== null) as PlatformAccessory[];
291 |
292 | if (pas.length > 0) {
293 | // remove the accessories from the platform
294 | this.platform.removeAccessory(...pas);
295 | }
296 |
297 | this.log.info('Device removed');
298 | }
299 | }
300 |
--------------------------------------------------------------------------------
/src/device-delegates/index.ts:
--------------------------------------------------------------------------------
1 | export * from './base';
2 |
3 | export * from './shelly-plus-1';
4 | export * from './shelly-plus-1-pm';
5 | export * from './shelly-plus-2-pm';
6 | export * from './shelly-plus-i4';
7 | export * from './shelly-plus-plug-us';
8 | export * from './shelly-pro-1';
9 | export * from './shelly-pro-1-pm';
10 | export * from './shelly-pro-2';
11 | export * from './shelly-pro-3';
12 | export * from './shelly-pro-2-pm';
13 | export * from './shelly-pro-4-pm';
14 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-plus-1-pm.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPlus1Pm,
3 | ShellyPlus1PmUl,
4 | } from 'shellies-ng';
5 |
6 | import { DeviceDelegate } from './base';
7 |
8 | /**
9 | * Handles Shelly Plus 1PM devices.
10 | */
11 | export class ShellyPlus1PmDelegate extends DeviceDelegate {
12 | protected setup() {
13 | const d = this.device as ShellyPlus1Pm;
14 |
15 | this.addSwitch(d.switch0, { single: true });
16 | }
17 | }
18 |
19 | DeviceDelegate.registerDelegate(
20 | ShellyPlus1PmDelegate,
21 | ShellyPlus1Pm,
22 | ShellyPlus1PmUl,
23 | );
24 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-plus-1.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPlus1,
3 | ShellyPlus1Ul,
4 | } from 'shellies-ng';
5 |
6 | import { DeviceDelegate } from './base';
7 |
8 | /**
9 | * Handles Shelly Plus 1 devices.
10 | */
11 | export class ShellyPlus1Delegate extends DeviceDelegate {
12 | protected setup() {
13 | const d = this.device as ShellyPlus1;
14 |
15 | this.addSwitch(d.switch0, { single: true });
16 | }
17 | }
18 |
19 | DeviceDelegate.registerDelegate(
20 | ShellyPlus1Delegate,
21 | ShellyPlus1,
22 | ShellyPlus1Ul,
23 | );
24 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-plus-2-pm.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPlus2Pm,
3 | ShellyPlus2PmRev1,
4 | } from 'shellies-ng';
5 |
6 | import { DeviceDelegate } from './base';
7 |
8 | /**
9 | * Handles Shelly Plus 2 PM devices.
10 | */
11 | export class ShellyPlus2PmDelegate extends DeviceDelegate {
12 | protected setup() {
13 | const d = this.device as ShellyPlus2Pm;
14 | const isCover = d.profile === 'cover';
15 |
16 | this.addCover(d.cover0, { active: isCover });
17 |
18 | this.addSwitch(d.switch0, { active: !isCover });
19 | this.addSwitch(d.switch1, { active: !isCover });
20 | }
21 | }
22 |
23 | DeviceDelegate.registerDelegate(
24 | ShellyPlus2PmDelegate,
25 | ShellyPlus2Pm,
26 | ShellyPlus2PmRev1,
27 | );
28 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-plus-i4.ts:
--------------------------------------------------------------------------------
1 | import { ShellyPlusI4 } from 'shellies-ng';
2 |
3 | import { DeviceDelegate } from './base';
4 | import {
5 | ReadonlySwitchAbility,
6 | ServiceLabelAbility,
7 | StatelessProgrammableSwitchAbility,
8 | } from '../abilities';
9 |
10 | /**
11 | * Handles Shelly Plus I4 devices.
12 | */
13 | export class ShellyPlusI4Delegate extends DeviceDelegate {
14 | protected setup() {
15 | const d = this.device as ShellyPlusI4;
16 |
17 | // determine each input type
18 | const input0IsButton = d.input0.config?.type === 'button';
19 | const input1IsButton = d.input1.config?.type === 'button';
20 | const input2IsButton = d.input2.config?.type === 'button';
21 | const input3IsButton = d.input3.config?.type === 'button';
22 |
23 | // create an accessory for all button inputs
24 | this.createAccessory(
25 | 'buttons',
26 | null,
27 | new StatelessProgrammableSwitchAbility(d.input0).setActive(input0IsButton),
28 | new StatelessProgrammableSwitchAbility(d.input1).setActive(input1IsButton),
29 | new StatelessProgrammableSwitchAbility(d.input2).setActive(input2IsButton),
30 | new StatelessProgrammableSwitchAbility(d.input3).setActive(input3IsButton),
31 | new ServiceLabelAbility(),
32 | ).setActive(input0IsButton || input1IsButton || input2IsButton || input3IsButton);
33 |
34 | // create accessories for all switch inputs
35 | this.createAccessory('switch0', null, new ReadonlySwitchAbility(d.input0)).setActive(!input0IsButton);
36 | this.createAccessory('switch1', null, new ReadonlySwitchAbility(d.input1)).setActive(!input1IsButton);
37 | this.createAccessory('switch2', null, new ReadonlySwitchAbility(d.input2)).setActive(!input2IsButton);
38 | this.createAccessory('switch3', null, new ReadonlySwitchAbility(d.input3)).setActive(!input3IsButton);
39 | }
40 | }
41 |
42 | DeviceDelegate.registerDelegate(ShellyPlusI4Delegate, ShellyPlusI4);
43 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-plus-plug-us.ts:
--------------------------------------------------------------------------------
1 | import { ShellyPlusPlugUs } from 'shellies-ng';
2 |
3 | import { DeviceDelegate } from './base';
4 |
5 | /**
6 | * Handles Shelly Plus Plug US devices.
7 | */
8 | export class ShellyPlusPlugUsDelegate extends DeviceDelegate {
9 | protected setup() {
10 | const d = this.device as ShellyPlusPlugUs;
11 |
12 | this.addSwitch(d.switch0, { single: true });
13 | }
14 | }
15 |
16 | DeviceDelegate.registerDelegate(ShellyPlusPlugUsDelegate, ShellyPlusPlugUs);
17 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-1-pm.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPro1Pm,
3 | ShellyPro1PmRev1,
4 | ShellyPro1PmRev2,
5 | } from 'shellies-ng';
6 |
7 | import { DeviceDelegate } from './base';
8 |
9 | /**
10 | * Handles Shelly Pro 1 PM devices.
11 | */
12 | export class ShellyPro1PmDelegate extends DeviceDelegate {
13 | protected setup() {
14 | const d = this.device as ShellyPro1Pm;
15 |
16 | this.addSwitch(d.switch0, { single: true });
17 | }
18 | }
19 |
20 | DeviceDelegate.registerDelegate(
21 | ShellyPro1PmDelegate,
22 | ShellyPro1Pm,
23 | ShellyPro1PmRev1,
24 | ShellyPro1PmRev2,
25 | );
26 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-1.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPro1,
3 | ShellyPro1Rev1,
4 | ShellyPro1Rev2,
5 | } from 'shellies-ng';
6 |
7 | import { DeviceDelegate } from './base';
8 |
9 | /**
10 | * Handles Shelly Pro 1 devices.
11 | */
12 | export class ShellyPro1Delegate extends DeviceDelegate {
13 | protected setup() {
14 | const d = this.device as ShellyPro1;
15 |
16 | this.addSwitch(d.switch0, { single: true });
17 | }
18 | }
19 |
20 | DeviceDelegate.registerDelegate(
21 | ShellyPro1Delegate,
22 | ShellyPro1,
23 | ShellyPro1Rev1,
24 | ShellyPro1Rev2,
25 | );
26 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-2-pm.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPro2Pm,
3 | ShellyPro2PmRev1,
4 | ShellyPro2PmRev2,
5 | } from 'shellies-ng';
6 |
7 | import { DeviceDelegate } from './base';
8 |
9 | /**
10 | * Handles Shelly Pro 2 PM devices.
11 | */
12 | export class ShellyPro2PmDelegate extends DeviceDelegate {
13 | protected setup() {
14 | const d = this.device as ShellyPro2Pm;
15 | const isCover = d.profile === 'cover';
16 |
17 | this.addCover(d.cover0, { active: isCover });
18 |
19 | this.addSwitch(d.switch0, { active: !isCover });
20 | this.addSwitch(d.switch1, { active: !isCover });
21 | }
22 | }
23 |
24 | DeviceDelegate.registerDelegate(
25 | ShellyPro2PmDelegate,
26 | ShellyPro2Pm,
27 | ShellyPro2PmRev1,
28 | ShellyPro2PmRev2,
29 | );
30 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-2.ts:
--------------------------------------------------------------------------------
1 | import {
2 | ShellyPro2,
3 | ShellyPro2Rev1,
4 | ShellyPro2Rev2,
5 | } from 'shellies-ng';
6 |
7 | import { DeviceDelegate } from './base';
8 |
9 | /**
10 | * Handles Shelly Pro 2 devices.
11 | */
12 | export class ShellyPro2Delegate extends DeviceDelegate {
13 | protected setup() {
14 | const d = this.device as ShellyPro2;
15 |
16 | this.addSwitch(d.switch0);
17 | this.addSwitch(d.switch1);
18 | }
19 | }
20 |
21 | DeviceDelegate.registerDelegate(
22 | ShellyPro2Delegate,
23 | ShellyPro2,
24 | ShellyPro2Rev1,
25 | ShellyPro2Rev2,
26 | );
27 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-3.ts:
--------------------------------------------------------------------------------
1 | import { ShellyPro3 } from 'shellies-ng';
2 |
3 | import { DeviceDelegate } from './base';
4 |
5 | /**
6 | * Handles Shelly Pro 3 devices.
7 | */
8 | export class ShellyPro3Delegate extends DeviceDelegate {
9 | protected setup() {
10 | const d = this.device as ShellyPro3;
11 |
12 | this.addSwitch(d.switch0);
13 | this.addSwitch(d.switch1);
14 | this.addSwitch(d.switch2);
15 | }
16 | }
17 |
18 | DeviceDelegate.registerDelegate(ShellyPro3Delegate, ShellyPro3);
19 |
--------------------------------------------------------------------------------
/src/device-delegates/shelly-pro-4-pm.ts:
--------------------------------------------------------------------------------
1 | import { ShellyPro4Pm } from 'shellies-ng';
2 |
3 | import { DeviceDelegate } from './base';
4 |
5 | /**
6 | * Handles Shelly Pro 4PM devices.
7 | */
8 | export class ShellyPro4PmDelegate extends DeviceDelegate {
9 | protected setup() {
10 | const d = this.device as ShellyPro4Pm;
11 |
12 | this.addSwitch(d.switch0);
13 | this.addSwitch(d.switch1);
14 | this.addSwitch(d.switch2);
15 | this.addSwitch(d.switch3);
16 | }
17 | }
18 |
19 | DeviceDelegate.registerDelegate(ShellyPro4PmDelegate, ShellyPro4Pm);
20 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import { API } from 'homebridge';
2 |
3 | import { PLATFORM_NAME, ShellyPlatform } from './platform';
4 |
5 | export = (api: API) => {
6 | api.registerPlatform(PLATFORM_NAME, ShellyPlatform);
7 | };
8 |
--------------------------------------------------------------------------------
/src/platform.ts:
--------------------------------------------------------------------------------
1 | import {
2 | API,
3 | DynamicPlatformPlugin,
4 | Logger,
5 | PlatformAccessory,
6 | PlatformConfig,
7 | } from 'homebridge';
8 |
9 | import {
10 | Device,
11 | DeviceDiscoverer,
12 | DeviceId,
13 | DeviceIdentifiers,
14 | MdnsDeviceDiscoverer,
15 | Shellies,
16 | } from 'shellies-ng';
17 |
18 | import { CustomCharacteristics, createCharacteristics } from './utils/characteristics';
19 | import { CustomServices, createServices } from './utils/services';
20 | import { DeviceCache } from './utils/device-cache';
21 | import { DeviceDelegate } from './device-delegates';
22 | import { PlatformOptions } from './config';
23 |
24 | type AccessoryUuid = string;
25 |
26 | /**
27 | * The name of this plugin.
28 | */
29 | export const PLUGIN_NAME = 'homebridge-shelly-ng';
30 |
31 | /**
32 | * The name of this homebridge platform.
33 | */
34 | export const PLATFORM_NAME = 'ShellyNG';
35 |
36 | /**
37 | * Utility class that "discovers" devices from the configuration options.
38 | */
39 | export class ConfigDeviceDiscoverer extends DeviceDiscoverer {
40 | /**
41 | * @param options - The platform configuration options.
42 | * @param emitInterval - The interval, in milliseconds, to wait between each emitted device.
43 | */
44 | constructor(readonly options: PlatformOptions, readonly emitInterval = 20) {
45 | super();
46 | }
47 |
48 | /**
49 | * Runs this discoverer.
50 | */
51 | async run() {
52 | // emit all devices that have a configured hostname
53 | for (const [id, opts] of this.options.deviceOptions) {
54 | if (opts.hostname) {
55 | await this.emitDevice({
56 | deviceId: id,
57 | hostname: opts.hostname,
58 | });
59 | }
60 | }
61 | }
62 |
63 | /**
64 | * Emits a device after the configured time interval has passed.
65 | */
66 | protected emitDevice(identifiers: DeviceIdentifiers): Promise {
67 | return new Promise((resolve) => {
68 | setTimeout(() => {
69 | this.handleDiscoveredDevice(identifiers);
70 | resolve();
71 | }, this.emitInterval);
72 | });
73 | }
74 | }
75 |
76 | /**
77 | * Utility class that "discovers" devices from a cache.
78 | */
79 | export class CacheDeviceDiscoverer extends DeviceDiscoverer {
80 | /**
81 | * @param deviceCache - The cached devices.
82 | * @param emitInterval - The interval, in milliseconds, to wait between each emitted device.
83 | */
84 | constructor(readonly deviceCache: DeviceCache, readonly emitInterval = 20) {
85 | super();
86 | }
87 |
88 | /**
89 | * Runs this discoverer.
90 | */
91 | async run() {
92 | // emit all cached devices
93 | for (const d of this.deviceCache) {
94 | await this.emitDevice({
95 | deviceId: d.id,
96 | hostname: d.hostname,
97 | });
98 | }
99 | }
100 |
101 | /**
102 | * Emits a device after the configured time interval has passed.
103 | */
104 | protected emitDevice(identifiers: DeviceIdentifiers): Promise {
105 | return new Promise((resolve) => {
106 | setTimeout(() => {
107 | this.handleDiscoveredDevice(identifiers);
108 | resolve();
109 | }, this.emitInterval);
110 | });
111 | }
112 | }
113 |
114 | /**
115 | * Implements a homebridge dynamic platform plugin.
116 | */
117 | export class ShellyPlatform implements DynamicPlatformPlugin {
118 | /**
119 | * The configuration options for this platform.
120 | */
121 | readonly options: PlatformOptions;
122 |
123 | /**
124 | * A set of custom HomeKit characteristics.
125 | */
126 | readonly customCharacteristics: CustomCharacteristics;
127 |
128 | /**
129 | * A set of custom HomeKit services.
130 | */
131 | readonly customServices: CustomServices;
132 |
133 | /**
134 | * A reference to the shellies-ng library.
135 | */
136 | protected readonly shellies: Shellies;
137 |
138 | /**
139 | * Holds all platform accessories that were loaded from cache during launch,
140 | * as well as accessories that have been created since launch.
141 | */
142 | protected readonly accessories: Map = new Map();
143 |
144 | /**
145 | * A reference to our cached devices.
146 | */
147 | readonly deviceCache: DeviceCache;
148 |
149 | /**
150 | * Holds all device delegates.
151 | */
152 | readonly deviceDelegates: Map = new Map();
153 |
154 | /**
155 | * This constructor is invoked by homebridge.
156 | * @param log - A logging device for this platform.
157 | * @param config - Configuration options for this platform.
158 | * @param api - A reference to the homebridge API.
159 | */
160 | constructor(
161 | readonly log: Logger,
162 | config: PlatformConfig,
163 | readonly api: API,
164 | ) {
165 | // get the platform options
166 | this.options = new PlatformOptions(config);
167 |
168 | this.customCharacteristics = Object.freeze(createCharacteristics(api));
169 | this.customServices = Object.freeze(createServices(api, this.customCharacteristics));
170 |
171 | // setup shellies-ng
172 | this.shellies = new Shellies({
173 | websocket: { ...this.options.websocket, clientId: 'homebridge-shelly-ng-' + Math.round(Math.random() * 1000000) },
174 | autoLoadStatus: true,
175 | autoLoadConfig: true,
176 | deviceOptions: this.options.deviceOptions,
177 | });
178 | this.shellies
179 | .on('add', this.handleAddedDevice, this)
180 | .on('remove', this.handleRemovedDevice, this)
181 | .on('exclude', this.handleExcludedDevice, this)
182 | .on('unknown', this.handleUnknownDevice, this)
183 | .on('error', this.handleError, this);
184 |
185 | this.deviceCache = new DeviceCache(api.user.storagePath(), log);
186 |
187 | // wait for homebridge to finish launching
188 | api.on('didFinishLaunching', this.initialize.bind(this));
189 | }
190 |
191 | /**
192 | * Configures cached accessories.
193 | * This method is invoked once for each cached accessory that is loaded during launch.
194 | */
195 | configureAccessory(accessory: PlatformAccessory) {
196 | // store it for later
197 | this.accessories.set(accessory.UUID, accessory);
198 | }
199 |
200 | /**
201 | * Returns the platform accessory with the given UUID.
202 | * @param uuid - The UUID.
203 | */
204 | getAccessory(uuid: AccessoryUuid): PlatformAccessory | undefined {
205 | return this.accessories.get(uuid);
206 | }
207 |
208 | /**
209 | * Adds one or more platform accessories to this platform.
210 | * This method will also register the accessories with homebridge.
211 | * @param accessories - The platform accessories to add.
212 | */
213 | addAccessory(...accessories: PlatformAccessory[]) {
214 | if (accessories.length === 0) {
215 | return;
216 | }
217 |
218 | const accs: PlatformAccessory[] = [];
219 |
220 | // add the accessories to our list
221 | for (const pa of accessories) {
222 | // skip if this accessory has already been added
223 | if (this.accessories.has(pa.UUID)) {
224 | continue;
225 | }
226 |
227 | this.accessories.set(pa.UUID, pa);
228 | accs.push(pa);
229 | }
230 |
231 | // register the accessories with homebridge
232 | this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accs);
233 | }
234 |
235 | /**
236 | * Removes one or more platform accessories from this platform.
237 | * This method will also unregister the accessories from homebridge.
238 | * @param accessories - The platform accessories to remove.
239 | */
240 | removeAccessory(...accessories: PlatformAccessory[]) {
241 | if (accessories.length === 0) {
242 | return;
243 | }
244 |
245 | // remove the accessories from our list
246 | for (const pa of accessories) {
247 | this.accessories.delete(pa.UUID);
248 | }
249 |
250 | // unregister the accessories from homebridge
251 | this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessories);
252 | }
253 |
254 | /**
255 | * Initializes this platform.
256 | */
257 | protected async initialize() {
258 | this.log.debug(
259 | this.accessories.size === 1
260 | ? 'Loaded 1 accessory from cache'
261 | : `Loaded ${this.accessories.size} accessories from cache`,
262 | );
263 |
264 | await this.runConfigDeviceDiscoverer();
265 |
266 | // load cached devices
267 | try {
268 | await this.deviceCache.load();
269 | } catch (e) {
270 | this.log.error(
271 | 'Failed to load cached devices:',
272 | e instanceof Error ? e.message : e,
273 | );
274 | }
275 |
276 | await this.runCacheDeviceDiscoverer();
277 |
278 | if (this.options.mdns.enable === true) {
279 | this.startMdnsDeviceDiscovery();
280 | } else {
281 | this.log.debug('mDNS device discovery disabled');
282 | }
283 | }
284 |
285 | /**
286 | * Discovers all devices found in the configuration.
287 | */
288 | protected runConfigDeviceDiscoverer(): Promise {
289 | // create a device discoverer
290 | const discoverer = new ConfigDeviceDiscoverer(this.options);
291 | // register it
292 | this.shellies.registerDiscoverer(discoverer);
293 | // run it
294 | return discoverer.run();
295 | }
296 |
297 | /**
298 | * Discovers all devices found in cache.
299 | */
300 | protected runCacheDeviceDiscoverer(): Promise {
301 | // create a device discoverer
302 | const discoverer = new CacheDeviceDiscoverer(this.deviceCache);
303 | // register it
304 | this.shellies.registerDiscoverer(discoverer);
305 | // run it
306 | return discoverer.run();
307 | }
308 |
309 | /**
310 | * Starts device discovery over mDNS.
311 | */
312 | protected async startMdnsDeviceDiscovery() {
313 | // create a device discoverer
314 | const discoverer = new MdnsDeviceDiscoverer(this.options.mdns);
315 | // register it
316 | this.shellies.registerDiscoverer(discoverer);
317 |
318 | // log errors
319 | discoverer.on('error', (error: Error) => {
320 | this.log.error('An error occurred in the mDNS device discovery service:', error.message);
321 | this.log.debug(error.stack || '');
322 | });
323 |
324 | try {
325 | // start the service
326 | await discoverer.start();
327 |
328 | this.log.info('mDNS device discovery started');
329 | } catch (e) {
330 | this.log.error('Failed to start the mDNS device discovery service:', e instanceof Error ? e.message : e);
331 | if (e instanceof Error && e.stack) {
332 | this.log.debug(e.stack);
333 | }
334 | }
335 | }
336 |
337 | /**
338 | * Handles 'add' events from the shellies-ng library.
339 | */
340 | protected async handleAddedDevice(device: Device) {
341 | // make sure this device hasn't already been added
342 | if (this.deviceDelegates.has(device.id)) {
343 | this.log.error(`Device with ID ${device.id} has already been added`);
344 | return;
345 | }
346 |
347 | // get the device delegate class for this device
348 | const cls = DeviceDelegate.getDelegate(device.model);
349 | if (cls === undefined) {
350 | // this is an unknown device
351 | this.handleUnknownDevice(device.id, device.model);
352 | return;
353 | }
354 |
355 | // get the configuration options for this device (and copy them)
356 | const opts = { ...this.options.getDeviceOptions(device.id) };
357 |
358 | // if no name has been specified...
359 | if (!opts.name) {
360 | // use the name from the API
361 | opts.name = device.system.config?.device?.name;
362 | }
363 |
364 | // create a delegate for this device
365 | const delegate = new cls(device, opts, this);
366 |
367 | // store the delegate
368 | this.deviceDelegates.set(device.id, delegate);
369 |
370 | // store info about this device in cache
371 | this.deviceCache.storeDevice(device);
372 | }
373 |
374 | /**
375 | * Handles 'remove' events from the shellies-ng library.
376 | */
377 | protected handleRemovedDevice(device: Device) {
378 | // destroy and remove the device delegate
379 | this.deviceDelegates.get(device.id)?.destroy();
380 | this.deviceDelegates.delete(device.id);
381 |
382 | // delete this device from cache
383 | this.deviceCache.delete(device.id);
384 | }
385 |
386 | /**
387 | * Handles 'exclude' events from the shellies-ng library.
388 | */
389 | protected handleExcludedDevice(deviceId: DeviceId) {
390 | this.log.info(`[${deviceId}] Device excluded`);
391 |
392 | // delete this device from cache
393 | this.deviceCache.delete(deviceId);
394 |
395 | if (this.deviceDelegates.has(deviceId)) {
396 | // destroy and remove the device delegate
397 | this.deviceDelegates.get(deviceId)!.destroy();
398 | this.deviceDelegates.delete(deviceId);
399 | } else {
400 | // find all of its platform accessories
401 | const pas: PlatformAccessory[] = [];
402 |
403 | for (const pa of this.accessories.values()) {
404 | if (pa.context.device?.id === deviceId) {
405 | pas.push(pa);
406 | }
407 | }
408 |
409 | // unregister them
410 | if (pas.length > 0) {
411 | this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, pas);
412 | }
413 |
414 | this.log.debug(
415 | pas.length === 1
416 | ? '1 platform accessory unregistered'
417 | : `${pas.length} platform accessories unregistered`,
418 | );
419 | }
420 | }
421 |
422 | /**
423 | * Handles 'unknown' events from the shellies-ng library.
424 | */
425 | protected handleUnknownDevice(deviceId: DeviceId, model: string) {
426 | this.log.info(`[${deviceId}] Unknown device of model "${model}" discovered.`);
427 | }
428 |
429 | /**
430 | * Handles 'error' events from the shellies-ng library.
431 | */
432 | protected handleError(deviceId: DeviceId, error: Error) {
433 | // print the error to the log
434 | this.log.error(error.message);
435 | this.log.debug(error.stack || '');
436 | }
437 | }
438 |
--------------------------------------------------------------------------------
/src/utils/characteristics.ts:
--------------------------------------------------------------------------------
1 | import { API, Characteristic, WithUUID } from 'homebridge';
2 |
3 | type C = WithUUID Characteristic> & WithUUID;
4 |
5 | export interface CustomCharacteristics {
6 | CurrentConsumption: C;
7 | ElectricCurrent: C;
8 | TotalConsumption: C;
9 | Voltage: C;
10 | }
11 |
12 | /**
13 | * Returns a set of custom HomeKit characteristics.
14 | * @param api - A reference to the homebridge API.
15 | */
16 | export const createCharacteristics = (api: API): CustomCharacteristics => {
17 | /**
18 | * Current energy consumption, in watts.
19 | */
20 | class CurrentConsumption extends api.hap.Characteristic {
21 | static readonly UUID = 'E863F10D-079E-48FF-8F27-9C2605A29F52';
22 |
23 | constructor() {
24 | super('Current Consumption', CurrentConsumption.UUID, {
25 | format: api.hap.Formats.FLOAT,
26 | perms: [api.hap.Perms.NOTIFY, api.hap.Perms.READ],
27 | unit: 'W',
28 | minValue: 0,
29 | maxValue: 12000,
30 | minStep: 0.1,
31 | });
32 | }
33 | }
34 |
35 | /**
36 | * Current measured electric current, in amperes.
37 | */
38 | class ElectricCurrent extends api.hap.Characteristic {
39 | static readonly UUID = 'E863F126-079E-48FF-8F27-9C2605A29F52';
40 |
41 | constructor() {
42 | super('Electric Current', ElectricCurrent.UUID, {
43 | format: api.hap.Formats.FLOAT,
44 | perms: [api.hap.Perms.NOTIFY, api.hap.Perms.READ],
45 | unit: 'A',
46 | minValue: 0,
47 | maxValue: 48,
48 | minStep: 0.1,
49 | });
50 | }
51 | }
52 |
53 | /**
54 | * Total energy consumption, in kilowatt hours.
55 | */
56 | class TotalConsumption extends api.hap.Characteristic {
57 | static readonly UUID = 'E863F10C-079E-48FF-8F27-9C2605A29F52';
58 |
59 | constructor() {
60 | super('Total Consumption', TotalConsumption.UUID, {
61 | format: api.hap.Formats.FLOAT,
62 | perms: [api.hap.Perms.NOTIFY, api.hap.Perms.READ],
63 | unit: 'kWh',
64 | minValue: 0,
65 | maxValue: 1000000,
66 | minStep: 0.1,
67 | });
68 | }
69 | }
70 |
71 | /**
72 | * Current measured voltage, in volts.
73 | */
74 | class Voltage extends api.hap.Characteristic {
75 | static readonly UUID = 'E863F10A-079E-48FF-8F27-9C2605A29F52';
76 |
77 | constructor() {
78 | super('Voltage', Voltage.UUID, {
79 | format: api.hap.Formats.FLOAT,
80 | perms: [api.hap.Perms.NOTIFY, api.hap.Perms.READ],
81 | unit: 'V',
82 | minValue: -1000,
83 | maxValue: 1000,
84 | minStep: 0.1,
85 | });
86 | }
87 | }
88 |
89 | return {
90 | CurrentConsumption,
91 | ElectricCurrent,
92 | TotalConsumption,
93 | Voltage,
94 | };
95 | };
96 |
--------------------------------------------------------------------------------
/src/utils/device-cache.ts:
--------------------------------------------------------------------------------
1 | import { Logger } from 'homebridge';
2 | import { promises as fs } from 'fs';
3 | import { resolve } from 'path';
4 |
5 | import { Device, DeviceId, WebSocketRpcHandler } from 'shellies-ng';
6 |
7 | const FILENAME = '.shelly-ng.json';
8 |
9 | const SAVE_DELAY = 1000;
10 |
11 | export interface CachedDeviceInfo {
12 | /**
13 | * Device ID.
14 | */
15 | id: DeviceId;
16 | /**
17 | * Device model.
18 | */
19 | model: string;
20 | /**
21 | * RPC handler protocol.
22 | */
23 | protocol: string;
24 | /**
25 | * The device's IP address or hostname.
26 | */
27 | hostname?: string;
28 | }
29 |
30 | export interface DeviceStorage {
31 | devices: CachedDeviceInfo[];
32 | }
33 |
34 | /**
35 | * Handles saving and loading device information to a cache file.
36 | */
37 | export class DeviceCache {
38 | /**
39 | * A path to the cache file.
40 | */
41 | readonly path: string;
42 |
43 | /**
44 | * Holds all devices loaded from the cache file.
45 | */
46 | protected devices = new Map();
47 |
48 | private saveTimeout: ReturnType | null = null;
49 |
50 | /**
51 | * @param storagePath - A path to the directory that the devices will be stored in.
52 | * @param log - A logging device.
53 | */
54 | constructor(storagePath: string, readonly log: Logger) {
55 | this.path = resolve(storagePath, FILENAME);
56 | }
57 |
58 | /**
59 | * Loads cached devices.
60 | */
61 | async load() {
62 | // remove any previously loaded devices
63 | this.devices.clear();
64 |
65 | try {
66 | // see if the cache file exists
67 | await fs.access(this.path);
68 | } catch (_) {
69 | // the file doesn't exist
70 | this.log.debug('Device cache file not found');
71 | return;
72 | }
73 |
74 | // read the file
75 | const data: string = await fs.readFile(this.path, { encoding: 'utf8' });
76 | const s = JSON.parse(data) as DeviceStorage;
77 |
78 | this.log.debug(`Loaded ${s.devices.length} device(s) from cache`);
79 |
80 | // store the loaded devices
81 | for (const d of s.devices) {
82 | this.devices.set(d.id, d);
83 | }
84 | }
85 |
86 | /**
87 | * Saves the devices to cache.
88 | */
89 | async save() {
90 | // serialize the devices
91 | const s = { devices: Array.from(this.devices.values()) };
92 | const data = JSON.stringify(s);
93 |
94 | this.log.debug(`Saving ${s.devices.length} device(s) to cache`);
95 |
96 | // write them to disk
97 | return fs.writeFile(this.path, data);
98 | }
99 |
100 | /**
101 | * Saves the devices to cache after a short delay.
102 | * Multiple calls to this method within the delay will be debounced.
103 | */
104 | saveDelayed() {
105 | // clear any previously set timeout
106 | if (this.saveTimeout !== null) {
107 | clearTimeout(this.saveTimeout);
108 | }
109 |
110 | this.saveTimeout = setTimeout(async () => {
111 | this.saveTimeout = null;
112 |
113 | try {
114 | await this.save();
115 | } catch (e) {
116 | this.log.error(
117 | 'Failed to save devices to cache:',
118 | e instanceof Error ? e.message : e,
119 | );
120 | }
121 | }, SAVE_DELAY);
122 | }
123 |
124 | /**
125 | * Returns device info for the given device ID.
126 | */
127 | get(id: DeviceId): CachedDeviceInfo | undefined {
128 | return this.devices.get(id);
129 | }
130 |
131 | /**
132 | * Stores the given device info.
133 | * @param d - The device info.
134 | * @param autoSave - Whether `saveDelayed()` should be automatically invoked.
135 | */
136 | set(d: CachedDeviceInfo, autoSave = true) {
137 | this.devices.set(d.id, d);
138 |
139 | if (autoSave === true) {
140 | this.saveDelayed();
141 | }
142 | }
143 |
144 | /**
145 | * Stores info about the given device in cache.
146 | * @param device - The device.
147 | * @param autoSave - Whether `saveDelayed()` should be automatically invoked.
148 | */
149 | storeDevice(device: Device, autoSave = true) {
150 | const protocol = device.rpcHandler.protocol;
151 | let hostname;
152 |
153 | if (protocol === 'websocket') {
154 | hostname = (device.rpcHandler as WebSocketRpcHandler).hostname;
155 | }
156 |
157 | this.set(
158 | {
159 | id: device.id,
160 | model: device.model,
161 | protocol,
162 | hostname,
163 | },
164 | autoSave,
165 | );
166 | }
167 |
168 | /**
169 | * Deletes info about the device with the given ID from cache.
170 | * @param id - The device ID.
171 | * @param autoSave - Whether `saveDelayed()` should be automatically invoked.
172 | */
173 | delete(id: DeviceId, autoSave = true) {
174 | this.devices.delete(id);
175 |
176 | if (autoSave === true) {
177 | this.saveDelayed();
178 | }
179 | }
180 |
181 | /**
182 | * Returns a new Iterator object that contains each device.
183 | */
184 | [Symbol.iterator](): IterableIterator {
185 | return this.devices.values();
186 | }
187 | }
188 |
--------------------------------------------------------------------------------
/src/utils/device-logger.ts:
--------------------------------------------------------------------------------
1 | import { Device } from 'shellies-ng';
2 | import { Logger, LogLevel } from 'homebridge';
3 |
4 | /**
5 | * Utility used to prefix log messages with device IDs.
6 | */
7 | export class DeviceLogger {
8 | protected readonly prefix: string;
9 |
10 | /**
11 | * @param device - The device to use.
12 | * @param deviceName - A user-friendly name of the device.
13 | * @param logger - The logging device to write to.
14 | */
15 | constructor(readonly device: Device, deviceName: string | undefined, protected readonly logger: Logger) {
16 | this.prefix = `[${deviceName || device.id}] `;
17 | }
18 |
19 | info(message: string, ...parameters: unknown[]) {
20 | this.log(LogLevel.INFO, message, ...parameters);
21 | }
22 |
23 | warn(message: string, ...parameters: unknown[]) {
24 | this.log(LogLevel.WARN, message, ...parameters);
25 | }
26 |
27 | error(message: string, ...parameters: unknown[]) {
28 | this.log(LogLevel.ERROR, message, ...parameters);
29 | }
30 |
31 | debug(message: string, ...parameters: unknown[]) {
32 | this.log(LogLevel.DEBUG, message, ...parameters);
33 | }
34 |
35 | log(level: LogLevel, message: string, ...parameters: unknown[]) {
36 | this.logger.log(
37 | level,
38 | this.prefix + message,
39 | ...parameters,
40 | );
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/utils/services.ts:
--------------------------------------------------------------------------------
1 | import { API, Service, WithUUID } from 'homebridge';
2 |
3 | import { CustomCharacteristics } from './characteristics';
4 |
5 | type S = WithUUID;
6 |
7 | export interface CustomServices {
8 | PowerMeter: S;
9 | }
10 |
11 | /**
12 | * Returns a set of custom HomeKit services.
13 | * @param api - A reference to the homebridge API.
14 | * @param characteristics - Custom characteristics used with these services.
15 | */
16 | export const createServices = (api: API, characteristics: CustomCharacteristics): CustomServices => {
17 | /**
18 | * Reports power meter readings.
19 | */
20 | class PowerMeter extends api.hap.Service {
21 | static readonly UUID = 'DEDBEA44-11ED-429C-BD75-9A2286AA8707';
22 |
23 | constructor(displayName?: string, subtype?: string) {
24 | super(displayName, PowerMeter.UUID, subtype);
25 |
26 | this.addCharacteristic(characteristics.CurrentConsumption);
27 |
28 | this.addOptionalCharacteristic(characteristics.TotalConsumption);
29 | this.addOptionalCharacteristic(characteristics.ElectricCurrent);
30 | this.addOptionalCharacteristic(characteristics.Voltage);
31 | }
32 | }
33 |
34 | return {
35 | PowerMeter,
36 | };
37 | };
38 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2018",
4 | "module": "commonjs",
5 | "lib": [
6 | "es2015",
7 | "es2016",
8 | "es2017",
9 | "es2018"
10 | ],
11 | "declaration": true,
12 | "declarationMap": true,
13 | "sourceMap": true,
14 | "outDir": "./dist",
15 | "rootDir": "./src",
16 | "strict": true,
17 | "esModuleInterop": true,
18 | "noImplicitAny": false,
19 | "experimentalDecorators": true
20 | },
21 | "include": [
22 | "src/"
23 | ],
24 | "exclude": [
25 | "**/*.spec.ts"
26 | ]
27 | }
28 |
--------------------------------------------------------------------------------