├── .gitignore
├── .project
├── CHANGELOG.md
├── LICENSE
├── README.md
├── config.schema.json
├── index.js
├── package.json
└── src
├── Constants.js
├── homekit
├── NukiBridgeMaintainanceSwitchAccessory.js
├── NukiBridgePlatform.js
├── NukiLockAccessory.js
└── NukiOpenerAccessory.js
└── nuki
├── NukiBridge.js
└── NukiLock.js
/.gitignore:
--------------------------------------------------------------------------------
1 | npm-debug.log
2 | .DS_Store
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | homebridge-nukiio
4 |
5 |
6 |
7 |
8 |
9 | com.eclipsesource.jshint.ui.builder
10 |
11 |
12 |
13 |
14 |
15 | org.nodeclipse.ui.NodeNature
16 | org.eclipse.wst.jsdt.core.jsNature
17 | tern.eclipse.ide.core.ternnature
18 |
19 |
20 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## 0.16.1
2 |
3 | Added some temporary logging.
4 |
5 | ## 0.16.0
6 |
7 | New features:
8 |
9 | - Support Nuki Smart Door.
10 | - Support Nuki Smart Lock 3.0 (Pro).
11 |
12 | ## 0.15.4
13 |
14 | Bugfix:
15 |
16 | - Fixed HTTP 503 Error while retrieving or adding callback by using retries.
17 |
18 | ## 0.15.3
19 |
20 | New features:
21 |
22 | - New button in opener to deactivate doorbell ring.
23 |
24 | ## 0.15.2
25 |
26 | New features:
27 |
28 | - New setting for sending hashed token instead of plaintext.
29 |
30 | ## 0.15.1
31 |
32 | New features:
33 |
34 | - New setting for locks preventLockingIfAlreadyLocked.
35 |
36 | ## 0.15.0
37 |
38 | New features:
39 |
40 | - Support Nuki Opener ringactionState in callback as doorbell.
41 |
42 | ## 0.14.0
43 |
44 | New features:
45 |
46 | - Support Nuki battery charging and battery charging state (needs bridge firmware version 2.7.0 or 1.17.0 and smart lock firmware version 2.8.1/1.10.0).
47 |
48 | ## 0.13.2
49 |
50 | Bugfix:
51 |
52 | - Fixed Config UI X schema file to not generate lock or opener for empty config.
53 | - Fixed that homebrige crashes if there is invalid config.
54 |
55 | ## 0.13.1
56 |
57 | New features:
58 |
59 | - Now the cache by default is stored in hombridge storage path '.homebridge-nukiio'.
60 |
61 | Bugfix:
62 |
63 | - Fixed Config UI X schema file.
64 |
65 | ## 0.13.0
66 |
67 | New features:
68 |
69 | - Support Config UI X.
70 |
71 | ## 0.12.0
72 |
73 | New features:
74 |
75 | - Make lock "ring to open" and "continuous mode" optional.
76 |
77 | ## 0.11.1
78 |
79 | Bugfix:
80 |
81 | - Fixed battery status after homebridge restart.
82 |
83 | ## 0.11.0
84 |
85 | New features:
86 |
87 | - Added door contact sensor support for Nuki 2.0 (needs bridge firmware version 2.6.0 or 1.16.0).
88 |
89 | ## 0.10.0
90 |
91 | New features:
92 |
93 | - Added a switch to locks with usesDoorLatch = true to de-/activate pulling the latch. Implemented to prevent accidental unlatch of door.
94 | You can use automations to switch to desired state (i.e. based on location or time).
95 |
96 | Feature changes and removal:
97 |
98 | - Door latch handling changed. If you define usesDoorLatch = true you will no longer get three locks, but only two.
99 | One that just does lock/unlock (without pulling the latch), and one that always is displayed as locked and pulls
100 | the door latch on unlock. This way done from personal experience where only these two are only needed. Other behavoirs
101 | could be done using scenes. Since one lock was removed you need to adapt your existing scenes/automations that used this lock.
102 |
103 | ## 0.9.0
104 |
105 | New features:
106 |
107 | - Under the hood improvements.
108 |
109 | ## 0.8.0
110 |
111 | New features:
112 |
113 | - Added suppert of Nuki Opener. See README for details.
114 | - Retry of LockActions is now also done fpr 503 errors.
115 | - Make retry behavior configurable.
116 | - Added parameter 'request_timeout_other' to set timeout for all other communication with bridge (get/list/add callbacks, maintainance calls, etc.)
117 |
118 | ## 0.7.9
119 |
120 | Bugfix:
121 |
122 | - No homekit notifications if homebridge restarts (thanks to nicoh88).
123 |
124 | ## 0.7.8
125 |
126 | New features:
127 |
128 | - Updated dependency to request.
129 |
130 | ## 0.7.7
131 |
132 | Bugfix:
133 |
134 | - Listen to Ipv4.
135 |
136 | ## 0.7.6
137 |
138 | Bugfix:
139 |
140 | - Fix initial state.
141 |
142 | ## 0.7.5
143 |
144 | Bugfix:
145 |
146 | - More fixings on updating state.
147 |
148 | ## 0.7.4
149 |
150 | Bugfix:
151 |
152 | - Fixed some issues updating state for "always unlock" and "always unlatch".
153 |
154 | ## 0.7.3
155 |
156 | Bugfix:
157 |
158 | - Fixed some issues updating state correctly.
159 |
160 | ## 0.7.2
161 |
162 | Bugfix:
163 |
164 | - Now uses updateValue instead of setValue to update iOS correctly.
165 |
166 | ## 0.7.1
167 |
168 | Bugfix:
169 |
170 | - Fixed README.
171 |
172 | ## 0.7.0
173 |
174 | Feature changes and removal:
175 |
176 | - Door latch handling changed. You can no longer define lock and unlock actions. Instead you need to define if a door uses a door latch.
177 | If so, than three locks will be added to homekit. One that unlocks the door pulling the door latch, one that unlocks the door without
178 | pulling the door latch, and one that always is display as locked and pulls the door latch on unlock.
179 | - You cannot add multiple locks with the same id anymore.
180 |
181 | ## 0.6.4
182 |
183 | New features:
184 |
185 | - Lock actions will now be called one more time if bridge returns success = false. This can happen due to connection issues.
186 |
187 | ## 0.6.3
188 |
189 | Bugfix:
190 |
191 | - Initial lock state request now works for lock state mode 1.
192 |
193 | ## 0.6.2
194 |
195 | Bugfix:
196 |
197 | - In case of a connection error during a lock action assume that it was successful. In rare cases this might be wrong, but in most cases I experienced a connection error the lock action was executed succesfully.
198 |
199 | ## 0.6.1
200 |
201 | Bugfix:
202 |
203 | - Button to refresh all now also pushes refreshed states to HomeKit.
204 |
205 | ## 0.6.0
206 |
207 | New features:
208 |
209 | - Implemented lock state mode "2".
210 | - Added the ability to add maintainance buttons for reboot, firmware update, and to refresh all locks state.
211 | - Added methods to bridge for reboot, firmware update, and for refreshing all locks.
212 |
213 | Bugfix:
214 |
215 | - Changed some methods to be marked as private.
216 | - Update of README.md.
217 | - Changed text for AccessoryInformation.
218 |
219 | ## 0.5.5
220 |
221 | Bugfix:
222 |
223 | - If an error occured calling a lock action, then the state will be set to unkown.
224 | - Finally fixed state issue for state update from background (i.e. for Webhooks and doors with door latches).
225 |
226 | ## 0.5.4
227 |
228 | Bugfix:
229 |
230 | - Move logging out put for successful message to actualle be called only after characteristics are set.
231 | - Removed unwanted console logging.
232 | - Only check initial locks state if lock_state_mode = 1.
233 | - More fixes on state issue for state update from background (i.e. for Webhooks and doors with door latches).
234 |
235 | ## 0.5.3
236 |
237 | Bugfix:
238 |
239 | - Bridge url now does not need to start with protocol http.
240 |
241 | ## 0.5.2
242 |
243 | New features:
244 |
245 | - Added priority to door to have a better order if you tell Siri to unlock all doors.
246 | - Added configuration for lock state mode.
247 |
248 | Bugfix:
249 |
250 | - Json repsonse success=false was not shown as error.
251 |
252 | ## 0.5.1
253 |
254 | Bugfix:
255 |
256 | - Removed unwanted logging.
257 | - Set default timeout for requesting lock state to 15 seconds.
258 | - Set default timeout for requesting lock action to 45 seconds.
259 | - Webhooks now work with Nuki bridge firmware 1.2.9 and up.
260 |
261 | ## 0.5.0
262 |
263 | New features:
264 |
265 | - Make use of Nuki Webhook to avoid requests for lock state.
266 | - Updated according to Nuki HTTP API documentation v1.0.3.
267 |
268 | Bugfix:
269 |
270 | - Added context to setValue call.
271 | - Hopefully fixed the state issue for state update from background (i.e. for Webhooks and doors with door latches).
272 | - Changed queue handling.
273 |
274 | ## 0.4.5
275 |
276 | Bugfix:
277 |
278 | - Fix logging.
279 | - Always updated to battery is low state.
280 |
281 | ## 0.4.4
282 |
283 | Bugfix:
284 |
285 | - Need to push battery state update back to HomeKit.
286 |
287 | ## 0.4.3
288 |
289 | Bugfix:
290 |
291 | - Added battery state update to the webhook.
292 |
293 | ## 0.4.2
294 |
295 | Bugfix:
296 |
297 | - Battery service is returned now.
298 |
299 | ## 0.4.1
300 |
301 | New features:
302 |
303 | - Added information service.
304 | - Added battery service (only critical battery state is provided by Nuki, so no change in percentage).
305 |
306 | Bugfix:
307 |
308 | - Extended logging.
309 | - Change cache key.
310 |
311 | ## 0.4.0
312 |
313 | New features:
314 |
315 | - Changed to provide a platform with accessories. You must change your configuration.
316 |
317 | ## 0.3.11
318 |
319 | Bugfix:
320 |
321 | - One more logging change to avoid confusion.
322 |
323 | ## 0.3.10
324 |
325 | Bugfix:
326 |
327 | - Improved logging some more.
328 |
329 | ## 0.3.9
330 |
331 | Bugfix:
332 |
333 | - Improved logging.
334 |
335 | ## 0.3.8
336 |
337 | New features:
338 |
339 | - Added server for receiving webhook requests (early stage, as not released yet by Nuki and requirements are not clear).
340 |
341 | Bugfix:
342 |
343 | - Next try to fix state for doors with door latches.
344 | - Doors with door latches now never execute a lock action.
345 | - CleanCode.
346 |
347 | ## 0.3.7
348 |
349 | Bugfix:
350 |
351 | - Context drives me crazy in JS.
352 |
353 | ## 0.3.6
354 |
355 | Bugfix:
356 |
357 | - Status cache corrected for doors with door latches.
358 |
359 | ## 0.3.5
360 |
361 | Bugfix:
362 |
363 | - Variable corrected.
364 |
365 | ## 0.3.4
366 |
367 | Bugfix:
368 |
369 | - Now, hopefully the status of doors with door latches works.
370 |
371 | ## 0.3.3
372 |
373 | Bugfix:
374 |
375 | - Added missing parameter.
376 |
377 | ## 0.3.2
378 |
379 | New features:
380 |
381 | - Use different request timeouts for lock state and lock action. (You might need to fix your configuration)
382 |
383 | Bugfix:
384 |
385 | - Wrong logging for lock actions.
386 |
387 | ## 0.3.1
388 |
389 | Bugfix:
390 |
391 | - Less logging.
392 | - Fix context, like always.
393 |
394 | ## 0.3.0
395 |
396 | New features:
397 |
398 | - Again some major code re-work.
399 |
400 | ## 0.2.4
401 |
402 | Bugfix:
403 |
404 | - Doors with door latches must never change to unlock state.
405 |
406 | ## 0.2.3
407 |
408 | Bugfix:
409 |
410 | - Fix wrong function call for setting state.
411 |
412 | ## 0.2.2
413 |
414 | Bugfix:
415 |
416 | - Fix context at other position.
417 |
418 | ## 0.2.1
419 |
420 | Bugfix:
421 |
422 | - Fix context.
423 |
424 | ## 0.2.0
425 |
426 | New features:
427 |
428 | - Support for doors with door latches. If you set "lock_action" and "unlock_action" both to "3" you get an accessory that shows always locked state and always does an unlatch.
429 | - You can now set the directory for the local cache.
430 | - Major re-work on request handling.
431 |
432 | Others:
433 |
434 | - Changed default value of "request_timeout" to 60000 ms.
435 | - Clean code.
436 |
437 | ## 0.1.4
438 |
439 | Bugfix:
440 |
441 | - Fix variable, again.
442 |
443 | ## 0.1.3
444 |
445 | New features:
446 |
447 | - If a getState request is running for one lock and getState is requested again for this lock, no additional request will be made, it will use the cache set by the running request when this one ends.
448 |
449 | ## 0.1.2
450 |
451 | Bugfix:
452 |
453 | - Set state to home kit even if a timeout was reached setting state as we can assume that everything went well and nuki is just too slow.
454 |
455 | ## 0.1.1
456 |
457 | Bugfix:
458 |
459 | - Fix variable.
460 |
461 | ## 0.1.0
462 |
463 | New features:
464 |
465 | - If timeout is reached use the last known state from cache.
466 |
467 | Bugfix:
468 |
469 | - Use timeout on requests to bridge.
470 |
471 | ## 0.0.5
472 |
473 | Bugfix:
474 |
475 | - Fixed socket hang up.
476 |
477 | ## 0.0.4
478 |
479 | New features:
480 |
481 | - Added configuration for lock action and unlock action (i.e. if you want to unlatch instead of just unlock).
482 |
483 | ## 0.0.3
484 |
485 | Initial release version.
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | [](https://github.com/homebridge/homebridge/wiki/Verified-Plugins)
2 |
3 | **NOTE: Since version 0.10.0 Only two locks are exposed. One that just does lock/unlock (without pulling the latch), and one that always is
4 | displayed as locked and pulls the door latch on unlock. This way done from personal experience where only these two are only needed. Other behavoirs
5 | could be done using scenes. Since one lock was removed you need to adapt your existing scenes/automations that used this lock. You will now also get a switch in
6 | the lock to enable/disbale unlatching, so you can use automations to switch to desired state (i.e. based on location or time). This was implemented
7 | to prevent accidental unlatch of door.**
8 |
9 | **NOTE: Since version 0.7.0 the configuration keys for lock and unlock actions are no longer supported, for now. Use 'usesDoorLatch' for doors with door latch.**
10 |
11 | **NOTE: Since version 0.4.0 the configuration changed to platform. You must fix your configuration to match the new configuration format.**
12 |
13 | ***
14 | # homebridge-nukiio
15 | Nuki.io support for Homebridge: https://github.com/nfarina/homebridge that supports Nuki Lock and Nuki Opener.
16 |
17 | # Current state
18 | Seems to work solid. Feel free to create new issues in github for any problems.
19 |
20 | # Requirements
21 | You need the following information from your bridge for the configuration:
22 | - You must activate the developer mode on you bridge
23 | - The URL to your bridge, IP and port can be configured when setting up the bridge in the Nuki App, example http://10.0.0.1:8080
24 | - The API token, can be configured when setting up the bridge in the Nuki App
25 | - The nuki id of your locks/opener, can be found when calling http://your-nuki-bridge-url/list?token=your-nuki-api-token in a browser
26 |
27 | # Configuration
28 | Example config.json:
29 |
30 | {
31 | "platforms": [
32 | {
33 | "platform": "NukiBridge",
34 | "bridge_url": "your-nuki-bridge-url",
35 | "api_token" : "your-nuki-api-token",
36 | "api_token_hashed": true, // (optional, default: false)
37 | "request_timeout_lockstate": 30000, // (in ms, optional, default: 15000)
38 | "request_timeout_lockaction": 60000, // (in ms, optional, default: 45000)
39 | "request_timeout_other": 30000, // (in ms, optional, default: 15000)
40 | "cache_directory": ".myFolder/.node-persist/storage", // (optional, default is in hombridge storage path '.homebridge-nukiio')
41 | "webhook_server_ip_or_name": "xxx.xxx.xxx.xxx", // (optional, must be the IP/Hostname of the server running homebridge)
42 | "webhook_port": 51827, // (optional, default: 51827, must be a free port on the server running homebridge, NOT the same as homebridge)
43 | "lock_state_mode": 0, // (see below, optional, default: 0)
44 | "lockaction_maxtries": 3, // (optional, default: 3)
45 | "lockaction_retrydelay": 3000, // (in ms, optional, default: 3000)
46 | "add_maintainance_buttons": false, // (optional, default: false, if set to true, than three switches will be added as accessory to do reboot, firmware update, and to refresh all locks state)
47 | "locks": [
48 | {
49 | "id": "your-lock-nukiid",
50 | "name": "Front Door",
51 | "usesDoorLatch" : true, // (default: false)
52 | "usesDoorContactSensor" : true, // (default: false)
53 | "preventLockingIfAlreadyLocked" : true, // (default: false)
54 | "priority" : 1, // (optional, default: 99 [locks with higher priority {lower number} will be proccessed first])
55 | "deviceType" : 0 // (default: 0, 0 = Nuki Smart Lock 1.0/2.0, 3 = Nuki Smart Door, 4 = Nuki Smart Lock 3.0 (Pro))
56 | }
57 | ],
58 | "openers": [
59 | {
60 | "id": "your-opener-nukiid",
61 | "name": "Main Opener",
62 | "disableRingToOpen": false,
63 | "disableContinuousMode": false,
64 | "priority" : 1 // (optional, default: 99 [openers with higher priority {lower number} will be proccessed first])
65 | }
66 | ]
67 | }
68 | ]
69 | }
70 |
71 | ## Cache directory storage (cache_directory)
72 | The cache directory is used to cache the state of the locks. It must point to a **valid** and **empty** directory and the user that runs homebridge must have **write access**.
73 |
74 | ## Configure lock state mode
75 | You can choose one of the following values to determine how to retrieve the state of the locks:
76 |
77 | |Value| Description|
78 | |-|-|
79 | |0 (default)| Lock states are requested from the bridge via /lockState. This means, that the bridge always connects to each lock via Bluetooth to retrieve an always up-to-date lock state. This mode takes a lot of time for retrieving the lock state when using more than one lock, as this can not be processed in parallel|
80 | |1| Only use internal cached values by the plugin. These values get their state by using the webhooks of the bridge, so you need to active them. This mode is the fastest as no request are send to the bridge but of course has the drawback that the cache might not always be correct.|
81 | |2| Lock states are requested from the bridge via /list using a last known lock state cached by Nuki bridge. This means, that the bridge does not connect to any lock via Bluetooth to retrieve lock state. This mode is faster than mode "0" but still makes requests to the bridge. If multiple locks request the lockstate in parallel than only one request is sent to bridge for all locks. The drawback is, that the last known state might not always be correct.|
82 |
83 | ## Use Nuki Webhook
84 | Usually the plugin makes calls to Nuki bridge to get the state of a lock. Since Nuki supports Webhooks it is possible for Nuki to push a lock state on the fly to the plugin.
85 | If the configuration parameter "webhook_server_ip_or_name" is set, than the plugin registers a Webhook in Nuki automatically if not already set to use it for lock state update and cache.
86 |
87 | *Note: An automatically added Webhook does not get removed ever, so you need to do it manually if you don't need it anymore.*
88 |
89 | ## Doors with door latches
90 | You can define if a door uses a door latch by setting 'usesDoorLatch' to true. If you do so, than two locks will be added to homekit. One that unlocks the door without
91 | pulling the door latch ("lockname") and one that always is displayed as locked and pulls the door latch on unlock ("lockname ALWAYS Unlatch").
92 | You will now also get a switch in the lock to enable/disbale unlatching so you can use automations to switch to desired state (i.e. based on location or time).
93 | This was implemented to prevent accidental unlatch of door.
94 |
95 | ## preventLockingIfAlreadyLocked
96 | This setting is usefull if you have a lock that is set to turn only 360 degrees instead of 720. Setting preventLockingIfAlreadyLocked to true avoids a second lock action so that the lock
97 | will never lock to 720. Use this setting carefully as this might not lock your lock if a wrong state is present in homebridge for any reason.
98 |
99 | ## Nuki Opener
100 | If you configure a Nuki opener you will get three lock accessories and one button. One lock to open the door, one to de/activate RingToOpen and one to de/activate ContinousMode.
101 | If the lock accessory for RingToOpen is secured then RingToOpen is inactive, other wise it is active.
102 | If the lock accessory for ContinousMode is secured then ContinousMode is inactive, other wise it is active.
103 | The button can be used to deactivate doorbell ring.
104 |
105 | # Errors
106 | For errors on lock actions a configured number of retries with delay will be done. You can set the parameters 'lockaction_maxtries' and 'lockaction_retrydelay' to meet your needs.
107 |
108 | # Additional information
109 | The plugin uses the Nuki API of the bridge. The API token can be configured via the Nuki app when enabling the API.
110 | The plugin was build on Nuki API documentation v1.9.0. Valid values for lock action and unlock action can be found in the Nuki API documentation.
111 |
--------------------------------------------------------------------------------
/config.schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "pluginAlias": "NukiBridge",
3 | "pluginType": "platform",
4 | "singular": true,
5 | "headerDisplay": "Nuki.io support for Homebridge that supports Nuki Lock and Nuki Opener.",
6 | "schema": {
7 | "type": "object",
8 | "properties": {
9 | "bridge_url": {
10 | "title": "Bridge URL",
11 | "description": "The URL of the Nuki bridge.",
12 | "default": "http://",
13 | "type": "string",
14 | "required": true,
15 | "format": "uri"
16 | },
17 | "api_token": {
18 | "title": "Bridge API Token",
19 | "description": "The API Token of the Nuki bridge. Can be configured when setting up the bridge in the Nuki App.",
20 | "type": "string",
21 | "required": true
22 | },
23 | "api_token_hashed": {
24 | "title": "Send Bridge API Token Hashed",
25 | "description": "Send Bridge API Token using a hash. By default it is plaintext.",
26 | "default": false,
27 | "type": "boolean"
28 | },
29 | "lock_state_mode": {
30 | "title": "Lock state mode",
31 | "description": "The mode to evaluate lock states. See readme for details.",
32 | "default": 0,
33 | "oneOf": [
34 | { "title": "Always request lock states", "enum": [0] },
35 | { "title": "Use plugin cache", "enum": [1] },
36 | { "title": "Use bridge cache", "enum": [2] }
37 | ],
38 | "type": "integer",
39 | "required": true
40 | },
41 | "webhook_server_ip_or_name": {
42 | "title": "Webhook server IP/name",
43 | "description": "The IP or name of the server receiving the webhook (server that is running homebridge).",
44 | "type": "string"
45 | },
46 | "webhook_port": {
47 | "title": "Webhook port",
48 | "description": "The port the webhook server should listen to. Must be free and not the hombridge port.",
49 | "default": 51827,
50 | "type": "integer",
51 | "minimum": 1
52 | },
53 | "cache_directory": {
54 | "title": "Cache directory",
55 | "description": "The directory where to write the cache. Default is in hombridge storage path '.homebridge-nukiio'. It must point to a valid and empty directory and the user that runs homebridge must have write access.",
56 | "default": "",
57 | "type": "string"
58 | },
59 | "request_timeout_lockstate": {
60 | "title": "Request timeout lock state",
61 | "description": "The request time of for requesting lock state.",
62 | "default": 15000,
63 | "type": "integer",
64 | "minimum": 1
65 | },
66 | "request_timeout_lockaction": {
67 | "title": "Request timeout lock action",
68 | "description": "The request time of for requesting lock action.",
69 | "default": 45000,
70 | "type": "integer",
71 | "minimum": 1
72 | },
73 | "request_timeout_other": {
74 | "title": "Request timeout other",
75 | "description": "The request time of for other requests.",
76 | "default": 15000,
77 | "type": "integer",
78 | "minimum": 1
79 | },
80 | "lockaction_maxtries": {
81 | "title": "Maxiumum retries lock action",
82 | "description": "The maxiumum retries for lock action.",
83 | "default": 3,
84 | "type": "integer",
85 | "minimum": 1
86 | },
87 | "lockaction_retrydelay": {
88 | "title": "Retry delay lock action",
89 | "description": "The retry delay for lock action.",
90 | "default": 3000,
91 | "type": "integer",
92 | "minimum": 1
93 | },
94 | "add_maintainance_buttons": {
95 | "title": "Maintainance buttons",
96 | "description": "Add maintainance buttons. If active, than three switches will be added as accessory to do reboot, firmware update, and to refresh all locks states.",
97 | "default": false,
98 | "type": "boolean"
99 | },
100 | "locks": {
101 | "title": "Locks",
102 | "type": "array",
103 | "items": {
104 | "type": "object",
105 | "properties": {
106 | "id": {
107 | "title": "Lock ID",
108 | "description": "The ID of the lock. Can be found when calling http://your-nuki-bridge-url/list?token=your-nuki-api-token in a browser.",
109 | "type": "string"
110 | },
111 | "name": {
112 | "title": "Name",
113 | "description": "The name of the lock to use in Homekit.",
114 | "type": "string"
115 | },
116 | "usesDoorLatch": {
117 | "title": "Uses door latch",
118 | "description": "Does your door use a door latch?",
119 | "type": "boolean"
120 | },
121 | "usesDoorContactSensor": {
122 | "title": "Uses door sensor",
123 | "description": "Does your nuki use a door sensor?",
124 | "type": "boolean"
125 | },
126 | "preventLockingIfAlreadyLocked": {
127 | "title": "Prevent locking if already locked",
128 | "description": "Can be used for locks set to turn 360 degrees to not lock twice.",
129 | "type": "boolean"
130 | },
131 | "priority": {
132 | "title": "Priority",
133 | "description": "The priority of the lock. Locks with higher priority {lower number} will be proccessed first.",
134 | "placeholder": 99,
135 | "type": "integer",
136 | "minimum": 1
137 | },
138 | "deviceType": {
139 | "title": "Device Type",
140 | "description": "The device type of the lock. 0 = Nuki Smart Lock 1.0/2.0, 3 = Nuki Smart Door, 4 = Nuki Smart Lock 3.0 (Pro).",
141 | "placeholder": 0,
142 | "type": "integer",
143 | "minimum": 0
144 | }
145 | },
146 | "required": [ "id", "name"]
147 | }
148 | },
149 | "openers": {
150 | "title": "Openers",
151 | "type": "array",
152 | "items": {
153 | "type": "object",
154 | "properties": {
155 | "id": {
156 | "title": "Opener ID",
157 | "description": "The ID of the opener. Can be found when calling http://your-nuki-bridge-url/list?token=your-nuki-api-token in a browser.",
158 | "type": "string"
159 | },
160 | "name": {
161 | "title": "Name",
162 | "description": "The name of the opener to use in Homekit.",
163 | "type": "string"
164 | },
165 | "disableRingToOpen": {
166 | "title": "Disable RingToOpen",
167 | "description": "Removes lock accessory for setting RingToOpen",
168 | "type": "boolean"
169 | },
170 | "disableContinuousMode": {
171 | "title": "Disable ContinuousMode",
172 | "description": "Removes lock accessory for setting ContinuousMode",
173 | "type": "boolean"
174 | },
175 | "priority": {
176 | "title": "Priority",
177 | "description": "The priority of the opener. Openers with higher priority {lower number} will be proccessed first.",
178 | "placeholder": 99,
179 | "type": "integer",
180 | "minimum": 1
181 | }
182 | },
183 | "required": [ "id", "name"]
184 | }
185 | }
186 | }
187 | },
188 | "form": [
189 | "bridge_url",
190 | {
191 | "key": "api_token",
192 | "type": "password"
193 | },
194 | "lock_state_mode",
195 | {
196 | "key": "webhook_server_ip_or_name",
197 | "condition": {
198 | "functionBody":"try { return model.lock_state_mode===1} catch(e){return false}"
199 | },
200 | "required": true
201 | },
202 | {
203 | "key": "webhook_port",
204 | "condition": {
205 | "functionBody":"try { return model.lock_state_mode===1} catch(e){return false}"
206 | },
207 | "required": true
208 | },
209 | "cache_directory",
210 | "request_timeout_lockstate",
211 | "request_timeout_lockaction",
212 | "request_timeout_other",
213 | "lockaction_maxtries",
214 | "lockaction_retrydelay",
215 | "add_maintainance_buttons",
216 | {
217 | "key": "locks",
218 | "items": [
219 | "locks[].id",
220 | "locks[].name",
221 | "locks[].usesDoorLatch",
222 | "locks[].usesDoorContactSensor",
223 | "locks[].priority",
224 | "locks[].deviceType"
225 | ]
226 | },
227 | {
228 | "key": "openers",
229 | "items": [
230 | "openers[].id",
231 | "openers[].name",
232 | "openers[].disableRingToOpen",
233 | "openers[].disableContinuousMode",
234 | "openers[].priority"
235 | ]
236 | }
237 | ]
238 |
239 | }
240 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | var NukiBridgeMaintainanceSwitchAccessory = require('./src/homekit/NukiBridgeMaintainanceSwitchAccessory');
2 | var NukiOpenerAccessory = require('./src/homekit/NukiOpenerAccessory');
3 | var NukiLockAccessory = require('./src/homekit/NukiLockAccessory');
4 | var NukiBridgePlatform = require('./src/homekit/NukiBridgePlatform');
5 |
6 | module.exports = function(homebridge) {
7 | homebridge.registerPlatform("homebridge-nukiio", "NukiBridge", NukiBridgePlatform);
8 | homebridge.registerAccessory("homebridge-nukiio", "NukiLock", NukiLockAccessory);
9 | homebridge.registerAccessory("homebridge-nukiio", "NukiOpener", NukiOpenerAccessory);
10 | homebridge.registerAccessory("homebridge-nukiio", "NukiBridgeMaintainanceSwitch", NukiBridgeMaintainanceSwitchAccessory);
11 | };
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "homebridge-nukiio",
3 | "version": "0.16.1",
4 | "description": "Homebridge plugin for Nuki: http://nuki.io",
5 | "license": "GPL-3.0",
6 | "keywords": [
7 | "homebridge-plugin",
8 | "homebridge",
9 | "plugin",
10 | "nuki",
11 | "lock",
12 | "smart",
13 | "homekit",
14 | "siri"
15 | ],
16 | "repository": {
17 | "type": "git",
18 | "url": "git@github.com:benzman81/homebridge-nukiio.git"
19 | },
20 | "bugs": {
21 | "url": "https://github.com/benzman81/homebridge-nukiio/issues"
22 | },
23 | "engines": {
24 | "node": ">=0.12.0",
25 | "homebridge": ">=0.3.0"
26 | },
27 | "dependencies": {
28 | "request": "2.87.x",
29 | "node-persist" : "2.0.x"
30 | },
31 | "homepage": "https://github.com/benzman81/homebridge-nukiio#readme",
32 | "author": "benzman81"
33 | }
34 |
--------------------------------------------------------------------------------
/src/Constants.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | NUKI_LOCK_ACTION_UNLOCK : "1",
3 | NUKI_LOCK_ACTION_LOCK : "2",
4 | NUKI_LOCK_ACTION_UNLATCH : "3",
5 | NUKI_LOCK_ACTION_LOCK_N_GO : "4",
6 | NUKI_LOCK_ACTION_LOCK_N_GO_UNLATCH : "5",
7 |
8 | NUKI_LOCK_STATE_UNCALIBRATED : 0,
9 | NUKI_LOCK_STATE_LOCKED : 1,
10 | NUKI_LOCK_STATE_UNLOCKING : 2,
11 | NUKI_LOCK_STATE_UNLOCKED : 3,
12 | NUKI_LOCK_STATE_LOCKING : 4,
13 | NUKI_LOCK_STATE_UNLATCHED : 5,
14 | NUKI_LOCK_STATE_UNLOCKED_LOCK_N_GO : 6,
15 | NUKI_LOCK_STATE_UNLATCHING : 7,
16 | NUKI_LOCK_STATE_MOTOR_BLOCKED : 254,
17 | NUKI_LOCK_STATE_UNDEFINED : 255,
18 |
19 | DEFAULT_REQUEST_TIMEOUT_LOCK_STATE : 15000,
20 | DEFAULT_REQUEST_TIMEOUT_LOCK_ACTION : 45000,
21 | DEFAULT_REQUEST_TIMEOUT_OTHER : 15000,
22 | DEFAULT_WEBHOOK_SERVER_PORT : 51827,
23 | DEFAULT_CACHE_DIRECTORY_NAME : ".homebridge-nukiio",
24 | DEFAULT_PRIORITY : 99,
25 | REBOOT_WAIT_TIME : 45000,
26 |
27 | DUMMY_BRIDGE_FOR_OPENER : false,
28 |
29 | LOCK_STATE_MODE_REQUEST_LOCKSTATE : 0,
30 | LOCK_STATE_MODE_ONLY_CACHE : 1,
31 | LOCK_STATE_MODE_REQUEST_LASTKNOWNLOCKSTATE : 2,
32 |
33 | CONTEXT_FROM_NUKI_BACKGROUND : "fromNukiBackground",
34 |
35 | DEFAULT_MAX_TRIES_FOR_LOCK_ACTIONS : 3,
36 | DEFAULT_DELAY_FOR_RETRY : 3000,
37 |
38 | BATTERY_FULL : 100,
39 | BATTERY_LOW : 5
40 | };
--------------------------------------------------------------------------------
/src/homekit/NukiBridgeMaintainanceSwitchAccessory.js:
--------------------------------------------------------------------------------
1 | const Constants = require('../Constants');
2 |
3 | var Service, Characteristic;
4 |
5 | function NukiBridgeMaintainanceSwitchAccessory(ServiceParam, CharacteristicParam, log, id, name, nukiBridge, nukiLockAccessories, nukiOpenerAccessories) {
6 | Service = ServiceParam;
7 | Characteristic = CharacteristicParam;
8 |
9 | this.log = log;
10 | this.id = id;
11 | this.name = name;
12 | this.nukiBridge = nukiBridge;
13 | this.nukiLockAccessories = nukiLockAccessories;
14 | this.nukiOpenerAccessories = nukiOpenerAccessories;
15 |
16 | this.switchService = new Service.Switch(this.name);
17 | this.switchService.getCharacteristic(Characteristic.On).on('get', this.getState.bind(this)).on('set', this.setState.bind(this));
18 |
19 | this.informationService = new Service.AccessoryInformation();
20 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "Nuki.io").setCharacteristic(Characteristic.Model, "Nuki.io Maintainance Switch").setCharacteristic(Characteristic.SerialNumber, "Nuki.io-Id " + this.id);
21 | }
22 |
23 | NukiBridgeMaintainanceSwitchAccessory.prototype.getState = function(callback) {
24 | this.log("Getting current state for '%s'...", this.id);
25 | var state = this.nukiBridge.storage.getItemSync('bridge-' + this.nukiBridge.bridgeUrl + '-' + this.id + '-cache');
26 | if (state === undefined) {
27 | state = false;
28 | }
29 | callback(null, state);
30 | };
31 |
32 | NukiBridgeMaintainanceSwitchAccessory.prototype.setState = function(powerOn, callback) {
33 | this.log("Switch state for '%s' to '%s'...", this.id, powerOn);
34 | this.nukiBridge.storage.setItemSync('bridge-' + this.nukiBridge.bridgeUrl + '-' + this.id + '-cache', false);
35 | if (powerOn) {
36 | if (this.id === "maintainance-switch-reboot") {
37 | var callbackWrapper = (function(err, json) {
38 | callback(null);
39 | setTimeout((function() {
40 | this.switchService.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
41 | }).bind(this), 2500);
42 | }).bind(this);
43 | this.nukiBridge.reboot(callbackWrapper);
44 | }
45 | else if (this.id === "maintainance-switch-fwupdate") {
46 | var callbackWrapper = (function(err, json) {
47 | callback(null);
48 | setTimeout((function() {
49 | this.switchService.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
50 | }).bind(this), 2500);
51 | }).bind(this);
52 | this.nukiBridge.updateFirmware(callbackWrapper);
53 | }
54 | else if (this.id === "maintainance-switch-refreshall") {
55 | var callbackWrapper = (function(err, json) {
56 | callback(null);
57 | setTimeout((function() {
58 | this.switchService.getCharacteristic(Characteristic.On).updateValue(false, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
59 | }).bind(this), 2500);
60 | for (var i = 0; i < this.nukiLockAccessories.length; i++) {
61 | var nukiLockAccessory = this.nukiLockAccessories[i];
62 | var isLockedCached = nukiLockAccessory.nukiLock.getIsLockedCached();
63 | var newHomeKitStateLocked = isLockedCached ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
64 | var newHomeKitStateLockedTarget = isLockedCached ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
65 | nukiLockAccessory.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitStateLocked, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
66 | nukiLockAccessory.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateLockedTarget, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
67 | }
68 | for (var i = 0; i < this.nukiOpenerAccessories.length; i++) {
69 | var nukiOpenerAccessory = this.nukiOpenerAccessories[i];
70 |
71 | var modeCached = nukiOpenerAccessory.nukiLock.getModeCached();
72 | var isContinuousModeCached = modeCached === 3;
73 | var lastHomeKitStateContinuousModeCached = isContinuousModeCached ? Characteristic.LockCurrentState.UNSECURED : Characteristic.LockCurrentState.SECURED;
74 | var lastHomeKitStateContinuousModeTargetCached = isContinuousModeCached ? Characteristic.LockTargetState.UNSECURED : Characteristic.LockTargetState.SECURED;
75 | nukiOpenerAccessory.lockServiceContinuousMode.getCharacteristic(Characteristic.LockCurrentState).updateValue(lastHomeKitStateContinuousModeCached, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
76 | nukiOpenerAccessory.lockServiceContinuousMode.getCharacteristic(Characteristic.LockTargetState).updateValue(lastHomeKitStateContinuousModeTargetCached, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
77 |
78 | var isRingToOpenLockedCached = nukiOpenerAccessory.nukiLock.getIsLockedCached();
79 | if (isContinuousModeCached) {
80 | isRingToOpenLockedCached = false;
81 | }
82 | var lastHomeKitStateRingToOpenCached = isRingToOpenLockedCached ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
83 | var lastHomeKitStateRingToOpenTargetCached = isRingToOpenLockedCached ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
84 | nukiOpenerAccessory.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(lastHomeKitStateRingToOpenCached, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
85 | nukiOpenerAccessory.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(lastHomeKitStateRingToOpenTargetCached, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
86 |
87 | nukiOpenerAccessory.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
88 | nukiOpenerAccessory.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
89 | }
90 | }).bind(this);
91 | this.nukiBridge.refreshAllLocks(callbackWrapper);
92 | }
93 | }
94 | else {
95 | callback(null);
96 | }
97 | };
98 |
99 | NukiBridgeMaintainanceSwitchAccessory.prototype.getServices = function() {
100 | return [ this.switchService, this.informationService ];
101 | };
102 |
103 | module.exports = NukiBridgeMaintainanceSwitchAccessory;
--------------------------------------------------------------------------------
/src/homekit/NukiBridgePlatform.js:
--------------------------------------------------------------------------------
1 | const Constants = require('../Constants');
2 |
3 | var NukiBridgeMaintainanceSwitchAccessory = require('./NukiBridgeMaintainanceSwitchAccessory');
4 | var NukiOpenerAccessory = require('./NukiOpenerAccessory');
5 | var NukiLockAccessory = require('./NukiLockAccessory');
6 |
7 | var NukiBridge = require('../nuki/NukiBridge');
8 |
9 | var Service, Characteristic;
10 |
11 | function NukiBridgePlatform(log, config, homebridge) {
12 | Service = homebridge.hap.Service;
13 | Characteristic = homebridge.hap.Characteristic;
14 |
15 | this.log = log;
16 |
17 | var bridge_url = config["bridge_url"];
18 | var api_token = config["api_token"];
19 | var api_token_hashed = config["api_token_hashed"] || false;
20 |
21 | if(!bridge_url || bridge_url === "" || !api_token || api_token === "") {
22 | this.log("Nuki platform config is incomplete. You need to set 'bridge_url' and 'api_token'.");
23 | return;
24 | }
25 |
26 | this.lockactionMaxtries = config["lockaction_maxtries"];
27 | this.lockactionRetryDelay = config["lockaction_retrydelay"];
28 | if (this.lockactionMaxtries == null || this.lockactionMaxtries == "" || this.lockactionMaxtries < 0) {
29 | this.lockactionMaxtries = Constants.DEFAULT_MAX_TRIES_FOR_LOCK_ACTIONS;
30 | }
31 | if (this.lockactionRetryDelay == null || this.lockactionRetryDelay == "" || this.lockactionRetryDelay < 500) {
32 | this.lockactionRetryDelay = Constants.DEFAULT_DELAY_FOR_RETRY;
33 | }
34 |
35 | this.nukiBridge = new NukiBridge(homebridge, this.log, bridge_url, api_token, api_token_hashed, config["request_timeout_lockstate"], config["request_timeout_lockaction"], config["request_timeout_other"], config["cache_directory"], config["lock_state_mode"], config["webhook_server_ip_or_name"], config["webhook_port"], this.lockactionMaxtries, this.lockactionRetryDelay);
36 | this.locks = config["locks"] || [];
37 | this.openers = config["openers"] || [];
38 | this.addMaintainanceButtons = config["add_maintainance_buttons"] || false;
39 | };
40 |
41 | NukiBridgePlatform.prototype.accessories = function(callback) {
42 | var accessories = [];
43 | var nukiLocks = [];
44 | if(this.locks) {
45 | for (var i = 0; i < this.locks.length; i++) {
46 | var lockConfig = this.locks[i];
47 | if(!lockConfig["id"] || lockConfig["id"] === "" || !lockConfig["name"] || lockConfig["name"] === "") {
48 | this.log("Lock config '%s' is incomplete. You need to set 'id' and 'name'.", i);
49 | continue;
50 | }
51 | var lock = new NukiLockAccessory(Service, Characteristic, this.log, lockConfig, this.nukiBridge, this);
52 | accessories.push(lock);
53 | nukiLocks.push(lock);
54 | }
55 | }
56 | var nukiOpeners = [];
57 | if(this.openers) {
58 | for (var j = 0; j < this.openers.length; j++) {
59 | var openerConfig = this.openers[j];
60 | if(!openerConfig["id"] || openerConfig["id"] === "" || !openerConfig["name"] || openerConfig["name"] === "") {
61 | this.log("Opener config '%s' is incomplete. You need to set 'id' and 'name'.", j);
62 | continue;
63 | }
64 | var opener = new NukiOpenerAccessory(Service, Characteristic, this.log, openerConfig, this.nukiBridge, this);
65 | accessories.push(opener);
66 | nukiOpeners.push(opener);
67 | }
68 | }
69 | if (this.addMaintainanceButtons) {
70 | accessories.push(new NukiBridgeMaintainanceSwitchAccessory(Service, Characteristic, this.log, "maintainance-switch-reboot", "Nuki Bridge Reboot", this.nukiBridge, nukiLocks, nukiOpeners));
71 | accessories.push(new NukiBridgeMaintainanceSwitchAccessory(Service, Characteristic, this.log, "maintainance-switch-fwupdate", "Nuki Bridge Firmware Update", this.nukiBridge, nukiLocks, nukiOpeners));
72 | accessories.push(new NukiBridgeMaintainanceSwitchAccessory(Service, Characteristic, this.log, "maintainance-switch-refreshall", "Nuki Bridge Refresh All", this.nukiBridge, nukiLocks, nukiOpeners));
73 | }
74 | callback(accessories);
75 | };
76 |
77 | module.exports = NukiBridgePlatform;
--------------------------------------------------------------------------------
/src/homekit/NukiLockAccessory.js:
--------------------------------------------------------------------------------
1 | const Constants = require('../Constants');
2 |
3 | var NukiLock = require('../nuki/NukiLock');
4 |
5 | var Service, Characteristic;
6 |
7 | function NukiLockAccessory(ServiceParam, CharacteristicParam, log, config, nukiBridge, nukiBridgePlatform) {
8 | Service = ServiceParam;
9 | Characteristic = CharacteristicParam;
10 |
11 | this.log = log;
12 | this.id = config["id"];
13 | this.name = config["name"];
14 | this.usesDoorLatch = config["usesDoorLatch"] === true || false;
15 | this.usesDoorContactSensor = config["usesDoorContactSensor"] === true || false;
16 | this.preventLockingIfAlreadyLocked = config["preventLockingIfAlreadyLocked"] === true || false;
17 | this.nukiBridge = nukiBridge;
18 | this.nukiBridgePlatform = nukiBridgePlatform;
19 | this.deviceType = config["deviceType"];
20 |
21 | if (this.deviceType == null || this.deviceType == "") {
22 | this.deviceType = 0;
23 | }
24 |
25 | this.services = [];
26 |
27 | this.informationService = new Service.AccessoryInformation();
28 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "Nuki.io").setCharacteristic(Characteristic.Model, "Nuki.io Lock").setCharacteristic(Characteristic.SerialNumber, "Nuki.io-Id " + this.id);
29 | this.services.push(this.informationService);
30 |
31 | this.lockServiceUnlock = new Service.LockMechanism(this.name, this.name);
32 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getState.bind(this));
33 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).on('get', this.getState.bind(this)).on('set', this.setState.bind(this));
34 | this.services.push(this.lockServiceUnlock);
35 |
36 | if (this.usesDoorLatch) {
37 | this.lockServiceAlwaysUnlatch = new Service.LockMechanism(this.name + " ALWAYS Unlatch", this.name + " ALWAYS Unlatch");
38 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getStateAlwaysUnlatch.bind(this));
39 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockTargetState).on('get', this.getStateAlwaysUnlatch.bind(this)).on('set', this.setStateAlwaysUnlatch.bind(this));
40 | this.services.push(this.lockServiceAlwaysUnlatch);
41 |
42 | this.switchUnlatchAllowedService = new Service.Switch(this.name + " Unlatch Allowed");
43 | this.switchUnlatchAllowedService.getCharacteristic(Characteristic.On).on('get', this.getStateSwitchUnlatchAllowed.bind(this)).on('set', this.setStateSwitchUnlatchAllowed.bind(this));
44 | this.services.push(this.switchUnlatchAllowedService);
45 | }
46 | if (this.usesDoorContactSensor) {
47 | this.doorContactSensor = new Service.ContactSensor(this.name + " Contact Sensor");
48 | this.doorContactSensor.getCharacteristic(Characteristic.ContactSensorState).on('get', this.getStateContactSensor.bind(this));
49 | this.services.push(this.doorContactSensor);
50 | }
51 |
52 | this.battservice = new Service.BatteryService(this.name);
53 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).on('get', this.getBattery.bind(this));
54 | this.battservice.getCharacteristic(Characteristic.ChargingState).on('get', this.getCharging.bind(this));
55 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).on('get', this.getLowBatt.bind(this));
56 | this.services.push(this.battservice);
57 |
58 | var webHookCallback = (function(isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode, ringactionState) {
59 | var newHomeKitStateLocked = isLocked ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
60 | var newHomeKitStateLockedTarget = isLocked ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
61 | var newHomeKitStateBatteryCritical = batteryCritical ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
62 | var newHomeKitStateBatteryCharging = batteryCharging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING;
63 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitStateLocked, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
64 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateLockedTarget, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
65 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).updateValue(newHomeKitStateBatteryCritical, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
66 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).updateValue(batteryChargeState, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
67 | this.battservice.getCharacteristic(Characteristic.ChargingState).updateValue(newHomeKitStateBatteryCharging, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
68 | if (this.usesDoorContactSensor) {
69 | this.doorContactSensor.getCharacteristic(Characteristic.ContactSensorState).updateValue(contactClosed ? Characteristic.ContactSensorState.CONTACT_DETECTED : Characteristic.ContactSensorState.CONTACT_NOT_DETECTED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
70 | }
71 | this.log("HomeKit state change by webhook complete. New isLocked = '%s' and batteryCritical = '%s', battery charging = '%s', battery charge state = '%s' and contactClosed = '%s'.", isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed);
72 | }).bind(this);
73 |
74 | this.nukiLock = new NukiLock(this.log, nukiBridge, this.id, config["priority"], this.deviceType, webHookCallback);
75 |
76 | // no notification when homebridge start/restart, set LockCurrentState and
77 | // LockTargetState before first getState
78 | var isLockedCached = this.nukiLock.getIsLockedCached();
79 | var lastHomeKitStateLockedCached = isLockedCached ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
80 | var lastHomeKitStateLockedTargetCached = isLockedCached ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
81 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(lastHomeKitStateLockedTargetCached, undefined, null);
82 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(lastHomeKitStateLockedCached, undefined, null);
83 | if (this.usesDoorLatch) {
84 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, null);
85 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, null);
86 |
87 | var isUnlatchAllowed = this._isUnlatchAllowed();
88 | this.switchUnlatchAllowedService.getCharacteristic(Characteristic.On).updateValue(isUnlatchAllowed, undefined, null);
89 | }
90 | var isBatteryLowCached = this.nukiLock.getIsBatteryLowCached();
91 | var batteryChargingCached = this.nukiLock.getBatteryChargingCached();
92 | var batteryChargeStateCached = this.nukiLock.getBatteryChargeStateCached();
93 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).updateValue(isBatteryLowCached ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL, undefined, null);
94 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).updateValue(batteryChargeStateCached, undefined, null);
95 | this.battservice.getCharacteristic(Characteristic.ChargingState).updateValue(batteryChargingCached ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING, undefined, null);
96 | };
97 |
98 | NukiLockAccessory.prototype.getState = function(callback) {
99 | var callbackIsLocked = (function(err, isLocked) {
100 | callback(err, isLocked ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED);
101 | }).bind(this);
102 | this.nukiLock.isLocked(callbackIsLocked);
103 | };
104 |
105 | NukiLockAccessory.prototype.getStateContactSensor = function(callback) {
106 | var callbackIsContactClosed = (function(err, isContactClosed) {
107 | callback(err, isContactClosed ? Characteristic.ContactSensorState.CONTACT_DETECTED : Characteristic.ContactSensorState.CONTACT_NOT_DETECTED);
108 | }).bind(this);
109 | this.nukiLock.isContactClosed(callbackIsContactClosed);
110 | };
111 |
112 | NukiLockAccessory.prototype.getStateAlwaysUnlatch = function(callback) {
113 | callback(null, Characteristic.LockCurrentState.SECURED);
114 | };
115 |
116 | NukiLockAccessory.prototype.setStateAlwaysUnlatch = function(homeKitState, callback, context) {
117 | var doLock = homeKitState == Characteristic.LockTargetState.SECURED;
118 | var isUnlatchAllowed = this._isUnlatchAllowed();
119 | if (doLock || !isUnlatchAllowed) {
120 | if (!doLock && !isUnlatchAllowed) {
121 | this.log("Unlatching is set to not be allowed so nothing is executed and state will be switched back.");
122 | }
123 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, null);
124 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, null);
125 | if (callback) {
126 | callback(null);
127 | }
128 | }
129 | else {
130 | var lockStateChangeCallback = (function(params, err, json) {
131 | if (err && err.retryableError && params.lockTry < this.nukiBridgePlatform.lockactionMaxtries) {
132 | this.log("An error occured processing lock action. Will retry now...");
133 | var currentLockTry = params.lockTry;
134 | params.lockTry = params.lockTry + 1;
135 | setTimeout((function() {
136 | this.nukiLock.unlatch(lockStateChangeCallback);
137 | }).bind(this), this.nukiBridgePlatform.lockactionRetryDelay * currentLockTry);
138 | }
139 | else {
140 | if (err) {
141 | if (params.lockTry == 1) {
142 | this.log("An error occured processing lock action. Reason: %s", err);
143 | }
144 | else {
145 | this.log("An error occured processing lock action after retrying multiple times. Reason: %s", err);
146 | }
147 | }
148 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.UNSECURED, undefined, null);
149 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.UNSECURED, undefined, null);
150 | callback(null);
151 | setTimeout((function() {
152 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
153 | this.lockServiceAlwaysUnlatch.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
154 | this.log("HomeKit change for door latch back to locked state complete.");
155 | }).bind(this), 1000);
156 | this.log("HomeKit state change complete.");
157 | }
158 | }).bind(this, {
159 | lockTry : 1
160 | });
161 |
162 | this.nukiLock.unlatch(lockStateChangeCallback);
163 | }
164 | };
165 |
166 | NukiLockAccessory.prototype.setState = function(homeKitState, callback, context) {
167 | var doLock = homeKitState == Characteristic.LockTargetState.SECURED;
168 | var newHomeKitState = doLock ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
169 | var newHomeKitStateTarget = doLock ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
170 |
171 | var isLockedCached = this.nukiLock.getIsLockedCached();
172 | if(this.preventLockingIfAlreadyLocked && isLockedCached === doLock) {
173 | this.log("Prevented lock as preventLockingIfAlreadyLocked=true and lock is already locked.");
174 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
175 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
176 | if (callback) {
177 | callback(null);
178 | }
179 | return;
180 | }
181 |
182 | var lockStateChangeCallback = (function(params, err, json) {
183 | if (err && err.retryableError) {
184 | if (params.lockTry < this.nukiBridgePlatform.lockactionMaxtries) {
185 | this.log("An error occured processing lock action. Will retry now...");
186 | var currentLockTry = params.lockTry;
187 | params.lockTry = params.lockTry + 1;
188 | setTimeout((function() {
189 | if (doLock) {
190 | this.nukiLock.lock(lockStateChangeCallback);
191 | }
192 | else {
193 | this.nukiLock.unlock(lockStateChangeCallback);
194 | }
195 | }).bind(this), this.nukiBridgePlatform.lockactionRetryDelay * currentLockTry);
196 | }
197 | else {
198 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
199 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
200 | callback(err);
201 | this.log("An error occured processing lock action after retrying multiple times. Reason: %s", err);
202 | }
203 | }
204 | else {
205 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
206 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
207 | callback(null);
208 | if (err) {
209 | this.log("An error occured processing lock action. Reason: %s", err);
210 | }
211 | }
212 | this.log("HomeKit state change complete.");
213 | }).bind(this, {
214 | lockTry : 1
215 | });
216 |
217 | if (context === Constants.CONTEXT_FROM_NUKI_BACKGROUND) {
218 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
219 | this.lockServiceUnlock.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
220 | if (callback) {
221 | callback(null);
222 | }
223 | this.log("HomeKit state change complete from Background.");
224 | }
225 | else {
226 | if (doLock) {
227 | this.nukiLock.lock(lockStateChangeCallback);
228 | }
229 | else {
230 | this.nukiLock.unlock(lockStateChangeCallback);
231 | }
232 | }
233 | };
234 |
235 | NukiLockAccessory.prototype.getBattery = function(callback) {
236 | var getChargeStateCallback = (function(err, chargeState) {
237 | if (err) {
238 | this.log("An error occured retrieving battery status. Reason: %s", err);
239 | callback(err);
240 | }
241 | else {
242 | callback(null, chargeState);
243 | }
244 | }).bind(this);
245 | this.nukiLock.getChargeState(getChargeStateCallback);
246 | };
247 |
248 | NukiLockAccessory.prototype.getCharging = function(callback) {
249 | var getChargingCallback = (function(err, charging) {
250 | if (err) {
251 | this.log("An error occured retrieving battery status. Reason: %s", err);
252 | callback(err);
253 | }
254 | else {
255 | callback(null, charging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING);
256 | }
257 | }).bind(this);
258 | this.nukiLock.getCharging(getChargingCallback);
259 | };
260 |
261 | NukiLockAccessory.prototype.getLowBatt = function(callback) {
262 | var getLowBattCallback = (function(err, lowBattery) {
263 | if (err) {
264 | this.log("An error occured retrieving battery status. Reason: %s", err);
265 | callback(err);
266 | }
267 | else {
268 | callback(null, lowBattery ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL);
269 | }
270 | }).bind(this);
271 | this.nukiLock.getLowBatt(getLowBattCallback);
272 | };
273 |
274 | NukiLockAccessory.prototype.getStateSwitchUnlatchAllowed = function(callback) {
275 | this.log("Getting current state for 'SwitchUnlatchAllowed'...");
276 | var state = this._isUnlatchAllowed();
277 | callback(null, state);
278 | };
279 |
280 | NukiLockAccessory.prototype.setStateSwitchUnlatchAllowed = function(powerOn, callback) {
281 | this.log("Switch state for 'SwitchUnlatchAllowed' to '%s'...", powerOn);
282 | this.nukiBridge.storage.setItemSync(this._getSwitchUnlatchAllowedStorageKey(), powerOn);
283 | callback(null);
284 | };
285 |
286 | NukiLockAccessory.prototype._isUnlatchAllowed = function() {
287 | var state = this.nukiBridge.storage.getItemSync(this._getSwitchUnlatchAllowedStorageKey());
288 | if (state === undefined) {
289 | state = true;
290 | }
291 | return state;
292 | };
293 |
294 | NukiLockAccessory.prototype._getSwitchUnlatchAllowedStorageKey = function() {
295 | return 'bridge-' + this.nukiBridge.bridgeUrl + '-lock-' + this.nukiLock.instanceId + '-' + this.nukiLock.id + '-switch-unlatch-allowed-cache';
296 | };
297 |
298 | NukiLockAccessory.prototype.getServices = function() {
299 | return this.services;
300 | };
301 |
302 | module.exports = NukiLockAccessory;
--------------------------------------------------------------------------------
/src/homekit/NukiOpenerAccessory.js:
--------------------------------------------------------------------------------
1 | const Constants = require('../Constants');
2 |
3 | var NukiLock = require('../nuki/NukiLock');
4 |
5 | var Service, Characteristic;
6 |
7 | function NukiOpenerAccessory(ServiceParam, CharacteristicParam, log, config, nukiBridge, nukiBridgePlatform) {
8 | Service = ServiceParam;
9 | Characteristic = CharacteristicParam;
10 |
11 | this.log = log;
12 | this.id = config["id"];
13 | this.name = config["name"];
14 | this.disableRingToOpen = config["disableRingToOpen"] === true || false;
15 | this.disableContinuousMode = config["disableContinuousMode"] === true || false;
16 | this.nukiBridge = nukiBridge;
17 | this.nukiBridgePlatform = nukiBridgePlatform;
18 | this.deviceType = 2;
19 |
20 | this.informationService = new Service.AccessoryInformation();
21 | this.informationService.setCharacteristic(Characteristic.Manufacturer, "Nuki.io").setCharacteristic(Characteristic.Model, "Nuki.io Opener").setCharacteristic(Characteristic.SerialNumber, "Nuki.io-Id " + this.id);
22 |
23 | this.lockServiceOpen = new Service.LockMechanism(this.name, this.name);
24 | this.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getStateAlwaysUnlatch.bind(this));
25 | this.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).on('get', this.getStateAlwaysUnlatch.bind(this)).on('set', this.setStateAlwaysUnlatch.bind(this));
26 |
27 | if(!this.disableRingToOpen) {
28 | this.lockServiceRingToOpen = new Service.LockMechanism("Ring To Open " + this.name, "Ring To Open " + this.name);
29 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getStateRingToOpen.bind(this));
30 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).on('get', this.getStateRingToOpen.bind(this)).on('set', this.setState.bind(this, "unlock"));
31 | }
32 |
33 | if(!this.disableContinuousMode) {
34 | this.lockServiceContinuousMode = new Service.LockMechanism("Continous Mode " + this.name, "Continous Mode " + this.name);
35 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockCurrentState).on('get', this.getStateContinuousMode.bind(this));
36 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockTargetState).on('get', this.getStateContinuousMode.bind(this)).on('set', this.setState.bind(this, "lockngo"));
37 | }
38 |
39 | this.doorbellService = new Service.Doorbell("Doorbell " + this.name, "Doorbell " + this.name);
40 |
41 | this.doorbellEnablementSwitchService = new Service.Switch("Doorbell Enabled " + this.name);
42 | this.doorbellEnablementSwitchService.getCharacteristic(Characteristic.On).on('get', this.getDoorbellEnabled.bind(this)).on('set', this.setDoorbellEnabled.bind(this));
43 | this.doorbellEnablementSwitchService.getCharacteristic(Characteristic.On).updateValue(this._getDoorbellEnabled(), undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
44 |
45 | this.battservice = new Service.BatteryService(this.name);
46 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).on('get', this.getBattery.bind(this));
47 | this.battservice.getCharacteristic(Characteristic.ChargingState).on('get', this.getCharging.bind(this));
48 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).on('get', this.getLowBatt.bind(this));
49 |
50 | var webHookCallback = (function(isRingToOpenLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode, ringactionState) {
51 | var isContinuousMode = mode === 3;
52 | if(!this.disableContinuousMode) {
53 | var newHomeKitStateContinuousMode = isContinuousMode ? Characteristic.LockCurrentState.UNSECURED : Characteristic.LockCurrentState.SECURED;
54 | var newHomeKitStateContinuousModeTarget = isContinuousMode ? Characteristic.LockTargetState.UNSECURED : Characteristic.LockTargetState.SECURED;
55 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitStateContinuousMode, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
56 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateContinuousModeTarget, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
57 | }
58 |
59 | if (isContinuousMode) {
60 | isRingToOpenLocked = false;
61 | }
62 | if(!this.disableRingToOpen) {
63 | var newHomeKitStateRingToOpenLocked = isRingToOpenLocked ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
64 | var newHomeKitStateRingToOpenLockedTarget = isRingToOpenLocked ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
65 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitStateRingToOpenLocked, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
66 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateRingToOpenLockedTarget, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
67 | }
68 |
69 | var newHomeKitStateBatteryCritical = batteryCritical ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
70 | var newHomeKitStateBatteryCharging = batteryCharging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING;
71 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).updateValue(newHomeKitStateBatteryCritical, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
72 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).updateValue(batteryChargeState, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
73 | this.battservice.getCharacteristic(Characteristic.ChargingState).updateValue(newHomeKitStateBatteryCharging, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
74 |
75 | if(ringactionState === true && this._getDoorbellEnabled() === true) {
76 | this.doorbellService.updateCharacteristic(Characteristic.ProgrammableSwitchEvent, 0);
77 | }
78 | this.log("HomeKit state change by webhook complete. New isRingToOpenLocked = '%s' and batteryCritical = '%s', battery charging = '%s', battery charge state = '%s' and mode = '%s', ringactionState = '%s'.", isRingToOpenLocked, batteryCritical, batteryCharging, batteryChargeState, mode, ringactionState);
79 | }).bind(this);
80 |
81 | this.nukiLock = new NukiLock(this.log, nukiBridge, this.id, config["priority"], this.deviceType, webHookCallback);
82 |
83 | // no notification when homebridge start/restart, set LockCurrentState and
84 | // LockTargetState before first getState
85 |
86 | if(!this.disableRingToOpen) {
87 | var isRingToOpenLockedCached = this.nukiLock.getIsLockedCached();
88 | var lastHomeKitStateRingToOpenCached = isRingToOpenLockedCached ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
89 | var lastHomeKitStateRingToOpenTargetCached = isRingToOpenLockedCached ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
90 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(lastHomeKitStateRingToOpenTargetCached, undefined, null);
91 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(lastHomeKitStateRingToOpenCached, undefined, null);
92 | }
93 |
94 | var modeCached = this.nukiLock.getModeCached();
95 | var isContinuousModeCached = modeCached === 3;
96 | if(!this.disableContinuousMode) {
97 | var lastHomeKitStateContinuousModeCached = isContinuousModeCached ? Characteristic.LockCurrentState.UNSECURED : Characteristic.LockCurrentState.SECURED;
98 | var lastHomeKitStateContinuousModeTargetCached = isContinuousModeCached ? Characteristic.LockTargetState.UNSECURED : Characteristic.LockTargetState.SECURED;
99 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockTargetState).updateValue(lastHomeKitStateContinuousModeTargetCached, undefined, null);
100 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockCurrentState).updateValue(lastHomeKitStateContinuousModeCached, undefined, null);
101 | }
102 |
103 | this.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, null);
104 | this.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, null);
105 |
106 | var isBatteryLowCached = this.nukiLock.getIsBatteryLowCached();
107 | var batteryChargingCached = this.nukiLock.getBatteryChargingCached();
108 | var batteryChargeStateCached = this.nukiLock.getBatteryChargeStateCached();
109 | this.battservice.getCharacteristic(Characteristic.StatusLowBattery).updateValue(isBatteryLowCached ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL, undefined, null);
110 | this.battservice.getCharacteristic(Characteristic.BatteryLevel).updateValue(batteryChargeStateCached, undefined, null);
111 | this.battservice.getCharacteristic(Characteristic.ChargingState).updateValue(batteryChargingCached ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING, undefined, null);
112 | };
113 |
114 | NukiOpenerAccessory.prototype.getStateRingToOpen = function(callback) {
115 | var callbackIsLocked = (function(err, isLocked) {
116 | var modeCached = this.nukiLock.getModeCached();
117 | var isContinuousModeCached = modeCached === 3;
118 | if (isContinuousModeCached) {
119 | isLocked = false;
120 | }
121 | callback(err, isLocked ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED);
122 | }).bind(this);
123 | this.nukiLock.isLocked(callbackIsLocked);
124 | };
125 |
126 | NukiOpenerAccessory.prototype.getStateContinuousMode = function(callback) {
127 | var callbackIsLocked = (function(err, isLocked) {
128 | var modeCached = this.nukiLock.getModeCached();
129 | var isContinuousModeCached = modeCached === 3;
130 | callback(err, isContinuousModeCached ? Characteristic.LockCurrentState.UNSECURED : Characteristic.LockCurrentState.SECURED);
131 | }).bind(this);
132 | this.nukiLock.isLocked(callbackIsLocked);
133 | };
134 |
135 | NukiOpenerAccessory.prototype.getStateAlwaysUnlatch = function(callback) {
136 | callback(null, Characteristic.LockCurrentState.SECURED);
137 | };
138 |
139 | NukiOpenerAccessory.prototype.setStateAlwaysUnlatch = function(homeKitState, callback, context) {
140 | var doLock = homeKitState == Characteristic.LockTargetState.SECURED;
141 | if (doLock) {
142 | this.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, null);
143 | this.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, null);
144 | if (callback) {
145 | callback(null);
146 | }
147 | }
148 | else {
149 | var lockStateChangeCallback = (function(params, err, json) {
150 | if (err && err.retryableError && params.lockTry < this.nukiBridgePlatform.lockactionMaxtries) {
151 | this.log("An error occured processing open action. Will retry now...");
152 | var currentLockTry = params.lockTry;
153 | params.lockTry = params.lockTry + 1;
154 | setTimeout((function() {
155 | this.nukiLock.unlatch(lockStateChangeCallback);
156 | }).bind(this), this.nukiBridgePlatform.lockactionRetryDelay * currentLockTry);
157 | }
158 | else {
159 | if (err) {
160 | if (params.lockTry == 1) {
161 | this.log("An error occured processing open action. Reason: %s", err);
162 | }
163 | else {
164 | this.log("An error occured processing open action after retrying multiple times. Reason: %s", err);
165 | }
166 | }
167 | this.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.UNSECURED, undefined, null);
168 | this.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.UNSECURED, undefined, null);
169 | callback(null);
170 | setTimeout((function() {
171 | this.lockServiceOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
172 | this.lockServiceOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
173 | this.log("HomeKit change for door opener back to locked state complete.");
174 | }).bind(this), 1000);
175 | this.log("HomeKit state change complete.");
176 | }
177 | }).bind(this, {
178 | lockTry : 1
179 | });
180 |
181 | this.nukiLock.unlatch(lockStateChangeCallback);
182 | }
183 | };
184 |
185 | NukiOpenerAccessory.prototype.setState = function(unlockType, homeKitState, callback, context) {
186 | var doLock = homeKitState == Characteristic.LockTargetState.SECURED;
187 | var newHomeKitState = doLock ? Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
188 | var newHomeKitStateTarget = doLock ? Characteristic.LockTargetState.SECURED : Characteristic.LockTargetState.UNSECURED;
189 | // this.log("S E T S T A T E: unlockType = %s, doLock = %s,homeKitState = %s",
190 | // unlockType, doLock, homeKitState);
191 | if (unlockType !== "lockngo") {
192 | var modeCached = this.nukiLock.getModeCached();
193 | var isContinuousModeCached = modeCached === 3;
194 | if (isContinuousModeCached) {
195 | if (doLock) {
196 | callback(null);
197 | if(!this.disableRingToOpen) {
198 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.SECURED, undefined, null);
199 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.SECURED, undefined, null);
200 | setTimeout((function() {
201 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(Characteristic.LockTargetState.UNSECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
202 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(Characteristic.LockCurrentState.UNSECURED, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
203 | this.log("HomeKit change for ring to open back to unlock state complete as continous mode is still active.");
204 | }).bind(this), 1000);
205 | }
206 | }
207 | else {
208 | callback(null);
209 | }
210 | return;
211 | }
212 | }
213 |
214 | var updateStates = (function(unlockType, doLock, newHomeKitState, newHomeKitStateTarget) {
215 | if (unlockType === "lockngo") {
216 | if(!this.disableContinuousMode) {
217 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
218 | this.lockServiceContinuousMode.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
219 | }
220 | if (!doLock || this.nukiLock.getIsLockedCached()) {
221 | if(!this.disableRingToOpen) {
222 | setTimeout((function() {
223 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
224 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, Constants.CONTEXT_FROM_NUKI_BACKGROUND);
225 | this.log("HomeKit change for ring to open back to unlock state complete as continous mode is still active.");
226 | }).bind(this), 1000);
227 | }
228 | }
229 | }
230 | else if(!this.disableRingToOpen) {
231 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockTargetState).updateValue(newHomeKitStateTarget, undefined, null);
232 | this.lockServiceRingToOpen.getCharacteristic(Characteristic.LockCurrentState).updateValue(newHomeKitState, undefined, null);
233 | }
234 | }).bind(this);
235 |
236 | var lockStateChangeCallback = (function(params, err, json) {
237 | if (err && err.retryableError) {
238 | if (params.lockTry < this.nukiBridgePlatform.lockactionMaxtries) {
239 | this.log("An error occured processing lock action. Will retry now...");
240 | var currentLockTry = params.lockTry;
241 | params.lockTry = params.lockTry + 1;
242 | setTimeout((function() {
243 | if (unlockType === "lockngo") {
244 | if (doLock) {
245 | this.nukiLock.lockNGoUnlatch(lockStateChangeCallback);
246 | }
247 | else {
248 | this.nukiLock.lockNGo(lockStateChangeCallback);
249 | }
250 | }
251 | else {
252 | if (doLock) {
253 | this.nukiLock.lock(lockStateChangeCallback);
254 | }
255 | else {
256 | this.nukiLock.unlock(lockStateChangeCallback);
257 | }
258 | }
259 | }).bind(this), this.nukiBridgePlatform.lockactionRetryDelay * currentLockTry);
260 | }
261 | else {
262 | updateStates(unlockType, doLock, newHomeKitState, newHomeKitStateTarget);
263 | callback(err);
264 | this.log("An error occured processing lock action after retrying multiple times. Reason: %s", err);
265 | }
266 | }
267 | else {
268 | updateStates(unlockType, doLock, newHomeKitState, newHomeKitStateTarget);
269 | callback(null);
270 | if (err) {
271 | this.log("An error occured processing lock action. Reason: %s", err);
272 | }
273 | }
274 | this.log("HomeKit state change complete.");
275 | }).bind(this, {
276 | lockTry : 1
277 | });
278 |
279 | if (context === Constants.CONTEXT_FROM_NUKI_BACKGROUND) {
280 | updateStates(unlockType, doLock, newHomeKitState, newHomeKitStateTarget);
281 | if (callback) {
282 | callback(null);
283 | }
284 | this.log("HomeKit state change complete from Background.");
285 | }
286 | else {
287 | if (unlockType === "lockngo") {
288 | if (doLock) {
289 | this.nukiLock.lockNGoUnlatch(lockStateChangeCallback);
290 | }
291 | else {
292 | this.nukiLock.lockNGo(lockStateChangeCallback);
293 | }
294 | }
295 | else {
296 | if (doLock) {
297 | this.nukiLock.lock(lockStateChangeCallback);
298 | }
299 | else {
300 | this.nukiLock.unlock(lockStateChangeCallback);
301 | }
302 | }
303 | }
304 | };
305 |
306 | NukiOpenerAccessory.prototype.getBattery = function(callback) {
307 | var getChargeStateCallback = (function(err, chargeState) {
308 | if (err) {
309 | this.log("An error occured retrieving battery status. Reason: %s", err);
310 | callback(err);
311 | }
312 | else {
313 | callback(null, chargeState);
314 | }
315 | }).bind(this);
316 | this.nukiLock.getChargeState(getChargeStateCallback);
317 | };
318 |
319 | NukiOpenerAccessory.prototype.getCharging = function(callback) {
320 | var getChargingCallback = (function(err, charging) {
321 | if (err) {
322 | this.log("An error occured retrieving battery status. Reason: %s", err);
323 | callback(err);
324 | }
325 | else {
326 | callback(null, charging ? Characteristic.ChargingState.CHARGING : Characteristic.ChargingState.NOT_CHARGING);
327 | }
328 | }).bind(this);
329 | this.nukiLock.getCharging(getChargingCallback);
330 | };
331 |
332 | NukiOpenerAccessory.prototype.getLowBatt = function(callback) {
333 | var getLowBattCallback = (function(err, lowBattery) {
334 | if (err) {
335 | this.log("An error occured retrieving battery status. Reason: %s", err);
336 | callback(err);
337 | }
338 | else {
339 | callback(null, lowBattery ? Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW : Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL);
340 | }
341 | }).bind(this);
342 | this.nukiLock.getLowBatt(getLowBattCallback);
343 | };
344 |
345 | NukiOpenerAccessory.prototype._getDoorbellEnabledStorageKey = function _getDoorbellEnabledStorageKey() {
346 | return 'bridge-' + this.nukiBridge.bridgeUrl + '-doorbellenabled-' + this.id + '-cache';
347 | };
348 |
349 | NukiOpenerAccessory.prototype._getDoorbellEnabled = function() {
350 | var doorbellEnabledCache = this.nukiBridge.storage.getItemSync(this._getDoorbellEnabledStorageKey());
351 | if (doorbellEnabledCache === undefined) {
352 | doorbellEnabledCache = true;
353 | }
354 | return doorbellEnabledCache;
355 | };
356 |
357 | NukiOpenerAccessory.prototype.getDoorbellEnabled = function(callback) {
358 | this.log.debug("Getting current state for '%s'...", this.id);
359 | callback(null, this._getDoorbellEnabled());
360 | };
361 |
362 | NukiOpenerAccessory.prototype.setDoorbellEnabled = function(enabled, callback, context) {
363 | this.log("Switch state for '%s'...", this.id);
364 | this.nukiBridge.storage.setItemSync(this._getDoorbellEnabledStorageKey(), enabled);
365 | callback(null);
366 | };
367 |
368 | NukiOpenerAccessory.prototype.getServices = function() {
369 | var services = [ this.lockServiceOpen, this.informationService, this.doorbellService, this.doorbellEnablementSwitchService, this.battservice ];
370 | if(!this.disableRingToOpen) {
371 | services.push(this.lockServiceRingToOpen);
372 | }
373 | if(!this.disableContinuousMode) {
374 | services.push(this.lockServiceContinuousMode);
375 | }
376 | return services;
377 | };
378 |
379 | module.exports = NukiOpenerAccessory;
--------------------------------------------------------------------------------
/src/nuki/NukiBridge.js:
--------------------------------------------------------------------------------
1 | var request = require("request");
2 | var http = require('http');
3 | var crypto = require('crypto');
4 |
5 | const Constants = require('../Constants');
6 |
7 | function NukiBridge(homebridge, log, bridgeUrl, apiToken, apiTokenHashed, requestTimeoutLockState, requestTimeoutLockAction, requestTimeoutOther, cacheDirectory, lockStateMode, webHookServerIpOrName, webHookServerPort, lockactionMaxtries, lockactionRetryDelay) {
8 | this.log = log;
9 | this.bridgeUrl = bridgeUrl;
10 | if (this.bridgeUrl.toLowerCase().lastIndexOf("http://", 0) === -1) {
11 | this.bridgeUrl = "http://" + this.bridgeUrl;
12 | }
13 | if (this.bridgeUrl.lastIndexOf("/") === this.bridgeUrl.length - 1) {
14 | this.bridgeUrl = this.bridgeUrl.slice(0, -1);
15 | }
16 | this.log("Initializing Nuki bridge '%s'...", this.bridgeUrl);
17 | this.apiToken = apiToken;
18 | this.apiTokenHashed = apiTokenHashed;
19 | this.requestTimeoutLockState = requestTimeoutLockState;
20 | this.requestTimeoutLockAction = requestTimeoutLockAction;
21 | this.requestTimeoutOther = requestTimeoutOther;
22 | this.cacheDirectory = cacheDirectory;
23 | this.lockStateMode = lockStateMode;
24 | this.webHookServerIpOrName = webHookServerIpOrName;
25 | this.webHookServerPort = webHookServerPort;
26 | this.lockactionMaxtries = lockactionMaxtries;
27 | this.lockactionRetryDelay = lockactionRetryDelay;
28 | if (this.requestTimeoutLockState == null || this.requestTimeoutLockState == "" || this.requestTimeoutLockState < 1) {
29 | this.requestTimeoutLockState = Constants.DEFAULT_REQUEST_TIMEOUT_LOCK_STATE;
30 | }
31 | if (this.requestTimeoutLockAction == null || this.requestTimeoutLockAction == "" || this.requestTimeoutLockAction < 1) {
32 | this.requestTimeoutLockAction = Constants.DEFAULT_REQUEST_TIMEOUT_LOCK_ACTION;
33 | }
34 | if (this.requestTimeoutOther == null || this.requestTimeoutOther == "" || this.requestTimeoutOther < 1) {
35 | this.requestTimeoutOther = Constants.DEFAULT_REQUEST_TIMEOUT_OTHER;
36 | }
37 | if (this.cacheDirectory == null || this.cacheDirectory == "") {
38 | this.cacheDirectory = homebridge.user.storagePath() + "/" + Constants.DEFAULT_CACHE_DIRECTORY_NAME;
39 | }
40 | if (this.lockStateMode == null || this.lockStateMode == "") {
41 | this.lockStateMode = Constants.LOCK_STATE_MODE_REQUEST_LOCKSTATE;
42 | }
43 | if (this.webHookServerPort == null || this.webHookServerPort == "") {
44 | this.webHookServerPort = Constants.DEFAULT_WEBHOOK_SERVER_PORT;
45 | }
46 |
47 | if ((this.webHookServerIpOrName == null || this.webHookServerIpOrName == "") && this.lockStateMode === Constants.LOCK_STATE_MODE_ONLY_CACHE) {
48 | this.log("Lock state mode 1 can only be used with webhooks configured. Yout need to enter a valid webhook server ip/name or use lock state mode 0 otherwise no lock state change will be recognized.");
49 | }
50 |
51 | this.storage = require('node-persist');
52 | this.storage.initSync({
53 | dir : this.cacheDirectory
54 | });
55 |
56 | this.runningRequest = false;
57 | this.queue = [];
58 | this.locks = [];
59 |
60 | if (this.webHookServerIpOrName && this.webHookServerIpOrName !== "") {
61 | this.webHookUrl = this.webHookServerIpOrName + ":" + this.webHookServerPort + "/";
62 | if (this.webHookUrl.toLowerCase().lastIndexOf("http://", 0) === -1) {
63 | this.webHookUrl = "http://" + this.webHookUrl;
64 | }
65 | this._createWebHookServer(this.log, this.webHookServerPort);
66 | this._addWebhookToBridge();
67 | }
68 |
69 | this.log("Initialized Nuki bridge.");
70 | };
71 |
72 | NukiBridge.prototype._createWebHookServer = function _createWebHookServer(log, webHookServerPort) {
73 | http.createServer((function(request, response) {
74 | var body = [];
75 | request.on('error', function(err) {
76 | log("[ERROR Nuki WebHook Server] Reason: %s.", err);
77 | }).on('data', function(chunk) {
78 | body.push(chunk);
79 | }).on('end', (function() {
80 | body = Buffer.concat(body).toString();
81 |
82 | response.on('error', function(err) {
83 | log("[ERROR Nuki WebHook Server] Reason: %s.", err);
84 | });
85 |
86 | response.statusCode = 200;
87 | response.setHeader('Content-Type', 'application/json');
88 |
89 | var json = JSON.parse(body);
90 | if (!json.nukiId || !json.state) {
91 | response.statusCode = 404;
92 | response.setHeader("Content-Type", "text/plain");
93 | var errorText = "[ERROR Nuki WebHook Server] No nukiId or state or batteryCritical in request.";
94 | log(errorText);
95 | response.write(errorText);
96 | response.end();
97 | }
98 | else {
99 | var nukiId = json.nukiId + "";
100 | var state = json.state;
101 | var batteryCritical = json.batteryCritical === true || json.batteryCritical === "true";
102 | var batteryCharging = json.batteryCharging === true || json.batteryCharging === "true";
103 | var batteryChargeState = json.batteryChargeState ? json.batteryChargeState: batteryCritical ? Constants.BATTERY_LOW : Constants.BATTERY_FULL;
104 | var contactClosed = json.doorsensorState !== 3;
105 | var mode = json.mode;
106 | var ringactionState = json.ringactionState === true || json.ringactionState === "true";
107 | var lock = this._getLock(nukiId);
108 | if (lock == null) {
109 | response.setHeader("Content-Type", "text/plain");
110 | var infoText = "[INFO Nuki WebHook Server] No lock found for nukiId '" + nukiId + "'.";
111 | log(infoText);
112 | response.write(infoText);
113 | response.end();
114 | }
115 | else {
116 | var responseBody = {
117 | success : true
118 | };
119 | var isLocked = lock._isLocked(state);
120 | lock._setLockCache(isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode);
121 | log("[INFO Nuki WebHook Server] Updated lock state from webhook to isLocked = '%s' (Nuki state '%s' ) for lock '%s' (instance id '%s') with batteryCritical = '%s', battery charging = '%s', battery charge state = '%s', contactClosed = '%s' and mode = '%s', ringactionState = '%s'.", isLocked, state, lock.id, lock.instanceId, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode, ringactionState);
122 | lock.webHookCallback(isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode, ringactionState);
123 | response.write(JSON.stringify(responseBody));
124 | response.end();
125 | }
126 | }
127 | }).bind(this));
128 | }).bind(this)).listen(webHookServerPort, "0.0.0.0");
129 | this.log("Started server for webhooks on port '%s'.", webHookServerPort);
130 | };
131 |
132 | NukiBridge.prototype._addWebhookToBridge = function _addWebhookToBridge() {
133 | this.log("Adding webhook for plugin to bridge...");
134 | var callbackWebhookList = (function(params, err, json) {
135 | if (err && err.retryableError && params.getWebhookTry < this.lockactionMaxtries) {
136 | this.log("An error occured retrieving callbacks. Will retry now...");
137 | var currentWebhookTry = params.getWebhookTry;
138 | params.getWebhookTry = params.getWebhookTry + 1;
139 | setTimeout((function() {
140 | this._getCallbacks(callbackWebhookList);
141 | }).bind(this), this.lockactionRetryDelay * currentWebhookTry);
142 | }
143 | else {
144 | if (err) {
145 | if (params.getWebhookTry == 1) {
146 | throw new Error("Request for webhooks failed: " + err);
147 | }
148 | else {
149 | throw new Error("Request for webhooks failed after retrying multiple times: " + err);
150 | }
151 | }
152 | else if (json) {
153 | var callbacks = json.callbacks;
154 | var webhookExists = false;
155 | for (var i = 0; i < callbacks.length; i++) {
156 | var callback = callbacks[i];
157 | if (callback.url === this.webHookUrl) {
158 | webhookExists = true;
159 | break;
160 | }
161 | }
162 | if (webhookExists) {
163 | this.log("Webhook for plugin already exists.");
164 | }
165 | else {
166 | this._addCallback();
167 | }
168 | }
169 | }
170 | }).bind(this, {
171 | getWebhookTry : 1
172 | });
173 | this._getCallbacks(callbackWebhookList);
174 | };
175 |
176 | NukiBridge.prototype._getCallbacks = function _getCallbacks(callback, doRequest) {
177 | if (!this.runningRequest && doRequest) {
178 | this._sendRequest("/callback/list", {
179 | }, this.requestTimeoutOther, callback);
180 | }
181 | else {
182 | this._addToQueue({
183 | callbackWebhookList : callback
184 | });
185 | }
186 | };
187 |
188 | NukiBridge.prototype._addCallback = function _addCallback(doRequest) {
189 | if (!this.runningRequest && doRequest) {
190 | var callback = (function(params, err, json) {
191 | if (err && err.retryableError && params.addWebhookTry < this.lockactionMaxtries) {
192 | this.log("An error occured adding callback. Will retry now...");
193 | var currentWebhookTry = params.addWebhookTry;
194 | params.addWebhookTry = params.addWebhookTry + 1;
195 | setTimeout((function() {
196 | this._sendRequest("/callback/add", {
197 | url : this.webHookUrl
198 | }, this.requestTimeoutOther, callback);
199 | }).bind(this), this.lockactionRetryDelay * currentWebhookTry);
200 | }
201 | else {
202 | if (err) {
203 | if (params.getWebhookTry == 1) {
204 | throw new Error("Adding webhook failed: " + err);
205 | }
206 | else {
207 | throw new Error("Adding webhook failed after retrying multiple times: " + err);
208 | }
209 | }
210 | else {
211 | this.log("Webhook for plugin added.");
212 | }
213 | }
214 | }).bind(this, {
215 | addWebhookTry : 1
216 | });
217 | this._sendRequest("/callback/add", {
218 | url : this.webHookUrl
219 | }, this.requestTimeoutOther, callback);
220 | }
221 | else {
222 | this._addToQueue({
223 | callbackWebhookAdd : true
224 | });
225 | }
226 | };
227 |
228 | NukiBridge.prototype.reboot = function reboot(callback, doRequest) {
229 | if (!this.runningRequest && doRequest) {
230 | var callbackWrapper = (function(err, json) {
231 | setTimeout((function() {
232 | callback(err, json);
233 | }).bind(this), Constants.REBOOT_WAIT_TIME);
234 | }).bind(this);
235 | this._sendRequest("/reboot", {
236 | }, this.requestTimeoutOther, callbackWrapper);
237 | }
238 | else {
239 | this._addToQueue({
240 | callbackReboot : callback
241 | });
242 | }
243 | };
244 |
245 | NukiBridge.prototype.updateFirmware = function updateFirmware(callback, doRequest) {
246 | if (!this.runningRequest && doRequest) {
247 | var callbackWrapper = (function(err, json) {
248 | setTimeout((function() {
249 | callback(err, json);
250 | }).bind(this), Constants.REBOOT_WAIT_TIME);
251 | }).bind(this);
252 | this._sendRequest("/fwupdate", {
253 | }, this.requestTimeoutOther, callbackWrapper);
254 | }
255 | else {
256 | this._addToQueue({
257 | callbackFirmware : callback
258 | });
259 | }
260 | };
261 |
262 | NukiBridge.prototype.refreshAllLocks = function refreshAllLocks(callback) {
263 | var singleLockCallback = (function(params, err, json) {
264 | params.locksChecked = params.locksChecked + 1;
265 | if (params.locksChecked === params.locksToCheckNum) {
266 | callback();
267 | }
268 | }).bind(this, {
269 | locksToCheckNum : this.locks.length,
270 | locksChecked : 0
271 | });
272 | for (var i = 0; i < this.locks.length; i++) {
273 | var lockToCheck = this.locks[i];
274 | lockToCheck.isLocked(singleLockCallback, true);
275 | }
276 | };
277 |
278 | NukiBridge.prototype._addLock = function _addLock(nukiLock) {
279 | nukiLock.instanceId = this.locks.length;
280 | this.locks.push(nukiLock);
281 | };
282 |
283 | NukiBridge.prototype._getLock = function _getLock(id) {
284 | for (var i = 0; i < this.locks.length; i++) {
285 | var lock = this.locks[i];
286 | if (lock.id === id) {
287 | return lock;
288 | }
289 | }
290 | return null;
291 | };
292 |
293 | NukiBridge.prototype._lockState = function _lockState(nukiLock, callbacks /*
294 | * (err,
295 | * json)
296 | */, doRequest) {
297 | if (!this.runningRequest && doRequest) {
298 | var singleCallBack = (function(err, json) {
299 | for (var i = 0; i < callbacks.length; i++) {
300 | callbacks[i](err, json);
301 | }
302 | }).bind(this);
303 | this._sendRequest("/lockState", {
304 | nukiId : nukiLock.id,
305 | deviceType : nukiLock.deviceType
306 | }, this.requestTimeoutLockState, singleCallBack);
307 | }
308 | else {
309 | this._addToQueue({
310 | nukiLock : nukiLock,
311 | callbacksLockState : callbacks
312 | });
313 | }
314 | };
315 |
316 | NukiBridge.prototype._lastKnownlockState = function _lastKnownlockState(nukiLock, callbacks /*
317 | * (err,
318 | * json)
319 | */, doRequest) {
320 | if (!this.runningRequest && doRequest) {
321 | var singleCallBack = (function(err, json) {
322 | if (!err && !json) {
323 | err = new Error("Error retrieving last known lock state.");
324 | }
325 | if (err) {
326 | for (var j = 0; j < callbacks.length; j++) {
327 | callbacks[j](err, json);
328 | }
329 | }
330 | else {
331 | for (var k = 0; k < callbacks.length; k++) {
332 | var lastKnownlockStateCallback = callbacks[k];
333 | var callbackNukiId = lastKnownlockStateCallback.nukiLock.id;
334 | var lockErr = new Error("Error retrieving last known lock state for '" + callbackNukiId + "'.");
335 | var stateJson = null;
336 | for (var i = 0; i < json.length; i++) {
337 | var jsonLock = json[i];
338 | if (jsonLock.nukiId + "" === callbackNukiId) {
339 | stateJson = jsonLock.lastKnownState;
340 | lockErr = null;
341 | break;
342 | }
343 | }
344 | lastKnownlockStateCallback(lockErr, stateJson);
345 | }
346 | }
347 | }).bind(this);
348 | this._sendRequest("/list", {
349 | }, this.requestTimeoutOther, singleCallBack);
350 | }
351 | else {
352 | this._addToQueue({
353 | nukiLock : nukiLock,
354 | callbacksLastKnownLockState : callbacks
355 | });
356 | }
357 | };
358 |
359 | NukiBridge.prototype._lockAction = function _lockAction(nukiLock, lockAction, callback /*
360 | * (err,
361 | * json)
362 | */, doRequest) {
363 | this.log("Temp debug log: function _lockAction called: doRequest: '%s', runningRequest: '%s'.",this.runningRequest, doRequest);
364 | if (!this.runningRequest, doRequest) {
365 | this.log("Process lock action '%s' for Nuki lock '%s' (instance id '%s') on Nuki bridge '%s'.", lockAction, nukiLock.id, nukiLock.instanceId, this.bridgeUrl);
366 | this._sendRequest("/lockAction", {
367 | nukiId : nukiLock.id,
368 | deviceType : nukiLock.deviceType,
369 | action : lockAction
370 | }, this.requestTimeoutLockAction, callback);
371 | }
372 | else {
373 | this.log("Temp debug log: function _lockAction called: added to queue");
374 | this._addToQueue({
375 | nukiLock : nukiLock,
376 | lockAction : lockAction,
377 | callback : callback
378 | });
379 | }
380 | };
381 |
382 | NukiBridge.prototype._sendRequest = function _sendRequest(entryPoint, queryObject, requestTimeout, callback /*
383 | * (err,
384 | * json)
385 | */) {
386 | var toBridgeUrl = this.bridgeUrl;
387 | if(!queryObject) {
388 | queryObject = {}
389 | }
390 | if(this.apiTokenHashed === true) {
391 | var currentTs = new Date().toISOString().replace(/[.]\d+/, '');
392 | var randomNum = Math.floor(Math.random() * 65535) + 1 ;
393 | var toHash = currentTs+","+randomNum+","+this.apiToken;
394 | var hash = crypto.createHash('sha256').update(toHash).digest('hex');
395 | queryObject.ts = currentTs;
396 | queryObject.rnr = randomNum;
397 | queryObject.hash = hash;
398 | }
399 | else {
400 | queryObject.token = this.apiToken;
401 | }
402 |
403 | if (queryObject.deviceType === 2 && Constants.DUMMY_BRIDGE_FOR_OPENER === true) {
404 | toBridgeUrl = "http://10.0.1.108:8881";
405 | }
406 | this.log("Send request to Nuki bridge '%s' on '%s' with '%s'.", toBridgeUrl, entryPoint, JSON.stringify(queryObject));
407 | this.runningRequest = true;
408 | request.get({
409 | url : toBridgeUrl + entryPoint,
410 | qs : queryObject,
411 | timeout : requestTimeout
412 | }, (function(err, response, body) {
413 | var statusCode = response && response.statusCode ? response.statusCode : -1;
414 | this.log("Request to Nuki bridge '%s' finished with status code '%s' and body '%s'.", toBridgeUrl, statusCode, body, err);
415 | if (!err && statusCode == 200) {
416 | var json = {};
417 | if (body !== "") {
418 | json = JSON.parse(body);
419 | }
420 | var success = json.success;
421 | if (json.hasOwnProperty('success')) {
422 | if (success == "true" || success == true) {
423 | callback(null, json);
424 | }
425 | else {
426 | var nukiUnsuccessfulError = new Error("Request to Nuki bridge was not succesful. (statusCode=200, nukiUnsuccessfulError=true, retryableError=true)");
427 | nukiUnsuccessfulError.nukiUnsuccessfulError = true;
428 | nukiUnsuccessfulError.retryableError = true;
429 | callback(nukiUnsuccessfulError);
430 | }
431 | }
432 | else {
433 | callback(null, json);
434 | }
435 | }
436 | else if (statusCode == 503) {
437 | var nukiRetryableError = new Error("Request to Nuki bridge was not succesful. (statusCode=503, nukiUnsuccessfulError=false, retryableError=true)");
438 | nukiRetryableError.nukiUnsuccessfulError = false;
439 | nukiRetryableError.retryableError = true;
440 | callback(nukiRetryableError);
441 | }
442 | else {
443 | callback(err || new Error("Request to Nuki bridge was not succesful."));
444 | }
445 | this.runningRequest = false;
446 | this._processNextQueueEntry();
447 | }).bind(this));
448 | };
449 |
450 | NukiBridge.prototype._addToQueue = function _addToQueue(queueEntry) {
451 | var wasReplaced = this._replaceQueueEntryForLockAction(queueEntry);
452 | var wasAddedToLastState = this._addLockStateRequestCallbacksToExisting(queueEntry);
453 | var wasAddedToLastKnownState = this._addLastKnownLockStateRequestCallbacksToExisting(queueEntry);
454 | if (!wasReplaced && !wasAddedToLastState && !wasAddedToLastKnownState) {
455 | this.queue.push(queueEntry);
456 | }
457 |
458 | this.queue.sort(function(queueEntry1, queueEntry2) {
459 | if (!queueEntry1.nukiLock || !queueEntry2.nukiLock) {
460 | return -1;
461 | }
462 | return queueEntry1.nukiLock.priority - queueEntry2.nukiLock.priority;
463 | });
464 |
465 | setTimeout((function() {
466 | if (!this.runningRequest) {
467 | this._processNextQueueEntry();
468 | }
469 | }).bind(this), 500);
470 | };
471 |
472 | NukiBridge.prototype._replaceQueueEntryForLockAction = function _replaceQueueEntryForLockAction(queueEntry) {
473 | var wasReplaced = false;
474 | for (var i = 0; i < this.queue.length; i++) {
475 | var alreadyQueuedEntry = this.queue[i];
476 | var sameLock = queueEntry.nukiLock && alreadyQueuedEntry.nukiLock && queueEntry.nukiLock.id == alreadyQueuedEntry.nukiLock.id;
477 | var bothLockAction = queueEntry.lockAction && alreadyQueuedEntry.lockAction;
478 | var needsReplace = sameLock && bothLockAction;
479 | if (needsReplace) {
480 | wasReplaced = true;
481 | this.queue[i] = queueEntry;
482 | alreadyQueuedEntry.callback(new Error("Request to Nuki bridge for locking was canceled due to newer lock request."));
483 | }
484 | }
485 | return wasReplaced;
486 | };
487 |
488 | NukiBridge.prototype._addLockStateRequestCallbacksToExisting = function _addLockStateRequestCallbacksToExisting(queueEntry) {
489 | var wasAdded = false;
490 | for (var i = 0; i < this.queue.length; i++) {
491 | var alreadyQueuedEntry = this.queue[i];
492 | var sameLock = queueEntry.nukiLock && alreadyQueuedEntry.nukiLock && queueEntry.nukiLock.id == alreadyQueuedEntry.nukiLock.id;
493 | var bothLockState = queueEntry.callbacksLockState && alreadyQueuedEntry.callbacksLockState;
494 | var addCallbacks = sameLock && bothLockState;
495 | if (addCallbacks) {
496 | wasAdded = true;
497 | alreadyQueuedEntry.callbacksLockState = alreadyQueuedEntry.callbacksLockState.concat(queueEntry.callbacksLockState);
498 | }
499 | }
500 | return wasAdded;
501 | };
502 |
503 | NukiBridge.prototype._addLastKnownLockStateRequestCallbacksToExisting = function _addLastKnownLockStateRequestCallbacksToExisting(queueEntry) {
504 | var wasAdded = false;
505 | for (var i = 0; i < this.queue.length; i++) {
506 | var alreadyQueuedEntry = this.queue[i];
507 | var bothLastKnownLockState = queueEntry.callbacksLastKnownLockState && alreadyQueuedEntry.callbacksLastKnownLockState;
508 | var addCallbacks = bothLastKnownLockState;
509 | if (addCallbacks) {
510 | wasAdded = true;
511 | alreadyQueuedEntry.callbacksLastKnownLockState = alreadyQueuedEntry.callbacksLastKnownLockState.concat(queueEntry.callbacksLastKnownLockState);
512 | }
513 | }
514 | return wasAdded;
515 | };
516 |
517 | NukiBridge.prototype._processNextQueueEntry = function _processNextQueueEntry() {
518 | if (this.queue.length > 0) {
519 | var queueEntry = this.queue.shift();
520 | var doRequest = true;
521 | if (queueEntry.nukiLock) {
522 | if (queueEntry.lockAction) {
523 | this._lockAction(queueEntry.nukiLock, queueEntry.lockAction, queueEntry.callback, doRequest);
524 | }
525 | else if (queueEntry.callbacksLockState) {
526 | this._lockState(queueEntry.nukiLock, queueEntry.callbacksLockState, doRequest);
527 | }
528 | else if (queueEntry.callbacksLastKnownLockState) {
529 | this._lastKnownlockState(queueEntry.nukiLock, queueEntry.callbacksLastKnownLockState, doRequest);
530 | }
531 | }
532 | else if (queueEntry.callbackWebhookList) {
533 | this._getCallbacks(queueEntry.callbackWebhookList, doRequest);
534 | }
535 | else if (queueEntry.callbackWebhookAdd) {
536 | this._addCallback(doRequest);
537 | }
538 | else if (queueEntry.callbackList) {
539 | this._getList(queueEntry.callbackList, doRequest);
540 | }
541 | else if (queueEntry.callbackReboot) {
542 | this.reboot(queueEntry.callbackReboot, doRequest);
543 | }
544 | else if (queueEntry.callbackFirmware) {
545 | this.updateFirmware(queueEntry.callbackFirmware, doRequest);
546 | }
547 | }
548 | };
549 |
550 | module.exports = NukiBridge;
--------------------------------------------------------------------------------
/src/nuki/NukiLock.js:
--------------------------------------------------------------------------------
1 | const Constants = require('../Constants');
2 |
3 | function NukiLock(log, nukiBridge, id, priority, deviceType, webHookCallback) {
4 | this.nukiBridge = nukiBridge;
5 | this.log = log;
6 | this.id = id;
7 | this.lockAction = Constants.NUKI_LOCK_ACTION_LOCK;
8 | this.unlockAction = Constants.NUKI_LOCK_ACTION_UNLOCK;
9 | this.unlatchAction = Constants.NUKI_LOCK_ACTION_UNLATCH;
10 | this.lockNGoAction = Constants.NUKI_LOCK_ACTION_LOCK_N_GO;
11 | this.lockNGoActionUnlatch = Constants.NUKI_LOCK_ACTION_LOCK_N_GO_UNLATCH;
12 | this.priority = priority;
13 | this.deviceType = deviceType;
14 | this.webHookCallback = webHookCallback;
15 |
16 | if (this.priority == null || this.priority == "") {
17 | this.priority = Constants.DEFAULT_PRIORITY;
18 | }
19 |
20 | this.nukiBridge._addLock(this);
21 |
22 | var callbackIsLocked = (function(err, json) {
23 | this.log("Initial is locked request finished.");
24 | }).bind(this);
25 | if (this.nukiBridge.lockStateMode === Constants.LOCK_STATE_MODE_ONLY_CACHE) {
26 | this.isLocked(callbackIsLocked, true);
27 | }
28 | };
29 |
30 | NukiLock.prototype.isLocked = function isLocked(callback /* (err, isLocked) */, forceRequest) {
31 | if (forceRequest || this.nukiBridge.lockStateMode === Constants.LOCK_STATE_MODE_REQUEST_LOCKSTATE || this.nukiBridge.lockStateMode === Constants.LOCK_STATE_MODE_REQUEST_LASTKNOWNLOCKSTATE) {
32 | var callbackWrapper = (function(err, json) {
33 | if (err) {
34 | var cachedIsLocked = this.getIsLockedCached();
35 | this.log("Request for lock state aborted. This is no problem and might happen due to canceled request or due to long response time of the Nuki bridge. Using cached value isLocked = '%s'.", cachedIsLocked);
36 | callback(null, cachedIsLocked);
37 | }
38 | else {
39 | var state = Constants.NUKI_LOCK_STATE_UNDEFINED;
40 | var batteryCritical = false;
41 | var batteryCharging = false;
42 | var batteryChargeState = 100;
43 | var contactClosed = true;
44 | var mode = 2;
45 | if (json) {
46 | state = json.state;
47 | batteryCritical = json.batteryCritical;
48 | batteryCharging = json.batteryCharging === true;
49 | batteryChargeState = json.batteryChargeState ? json.batteryChargeState: batteryCritical ? Constants.BATTERY_LOW : Constants.BATTERY_FULL;
50 | contactClosed = json.doorsensorState !== 3;
51 | mode = json.mode;
52 | }
53 | var isLocked = this._isLocked(state);
54 | this.log("Lock state is isLocked = '%s' (Nuki state '%s' ) with battery critical = '%s', battery charging = '%s', battery charge state = '%s', contactClosed = '%s' and mode = '%s'", isLocked, state, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode);
55 | this._setLockCache(isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode);
56 | callback(null, isLocked);
57 | }
58 | }).bind(this);
59 | callbackWrapper.nukiLock = this;
60 | if (this.nukiBridge.lockStateMode === Constants.LOCK_STATE_MODE_REQUEST_LASTKNOWNLOCKSTATE) {
61 | this.nukiBridge._lastKnownlockState(this, [ callbackWrapper ]);
62 | }
63 | else {
64 | this.nukiBridge._lockState(this, [ callbackWrapper ]);
65 | }
66 | }
67 | else {
68 | var cachedIsLocked = this.getIsLockedCached();
69 | this.log("Cached lock state is isLocked = '%s'.", cachedIsLocked);
70 | callback(null, cachedIsLocked);
71 | }
72 | };
73 |
74 | NukiLock.prototype.isContactClosed = function isContactClosed(callback /* (err, isContactClosed) */) {
75 | var callbackIsLocked = (function(err, islocked) {
76 | callback(err, this._getIsContactClosed());
77 | }).bind(this);
78 | this.isLocked(callbackIsLocked);
79 | };
80 |
81 | NukiLock.prototype.getLowBatt = function getLowBatt(callback /* (err, lowBattt) */) {
82 | callback(null, this.getIsBatteryLowCached());
83 | };
84 |
85 | NukiLock.prototype.getCharging = function getCharging(callback /* (err, charging) */) {
86 | callback(null, this.getBatteryChargingCached());
87 | };
88 |
89 | NukiLock.prototype.getChargeState = function getChargeState(callback /* (err, chargeState) */) {
90 | callback(null, this.getBatteryChargeStateCached());
91 | };
92 |
93 | NukiLock.prototype._isLocked = function _isLocked(state) {
94 | var isLocked = state == Constants.NUKI_LOCK_STATE_LOCKED || state == Constants.NUKI_LOCK_STATE_LOCKING || state == Constants.NUKI_LOCK_STATE_UNCALIBRATED || state == Constants.NUKI_LOCK_STATE_MOTOR_BLOCKED || state == Constants.NUKI_LOCK_STATE_UNDEFINED;
95 | return isLocked;
96 | };
97 |
98 | NukiLock.prototype.lock = function lock(callback) {
99 | var callbackWrapper = (function(err, json) {
100 | if (!err || !err.retryableError) {
101 | this._setLockCache(true);
102 | }
103 | callback(err, json);
104 | }).bind(this);
105 | this.nukiBridge._lockAction(this, this.lockAction, callbackWrapper);
106 | };
107 |
108 | NukiLock.prototype.unlock = function unlock(callback) {
109 | var callbackWrapper = (function(err, json) {
110 | if (!err || !err.retryableError) {
111 | this._setLockCache(false);
112 | }
113 | callback(err, json);
114 | }).bind(this);
115 | this.log("Temp debug log: function unlock called.");
116 | this.nukiBridge._lockAction(this, this.unlockAction, callbackWrapper);
117 | };
118 |
119 | NukiLock.prototype.unlatch = function unlatch(callback) {
120 | var callbackWrapper = (function(err, json) {
121 | if ((!err || !err.retryableError) && this.deviceType === 0) {
122 | this._setLockCache(false);
123 | }
124 | callback(err, json);
125 | }).bind(this);
126 | this.log("Temp debug log: function unlatch called.");
127 | this.nukiBridge._lockAction(this, this.unlatchAction, callbackWrapper);
128 | };
129 |
130 | NukiLock.prototype.lockNGo = function lock(callback) {
131 | var callbackWrapper = (function(err, json) {
132 | if (!err || !err.retryableError) {
133 | this._setLockCache(undefined, undefined, 3);
134 | }
135 | callback(err, json);
136 | }).bind(this);
137 | this.nukiBridge._lockAction(this, this.lockNGoAction, callbackWrapper);
138 | };
139 |
140 | NukiLock.prototype.lockNGoUnlatch = function unlock(callback) {
141 | var callbackWrapper = (function(err, json) {
142 | if (!err || !err.retryableError) {
143 | this._setLockCache(undefined, undefined, 2);
144 | }
145 | callback(err, json);
146 | }).bind(this);
147 | this.nukiBridge._lockAction(this, this.lockNGoActionUnlatch, callbackWrapper);
148 | };
149 |
150 | NukiLock.prototype.getIsLockedCached = function getIsLockedCached() {
151 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
152 | if (lockCache === undefined) {
153 | return true;
154 | }
155 | return lockCache.isLocked;
156 | };
157 |
158 | NukiLock.prototype._getIsContactClosed = function _getIsContactClosed() {
159 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
160 | if (lockCache === undefined) {
161 | return true;
162 | }
163 | return lockCache.contactClosed;
164 | };
165 |
166 | NukiLock.prototype.getIsBatteryLowCached = function getIsBatteryLowCached() {
167 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
168 | if (lockCache === undefined) {
169 | return false;
170 | }
171 | return lockCache.batteryCritical;
172 | };
173 |
174 | NukiLock.prototype.getBatteryChargingCached = function getBatteryChargingCached() {
175 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
176 | if (lockCache === undefined) {
177 | return false;
178 | }
179 | return lockCache.batteryCharging;
180 | };
181 |
182 | NukiLock.prototype.getBatteryChargeStateCached = function getBatteryChargeStateCached() {
183 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
184 | if (lockCache === undefined) {
185 | return false;
186 | }
187 | return lockCache.batteryChargeState;
188 | };
189 |
190 | NukiLock.prototype.getModeCached = function getModeCached() {
191 | var lockCache = this.nukiBridge.storage.getItemSync(this._getLockStorageKey());
192 | if (lockCache === undefined) {
193 | return 2;
194 | }
195 | return lockCache.mode;
196 | };
197 |
198 | NukiLock.prototype._setLockCache = function _setLockCache(isLocked, batteryCritical, batteryCharging, batteryChargeState, contactClosed, mode) {
199 | var newCache = {
200 | isLocked : this.getIsLockedCached(),
201 | batteryCritical : this.getIsBatteryLowCached(),
202 | batteryCharging : this.getBatteryChargingCached(),
203 | batteryChargeState : this.getBatteryChargeStateCached(),
204 | contactClosed : this._getIsContactClosed(),
205 | mode : this.getModeCached()
206 | }
207 | if (isLocked !== undefined && isLocked !== null) {
208 | newCache.isLocked = isLocked;
209 | }
210 | if (batteryCritical !== undefined && batteryCritical !== null) {
211 | newCache.batteryCritical = batteryCritical;
212 | }
213 | if (batteryCharging !== undefined && batteryCharging !== null) {
214 | newCache.batteryCharging = batteryCharging;
215 | }
216 | if (batteryChargeState !== undefined && batteryChargeState !== null) {
217 | newCache.batteryChargeState = batteryChargeState;
218 | }
219 | if (contactClosed !== undefined && contactClosed !== null) {
220 | newCache.contactClosed = contactClosed;
221 | }
222 | if (mode !== undefined && mode !== null) {
223 | newCache.mode = mode;
224 | }
225 | this.nukiBridge.storage.setItemSync(this._getLockStorageKey(), newCache);
226 | };
227 |
228 | NukiLock.prototype._getLockStorageKey = function _getLockStorageKey() {
229 | return 'bridge-' + this.nukiBridge.bridgeUrl + '-lock-' + this.instanceId + '-' + this.id + '-cache';
230 | };
231 |
232 | module.exports = NukiLock;
--------------------------------------------------------------------------------