-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconnection.ts
869 lines (830 loc) · 34.5 KB
/
connection.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
"use strict";
import debugModule from "debug";
import { timeout as promiseTimeout } from "promise-timeout";
import {
ConnectionOptions,
PeerCertificate,
TLSSocket,
checkServerIdentity as checkServerIdentityOriginal,
connect,
} from "tls";
import { GW_ERROR_NTF } from "./KLF200-API/GW_ERROR_NTF.js";
import { GW_GET_STATE_REQ } from "./KLF200-API/GW_GET_STATE_REQ.js";
import { KLF200SocketProtocol } from "./KLF200-API/KLF200SocketProtocol.js";
import {
GW_COMMON_STATUS,
GW_FRAME_COMMAND_REQ,
GatewayCommand,
IGW_FRAME,
IGW_FRAME_COMMAND,
IGW_FRAME_RCV,
IGW_FRAME_REQ,
KLF200_PORT,
} from "./KLF200-API/common.js";
import { ca } from "./ca.js";
import {
GW_ACTIVATE_PRODUCTGROUP_CFM,
GW_ACTIVATE_PRODUCTGROUP_REQ,
GW_ACTIVATE_SCENE_CFM,
GW_ACTIVATE_SCENE_REQ,
GW_CLEAR_ACTIVATION_LOG_CFM,
GW_CLEAR_ACTIVATION_LOG_REQ,
GW_COMMAND_SEND_CFM,
GW_COMMAND_SEND_REQ,
GW_CS_ACTIVATE_CONFIGURATION_MODE_CFM,
GW_CS_ACTIVATE_CONFIGURATION_MODE_REQ,
GW_CS_CONTROLLER_COPY_CFM,
GW_CS_CONTROLLER_COPY_REQ,
GW_CS_DISCOVER_NODES_CFM,
GW_CS_DISCOVER_NODES_REQ,
GW_CS_GENERATE_NEW_KEY_CFM,
GW_CS_GENERATE_NEW_KEY_REQ,
GW_CS_GET_SYSTEMTABLE_DATA_CFM,
GW_CS_GET_SYSTEMTABLE_DATA_REQ,
GW_CS_RECEIVE_KEY_CFM,
GW_CS_RECEIVE_KEY_REQ,
GW_CS_REMOVE_NODES_CFM,
GW_CS_REMOVE_NODES_REQ,
GW_CS_REPAIR_KEY_CFM,
GW_CS_REPAIR_KEY_REQ,
GW_CS_VIRGIN_STATE_CFM,
GW_CS_VIRGIN_STATE_REQ,
GW_DELETE_GROUP_CFM,
GW_DELETE_GROUP_REQ,
GW_DELETE_SCENE_CFM,
GW_DELETE_SCENE_REQ,
GW_GET_ACTIVATION_LOG_HEADER_CFM,
GW_GET_ACTIVATION_LOG_HEADER_REQ,
GW_GET_ACTIVATION_LOG_LINE_CFM,
GW_GET_ACTIVATION_LOG_LINE_REQ,
GW_GET_ALL_GROUPS_INFORMATION_CFM,
GW_GET_ALL_GROUPS_INFORMATION_REQ,
GW_GET_ALL_NODES_INFORMATION_CFM,
GW_GET_ALL_NODES_INFORMATION_REQ,
GW_GET_CONTACT_INPUT_LINK_LIST_CFM,
GW_GET_CONTACT_INPUT_LINK_LIST_REQ,
GW_GET_GROUP_INFORMATION_CFM,
GW_GET_GROUP_INFORMATION_REQ,
GW_GET_LIMITATION_STATUS_CFM,
GW_GET_LIMITATION_STATUS_REQ,
GW_GET_LOCAL_TIME_CFM,
GW_GET_LOCAL_TIME_REQ,
GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_CFM,
GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_REQ,
GW_GET_NETWORK_SETUP_CFM,
GW_GET_NETWORK_SETUP_REQ,
GW_GET_NODE_INFORMATION_CFM,
GW_GET_NODE_INFORMATION_REQ,
GW_GET_PROTOCOL_VERSION_CFM,
GW_GET_PROTOCOL_VERSION_REQ,
GW_GET_SCENE_INFORMATION_CFM,
GW_GET_SCENE_INFORMATION_REQ,
GW_GET_SCENE_LIST_CFM,
GW_GET_SCENE_LIST_REQ,
GW_GET_STATE_CFM,
GW_GET_VERSION_CFM,
GW_GET_VERSION_REQ,
GW_HOUSE_STATUS_MONITOR_DISABLE_CFM,
GW_HOUSE_STATUS_MONITOR_DISABLE_REQ,
GW_HOUSE_STATUS_MONITOR_ENABLE_CFM,
GW_HOUSE_STATUS_MONITOR_ENABLE_REQ,
GW_INITIALIZE_SCENE_CANCEL_CFM,
GW_INITIALIZE_SCENE_CANCEL_REQ,
GW_INITIALIZE_SCENE_CFM,
GW_INITIALIZE_SCENE_REQ,
GW_LEAVE_LEARN_STATE_CFM,
GW_LEAVE_LEARN_STATE_REQ,
GW_MODE_SEND_CFM,
GW_MODE_SEND_REQ,
GW_NEW_GROUP_CFM,
GW_NEW_GROUP_REQ,
GW_PASSWORD_CHANGE_CFM,
GW_PASSWORD_CHANGE_REQ,
GW_PASSWORD_ENTER_CFM,
GW_PASSWORD_ENTER_REQ,
GW_REBOOT_CFM,
GW_REBOOT_REQ,
GW_RECORD_SCENE_CFM,
GW_RECORD_SCENE_REQ,
GW_REMOVE_CONTACT_INPUT_LINK_CFM,
GW_REMOVE_CONTACT_INPUT_LINK_REQ,
GW_RENAME_SCENE_CFM,
GW_RENAME_SCENE_REQ,
GW_RTC_SET_TIME_ZONE_CFM,
GW_RTC_SET_TIME_ZONE_REQ,
GW_SET_CONTACT_INPUT_LINK_CFM,
GW_SET_CONTACT_INPUT_LINK_REQ,
GW_SET_FACTORY_DEFAULT_CFM,
GW_SET_FACTORY_DEFAULT_REQ,
GW_SET_GROUP_INFORMATION_CFM,
GW_SET_GROUP_INFORMATION_REQ,
GW_SET_LIMITATION_CFM,
GW_SET_LIMITATION_REQ,
GW_SET_NETWORK_SETUP_CFM,
GW_SET_NETWORK_SETUP_REQ,
GW_SET_NODE_NAME_CFM,
GW_SET_NODE_NAME_REQ,
GW_SET_NODE_ORDER_AND_PLACEMENT_CFM,
GW_SET_NODE_ORDER_AND_PLACEMENT_REQ,
GW_SET_NODE_VARIATION_CFM,
GW_SET_NODE_VARIATION_REQ,
GW_SET_UTC_CFM,
GW_SET_UTC_REQ,
GW_STATUS_REQUEST_CFM,
GW_STATUS_REQUEST_REQ,
GW_STOP_SCENE_CFM,
GW_STOP_SCENE_REQ,
GW_WINK_SEND_CFM,
GW_WINK_SEND_REQ,
} from "./index.js";
import { Disposable, Listener, TypedEvent } from "./utils/TypedEvent.js";
const debug = debugModule(`klf-200-api:connection`);
/**
* Interface for the connection.
*
* @interface IConnection
*/
export interface IConnection {
/**
* Logs in to the KLF interface by sending the GW_PASSWORD_ENTER_REQ.
*
* @param {string} password The password needed for login. The factory default password is velux123.
* @param {number} [timeout] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<void>} Returns a promise that resolves to true on success or rejects with the errors.
*/
loginAsync(password: string, timeout?: number): Promise<void>;
/**
* Logs out from the KLF interface and closes the socket.
*
* @param {number} [timeout] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<void>} Returns a promise that resolves to true on successful logout or rejects with the errors.
*/
logoutAsync(timeout?: number): Promise<void>;
/**
* Sends a request frame to the KLF interface.
*
* @param {IGW_FRAME_REQ} frame The frame that should be sent to the KLF interface.
* @param {number} [timeout] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<IGW_FRAME_RCV>} Returns a promise with the corresponding confirmation message as value.
* In case of an error frame the promise will be rejected with the error number.
* If the request frame is a command (with a SessionID) than the promise will be
* resolved by the corresponding confirmation frame with a matching session ID.
*/
sendFrameAsync(frame: GW_REBOOT_REQ, timeout?: number): Promise<GW_REBOOT_CFM>;
sendFrameAsync(frame: GW_SET_FACTORY_DEFAULT_REQ, timeout?: number): Promise<GW_SET_FACTORY_DEFAULT_CFM>;
sendFrameAsync(frame: GW_GET_VERSION_REQ, timeout?: number): Promise<GW_GET_VERSION_CFM>;
sendFrameAsync(frame: GW_GET_PROTOCOL_VERSION_REQ, timeout?: number): Promise<GW_GET_PROTOCOL_VERSION_CFM>;
sendFrameAsync(frame: GW_GET_STATE_REQ, timeout?: number): Promise<GW_GET_STATE_CFM>;
sendFrameAsync(frame: GW_LEAVE_LEARN_STATE_REQ, timeout?: number): Promise<GW_LEAVE_LEARN_STATE_CFM>;
sendFrameAsync(frame: GW_GET_NETWORK_SETUP_REQ, timeout?: number): Promise<GW_GET_NETWORK_SETUP_CFM>;
sendFrameAsync(frame: GW_SET_NETWORK_SETUP_REQ, timeout?: number): Promise<GW_SET_NETWORK_SETUP_CFM>;
sendFrameAsync(frame: GW_CS_GET_SYSTEMTABLE_DATA_REQ, timeout?: number): Promise<GW_CS_GET_SYSTEMTABLE_DATA_CFM>;
sendFrameAsync(frame: GW_CS_DISCOVER_NODES_REQ, timeout?: number): Promise<GW_CS_DISCOVER_NODES_CFM>;
sendFrameAsync(frame: GW_CS_REMOVE_NODES_REQ, timeout?: number): Promise<GW_CS_REMOVE_NODES_CFM>;
sendFrameAsync(frame: GW_CS_VIRGIN_STATE_REQ, timeout?: number): Promise<GW_CS_VIRGIN_STATE_CFM>;
sendFrameAsync(frame: GW_CS_CONTROLLER_COPY_REQ, timeout?: number): Promise<GW_CS_CONTROLLER_COPY_CFM>;
sendFrameAsync(frame: GW_CS_RECEIVE_KEY_REQ, timeout?: number): Promise<GW_CS_RECEIVE_KEY_CFM>;
sendFrameAsync(frame: GW_CS_GENERATE_NEW_KEY_REQ, timeout?: number): Promise<GW_CS_GENERATE_NEW_KEY_CFM>;
sendFrameAsync(frame: GW_CS_REPAIR_KEY_REQ, timeout?: number): Promise<GW_CS_REPAIR_KEY_CFM>;
sendFrameAsync(
frame: GW_CS_ACTIVATE_CONFIGURATION_MODE_REQ,
timeout?: number,
): Promise<GW_CS_ACTIVATE_CONFIGURATION_MODE_CFM>;
sendFrameAsync(frame: GW_GET_NODE_INFORMATION_REQ, timeout?: number): Promise<GW_GET_NODE_INFORMATION_CFM>;
sendFrameAsync(
frame: GW_GET_ALL_NODES_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_ALL_NODES_INFORMATION_CFM>;
sendFrameAsync(frame: GW_SET_NODE_VARIATION_REQ, timeout?: number): Promise<GW_SET_NODE_VARIATION_CFM>;
sendFrameAsync(frame: GW_SET_NODE_NAME_REQ, timeout?: number): Promise<GW_SET_NODE_NAME_CFM>;
sendFrameAsync(
frame: GW_SET_NODE_ORDER_AND_PLACEMENT_REQ,
timeout?: number,
): Promise<GW_SET_NODE_ORDER_AND_PLACEMENT_CFM>;
sendFrameAsync(frame: GW_GET_GROUP_INFORMATION_REQ, timeout?: number): Promise<GW_GET_GROUP_INFORMATION_CFM>;
sendFrameAsync(frame: GW_SET_GROUP_INFORMATION_REQ, timeout?: number): Promise<GW_SET_GROUP_INFORMATION_CFM>;
sendFrameAsync(frame: GW_DELETE_GROUP_REQ, timeout?: number): Promise<GW_DELETE_GROUP_CFM>;
sendFrameAsync(frame: GW_NEW_GROUP_REQ, timeout?: number): Promise<GW_NEW_GROUP_CFM>;
sendFrameAsync(
frame: GW_GET_ALL_GROUPS_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_ALL_GROUPS_INFORMATION_CFM>;
sendFrameAsync(
frame: GW_HOUSE_STATUS_MONITOR_ENABLE_REQ,
timeout?: number,
): Promise<GW_HOUSE_STATUS_MONITOR_ENABLE_CFM>;
sendFrameAsync(
frame: GW_HOUSE_STATUS_MONITOR_DISABLE_REQ,
timeout?: number,
): Promise<GW_HOUSE_STATUS_MONITOR_DISABLE_CFM>;
sendFrameAsync(frame: GW_COMMAND_SEND_REQ, timeout?: number): Promise<GW_COMMAND_SEND_CFM>;
sendFrameAsync(frame: GW_STATUS_REQUEST_REQ, timeout?: number): Promise<GW_STATUS_REQUEST_CFM>;
sendFrameAsync(frame: GW_WINK_SEND_REQ, timeout?: number): Promise<GW_WINK_SEND_CFM>;
sendFrameAsync(frame: GW_SET_LIMITATION_REQ, timeout?: number): Promise<GW_SET_LIMITATION_CFM>;
sendFrameAsync(frame: GW_GET_LIMITATION_STATUS_REQ, timeout?: number): Promise<GW_GET_LIMITATION_STATUS_CFM>;
sendFrameAsync(frame: GW_MODE_SEND_REQ, timeout?: number): Promise<GW_MODE_SEND_CFM>;
sendFrameAsync(frame: GW_INITIALIZE_SCENE_REQ, timeout?: number): Promise<GW_INITIALIZE_SCENE_CFM>;
sendFrameAsync(frame: GW_INITIALIZE_SCENE_CANCEL_REQ, timeout?: number): Promise<GW_INITIALIZE_SCENE_CANCEL_CFM>;
sendFrameAsync(frame: GW_RECORD_SCENE_REQ, timeout?: number): Promise<GW_RECORD_SCENE_CFM>;
sendFrameAsync(frame: GW_DELETE_SCENE_REQ, timeout?: number): Promise<GW_DELETE_SCENE_CFM>;
sendFrameAsync(frame: GW_RENAME_SCENE_REQ, timeout?: number): Promise<GW_RENAME_SCENE_CFM>;
sendFrameAsync(frame: GW_GET_SCENE_LIST_REQ, timeout?: number): Promise<GW_GET_SCENE_LIST_CFM>;
sendFrameAsync(frame: GW_GET_SCENE_INFORMATION_REQ, timeout?: number): Promise<GW_GET_SCENE_INFORMATION_CFM>;
sendFrameAsync(frame: GW_ACTIVATE_SCENE_REQ, timeout?: number): Promise<GW_ACTIVATE_SCENE_CFM>;
sendFrameAsync(frame: GW_STOP_SCENE_REQ, timeout?: number): Promise<GW_STOP_SCENE_CFM>;
sendFrameAsync(frame: GW_ACTIVATE_PRODUCTGROUP_REQ, timeout?: number): Promise<GW_ACTIVATE_PRODUCTGROUP_CFM>;
sendFrameAsync(
frame: GW_GET_CONTACT_INPUT_LINK_LIST_REQ,
timeout?: number,
): Promise<GW_GET_CONTACT_INPUT_LINK_LIST_CFM>;
sendFrameAsync(frame: GW_SET_CONTACT_INPUT_LINK_REQ, timeout?: number): Promise<GW_SET_CONTACT_INPUT_LINK_CFM>;
sendFrameAsync(
frame: GW_REMOVE_CONTACT_INPUT_LINK_REQ,
timeout?: number,
): Promise<GW_REMOVE_CONTACT_INPUT_LINK_CFM>;
sendFrameAsync(
frame: GW_GET_ACTIVATION_LOG_HEADER_REQ,
timeout?: number,
): Promise<GW_GET_ACTIVATION_LOG_HEADER_CFM>;
sendFrameAsync(frame: GW_CLEAR_ACTIVATION_LOG_REQ, timeout?: number): Promise<GW_CLEAR_ACTIVATION_LOG_CFM>;
sendFrameAsync(frame: GW_GET_ACTIVATION_LOG_LINE_REQ, timeout?: number): Promise<GW_GET_ACTIVATION_LOG_LINE_CFM>;
sendFrameAsync(
frame: GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_REQ,
timeout?: number,
): Promise<GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_CFM>;
sendFrameAsync(frame: GW_SET_UTC_REQ, timeout?: number): Promise<GW_SET_UTC_CFM>;
sendFrameAsync(frame: GW_RTC_SET_TIME_ZONE_REQ, timeout?: number): Promise<GW_RTC_SET_TIME_ZONE_CFM>;
sendFrameAsync(frame: GW_GET_LOCAL_TIME_REQ, timeout?: number): Promise<GW_GET_LOCAL_TIME_CFM>;
sendFrameAsync(frame: GW_PASSWORD_ENTER_REQ, timeout?: number): Promise<GW_PASSWORD_ENTER_CFM>;
sendFrameAsync(frame: GW_PASSWORD_CHANGE_REQ, timeout?: number): Promise<GW_PASSWORD_CHANGE_CFM>;
sendFrameAsync(frame: IGW_FRAME_REQ, timeout?: number): Promise<IGW_FRAME_RCV>;
/**
* Add a handler to listen for confirmations and notification.
* You can provide an optional filter to listen only to
* specific events.
*
* @param {Listener<IGW_FRAME_RCV>} handler Callback functions that is called for an event
* @param {GatewayCommand[]} [filter] Array of GatewayCommand entries you want to listen to. Optional.
* @returns {Disposable} Returns a Disposable that you can call to remove the handler.
*/
on(handler: Listener<IGW_FRAME_RCV>, filter?: GatewayCommand[]): Disposable;
/**
* Add a handler to listen for confirmations and notification.
* You can provide an optional filter to listen only to
* specific events.
*
* @param {Listener<IGW_FRAME_REQ>} handler Callback functions that is called for an event
* @param {GatewayCommand[]} [filter] Array of GatewayCommand entries you want to listen to. Optional.
* @returns {Disposable} Returns a Disposable that you can call to remove the handler.
*/
onFrameSent(handler: Listener<IGW_FRAME_REQ>, filter?: GatewayCommand[]): Disposable;
/**
* Gets the underlying socket protocol handler.
*
* @type {KLF200SocketProtocol}
*/
readonly KLF200SocketProtocol?: KLF200SocketProtocol;
}
const FINGERPRINT: string = "02:8C:23:A0:89:2B:62:98:C4:99:00:5B:D2:E7:2E:0A:70:3D:71:6A";
/**
* The Connection class is used to handle the communication with the Velux KLF interface.
* It provides login and logout functionality and provides methods to run other commands
* on the socket API.
*
* ```
* const Connection = require('velux-api').Connection;
*
* let conn = new Connection('velux-klf-12ab');
* conn.loginAsync('velux123')
* .then(() => {
* ... do some other stuff ...
* return conn.logoutAsync();
* })
* .catch((err) => { // always close the connection
* return conn.logoutAsync().reject(err);
* });
* ```
*
* @class Connection
*/
export class Connection implements IConnection {
private sckt?: TLSSocket;
private klfProtocol?: KLF200SocketProtocol;
readonly host: string;
readonly CA: Buffer = ca;
readonly fingerprint: string = FINGERPRINT;
readonly connectionOptions?: ConnectionOptions;
/**
* Creates a new connection object that connect to the given host.
* @param {string} host Host name or IP address of the KLF-200 interface.
* @param {Buffer} [CA=ca] A buffer with a certificate of the certificate authority.
* Currently, the interface uses a self-signed certificate
* thus a certificate has to be provided for the CA.
* This parameter is optional and in case the certificate
* will be changed with subsequent firmware updates you can
* provide the matching certificate with this parameter.
* @param {string} [fingerprint=FINGERPRINT] The fingerprint of the certificate. This parameter is optional.
*/
constructor(host: string, CA?: Buffer, fingerprint?: string);
/**
* Creates a new connection object that connect to the given host.
* @param host Host name or IP address of the KLF-200 interface.
* @param connectionOptions Options that will be provided to the connect method of the TLS socket.
*/
constructor(host: string, connectionOptions: ConnectionOptions);
constructor(host: string, CAorConnectionOptions?: Buffer | ConnectionOptions, fingerprint?: string) {
this.host = host;
if (CAorConnectionOptions !== undefined) {
if (Buffer.isBuffer(CAorConnectionOptions)) {
this.CA = CAorConnectionOptions;
} else {
this.connectionOptions = CAorConnectionOptions;
}
}
if (fingerprint !== undefined) {
this.fingerprint = fingerprint;
}
}
/**
* Gets the [[KLF200SocketProtocol]] object used by this connection.
* This property has a value after calling [[loginAsync]], only.
*
* @readonly
*/
public get KLF200SocketProtocol(): KLF200SocketProtocol | undefined {
return this.klfProtocol;
}
/**
* This method implements the login process without timeout.
* The [[loginAsync]] function wraps this into a timed promise.
*
* @private
* @param {string} password The password needed for login. The factory default password is velux123.
* @returns {Promise<void>} Returns a promise that resolves to true on success or rejects with the errors.
*/
private async _loginAsync(password: string, timeout: number): Promise<void> {
try {
await this.initSocketAsync();
this.klfProtocol = new KLF200SocketProtocol(<TLSSocket>this.sckt);
const passwordCFM = await this.sendFrameAsync(new GW_PASSWORD_ENTER_REQ(password), timeout);
if (passwordCFM.Status !== GW_COMMON_STATUS.SUCCESS) {
return Promise.reject(new Error("Login failed."));
} else {
return Promise.resolve();
}
} catch (error) {
return Promise.reject(error);
}
}
/**
* Logs in to the KLF interface by sending the GW_PASSWORD_ENTER_REQ.
*
* @param {string} password The password needed for login. The factory default password is velux123.
* @param {number} [timeout=60] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<void>} Returns a promise that resolves to true on success or rejects with the errors.
*/
public async loginAsync(password: string, timeout: number = 60): Promise<void> {
try {
await this._loginAsync(password, timeout);
} catch (error) {
return Promise.reject(error);
}
}
/**
* Logs out from the KLF interface and closes the socket.
*
* @param {number} [timeout=10] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<void>} Returns a promise that resolves to true on successful logout or rejects with the errors.
*/
public async logoutAsync(timeout: number = 10): Promise<void> {
try {
debug("Logging out from the KLF interface and closing the socket...");
if (this.sckt) {
if (this.klfProtocol) {
this.klfProtocol = undefined;
}
return promiseTimeout(
new Promise<void>((resolve, reject) => {
try {
// Close socket
debug("Closing socket...");
this.sckt?.end("", () => {
debug("Socket closed.");
resolve();
});
} catch (error) {
debug("Error while closing socket:", error);
reject(error);
}
}),
timeout * 1000,
);
} else {
debug("No socket to close.");
return Promise.resolve();
}
} catch (error) {
debug("Error while logging out:", error);
return Promise.reject(error);
}
}
/**
* Sends a request frame to the KLF interface.
*
* @param {IGW_FRAME_REQ} frame The frame that should be sent to the KLF interface.
* @param {number} [timeout=10] A timeout in seconds. After the timeout the returned promise will be rejected.
* @returns {Promise<IGW_FRAME_RCV>} Returns a promise with the corresponding confirmation message as value.
* In case of an error frame the promise will be rejected with the error number.
* If the request frame is a command (with a SessionID) than the promise will be
* resolved by the corresponding confirmation frame with a matching session ID.
*/
public async sendFrameAsync(frame: GW_REBOOT_REQ, timeout?: number): Promise<GW_REBOOT_CFM>;
public async sendFrameAsync(
frame: GW_SET_FACTORY_DEFAULT_REQ,
timeout?: number,
): Promise<GW_SET_FACTORY_DEFAULT_CFM>;
public async sendFrameAsync(frame: GW_GET_VERSION_REQ, timeout?: number): Promise<GW_GET_VERSION_CFM>;
public async sendFrameAsync(
frame: GW_GET_PROTOCOL_VERSION_REQ,
timeout?: number,
): Promise<GW_GET_PROTOCOL_VERSION_CFM>;
public async sendFrameAsync(frame: GW_GET_STATE_REQ, timeout?: number): Promise<GW_GET_STATE_CFM>;
public async sendFrameAsync(frame: GW_LEAVE_LEARN_STATE_REQ, timeout?: number): Promise<GW_LEAVE_LEARN_STATE_CFM>;
public async sendFrameAsync(frame: GW_GET_NETWORK_SETUP_REQ, timeout?: number): Promise<GW_GET_NETWORK_SETUP_CFM>;
public async sendFrameAsync(frame: GW_SET_NETWORK_SETUP_REQ, timeout?: number): Promise<GW_SET_NETWORK_SETUP_CFM>;
public async sendFrameAsync(
frame: GW_CS_GET_SYSTEMTABLE_DATA_REQ,
timeout?: number,
): Promise<GW_CS_GET_SYSTEMTABLE_DATA_CFM>;
public async sendFrameAsync(frame: GW_CS_DISCOVER_NODES_REQ, timeout?: number): Promise<GW_CS_DISCOVER_NODES_CFM>;
public async sendFrameAsync(frame: GW_CS_REMOVE_NODES_REQ, timeout?: number): Promise<GW_CS_REMOVE_NODES_CFM>;
public async sendFrameAsync(frame: GW_CS_VIRGIN_STATE_REQ, timeout?: number): Promise<GW_CS_VIRGIN_STATE_CFM>;
public async sendFrameAsync(frame: GW_CS_CONTROLLER_COPY_REQ, timeout?: number): Promise<GW_CS_CONTROLLER_COPY_CFM>;
public async sendFrameAsync(frame: GW_CS_RECEIVE_KEY_REQ, timeout?: number): Promise<GW_CS_RECEIVE_KEY_CFM>;
public async sendFrameAsync(
frame: GW_CS_GENERATE_NEW_KEY_REQ,
timeout?: number,
): Promise<GW_CS_GENERATE_NEW_KEY_CFM>;
public async sendFrameAsync(frame: GW_CS_REPAIR_KEY_REQ, timeout?: number): Promise<GW_CS_REPAIR_KEY_CFM>;
public async sendFrameAsync(
frame: GW_CS_ACTIVATE_CONFIGURATION_MODE_REQ,
timeout?: number,
): Promise<GW_CS_ACTIVATE_CONFIGURATION_MODE_CFM>;
public async sendFrameAsync(
frame: GW_GET_NODE_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_NODE_INFORMATION_CFM>;
public async sendFrameAsync(
frame: GW_GET_ALL_NODES_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_ALL_NODES_INFORMATION_CFM>;
public async sendFrameAsync(frame: GW_SET_NODE_VARIATION_REQ, timeout?: number): Promise<GW_SET_NODE_VARIATION_CFM>;
public async sendFrameAsync(frame: GW_SET_NODE_NAME_REQ, timeout?: number): Promise<GW_SET_NODE_NAME_CFM>;
public async sendFrameAsync(
frame: GW_SET_NODE_ORDER_AND_PLACEMENT_REQ,
timeout?: number,
): Promise<GW_SET_NODE_ORDER_AND_PLACEMENT_CFM>;
public async sendFrameAsync(
frame: GW_GET_GROUP_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_GROUP_INFORMATION_CFM>;
public async sendFrameAsync(
frame: GW_SET_GROUP_INFORMATION_REQ,
timeout?: number,
): Promise<GW_SET_GROUP_INFORMATION_CFM>;
public async sendFrameAsync(frame: GW_DELETE_GROUP_REQ, timeout?: number): Promise<GW_DELETE_GROUP_CFM>;
public async sendFrameAsync(frame: GW_NEW_GROUP_REQ, timeout?: number): Promise<GW_NEW_GROUP_CFM>;
public async sendFrameAsync(
frame: GW_GET_ALL_GROUPS_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_ALL_GROUPS_INFORMATION_CFM>;
public async sendFrameAsync(
frame: GW_HOUSE_STATUS_MONITOR_ENABLE_REQ,
timeout?: number,
): Promise<GW_HOUSE_STATUS_MONITOR_ENABLE_CFM>;
public async sendFrameAsync(
frame: GW_HOUSE_STATUS_MONITOR_DISABLE_REQ,
timeout?: number,
): Promise<GW_HOUSE_STATUS_MONITOR_DISABLE_CFM>;
public async sendFrameAsync(frame: GW_COMMAND_SEND_REQ, timeout?: number): Promise<GW_COMMAND_SEND_CFM>;
public async sendFrameAsync(frame: GW_STATUS_REQUEST_REQ, timeout?: number): Promise<GW_STATUS_REQUEST_CFM>;
public async sendFrameAsync(frame: GW_WINK_SEND_REQ, timeout?: number): Promise<GW_WINK_SEND_CFM>;
public async sendFrameAsync(frame: GW_SET_LIMITATION_REQ, timeout?: number): Promise<GW_SET_LIMITATION_CFM>;
public async sendFrameAsync(
frame: GW_GET_LIMITATION_STATUS_REQ,
timeout?: number,
): Promise<GW_GET_LIMITATION_STATUS_CFM>;
public async sendFrameAsync(frame: GW_MODE_SEND_REQ, timeout?: number): Promise<GW_MODE_SEND_CFM>;
public async sendFrameAsync(frame: GW_INITIALIZE_SCENE_REQ, timeout?: number): Promise<GW_INITIALIZE_SCENE_CFM>;
public async sendFrameAsync(
frame: GW_INITIALIZE_SCENE_CANCEL_REQ,
timeout?: number,
): Promise<GW_INITIALIZE_SCENE_CANCEL_CFM>;
public async sendFrameAsync(frame: GW_RECORD_SCENE_REQ, timeout?: number): Promise<GW_RECORD_SCENE_CFM>;
public async sendFrameAsync(frame: GW_DELETE_SCENE_REQ, timeout?: number): Promise<GW_DELETE_SCENE_CFM>;
public async sendFrameAsync(frame: GW_RENAME_SCENE_REQ, timeout?: number): Promise<GW_RENAME_SCENE_CFM>;
public async sendFrameAsync(frame: GW_GET_SCENE_LIST_REQ, timeout?: number): Promise<GW_GET_SCENE_LIST_CFM>;
public async sendFrameAsync(
frame: GW_GET_SCENE_INFORMATION_REQ,
timeout?: number,
): Promise<GW_GET_SCENE_INFORMATION_CFM>;
public async sendFrameAsync(frame: GW_ACTIVATE_SCENE_REQ, timeout?: number): Promise<GW_ACTIVATE_SCENE_CFM>;
public async sendFrameAsync(frame: GW_STOP_SCENE_REQ, timeout?: number): Promise<GW_STOP_SCENE_CFM>;
public async sendFrameAsync(
frame: GW_ACTIVATE_PRODUCTGROUP_REQ,
timeout?: number,
): Promise<GW_ACTIVATE_PRODUCTGROUP_CFM>;
public async sendFrameAsync(
frame: GW_GET_CONTACT_INPUT_LINK_LIST_REQ,
timeout?: number,
): Promise<GW_GET_CONTACT_INPUT_LINK_LIST_CFM>;
public async sendFrameAsync(
frame: GW_SET_CONTACT_INPUT_LINK_REQ,
timeout?: number,
): Promise<GW_SET_CONTACT_INPUT_LINK_CFM>;
public async sendFrameAsync(
frame: GW_REMOVE_CONTACT_INPUT_LINK_REQ,
timeout?: number,
): Promise<GW_REMOVE_CONTACT_INPUT_LINK_CFM>;
public async sendFrameAsync(
frame: GW_GET_ACTIVATION_LOG_HEADER_REQ,
timeout?: number,
): Promise<GW_GET_ACTIVATION_LOG_HEADER_CFM>;
public async sendFrameAsync(
frame: GW_CLEAR_ACTIVATION_LOG_REQ,
timeout?: number,
): Promise<GW_CLEAR_ACTIVATION_LOG_CFM>;
public async sendFrameAsync(
frame: GW_GET_ACTIVATION_LOG_LINE_REQ,
timeout?: number,
): Promise<GW_GET_ACTIVATION_LOG_LINE_CFM>;
public async sendFrameAsync(
frame: GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_REQ,
timeout?: number,
): Promise<GW_GET_MULTIPLE_ACTIVATION_LOG_LINES_CFM>;
public async sendFrameAsync(frame: GW_SET_UTC_REQ, timeout?: number): Promise<GW_SET_UTC_CFM>;
public async sendFrameAsync(frame: GW_RTC_SET_TIME_ZONE_REQ, timeout?: number): Promise<GW_RTC_SET_TIME_ZONE_CFM>;
public async sendFrameAsync(frame: GW_GET_LOCAL_TIME_REQ, timeout?: number): Promise<GW_GET_LOCAL_TIME_CFM>;
public async sendFrameAsync(frame: GW_PASSWORD_ENTER_REQ, timeout?: number): Promise<GW_PASSWORD_ENTER_CFM>;
public async sendFrameAsync(frame: GW_PASSWORD_CHANGE_REQ, timeout?: number): Promise<GW_PASSWORD_CHANGE_CFM>;
public async sendFrameAsync(frame: IGW_FRAME_REQ, timeout: number = 10): Promise<IGW_FRAME_RCV> {
try {
debug(`sendFrameAsync called with frame: ${stringifyFrame(frame)}, timeout: ${timeout}.`);
const frameName = GatewayCommand[frame.Command];
const expectedConfirmationFrameName: keyof typeof GatewayCommand = (frameName.slice(0, -3) +
"CFM") as keyof typeof GatewayCommand;
const expectedConfirmationFrameCommand = GatewayCommand[expectedConfirmationFrameName];
const sessionID = frame instanceof GW_FRAME_COMMAND_REQ ? frame.SessionID : undefined;
debug(
`Expected confirmation frame is ${expectedConfirmationFrameName} (${expectedConfirmationFrameCommand}). Session ID: ${sessionID}`,
);
// Setup the event handlers first to prevent a race condition
// where we don't see the events.
let resolve: (value: IGW_FRAME_RCV | PromiseLike<IGW_FRAME_RCV>) => void, reject: (reason?: any) => void;
const notificationHandler = new Promise<IGW_FRAME_RCV>((res, rej) => {
resolve = res;
reject = rej;
});
let cfmHandler: Disposable | undefined = undefined;
let errHandler: Disposable | undefined = undefined;
try {
errHandler = (this.klfProtocol as KLF200SocketProtocol).onError((error) => {
debug(`sendFrameAsync protocol error handler: ${JSON.stringify(error)}.`);
errHandler?.dispose();
cfmHandler?.dispose();
reject(error);
});
cfmHandler = (this.klfProtocol as KLF200SocketProtocol).on((notificationFrame) => {
try {
debug(`sendFrameAsync frame received: ${stringifyFrame(notificationFrame)}.`);
if (notificationFrame instanceof GW_ERROR_NTF) {
debug(`sendFrameAsync GW_ERROR_NTF received: ${stringifyFrame(notificationFrame)}.`);
errHandler?.dispose();
cfmHandler?.dispose();
reject(new Error(notificationFrame.getError(), { cause: notificationFrame }));
} else if (
notificationFrame.Command === expectedConfirmationFrameCommand &&
(typeof sessionID === "undefined" ||
sessionID === (notificationFrame as IGW_FRAME_COMMAND).SessionID)
) {
debug(`sendFrameAsync expected frame received: ${stringifyFrame(notificationFrame)}.`);
errHandler?.dispose();
cfmHandler?.dispose();
resolve(notificationFrame);
}
} catch (error) {
errHandler?.dispose();
cfmHandler?.dispose();
reject(error);
}
});
this.shiftKeepAlive();
await (this.klfProtocol as KLF200SocketProtocol).write(frame.Data);
await this.notifyFrameSent(frame);
return await promiseTimeout(notificationHandler, timeout * 1000);
} catch (error) {
debug(
`sendFrameAsync error occurred: ${typeof error === "string" ? error : JSON.stringify(error)} with frame sent: ${stringifyFrame(frame)}.`,
);
errHandler?.dispose();
cfmHandler?.dispose();
reject!(error);
return Promise.reject(error);
}
} catch (error) {
debug(
`sendFrameAsync error occurred (outer): ${typeof error === "string" ? error : JSON.stringify(error)} with frame sent: ${stringifyFrame(frame)}.`,
);
return Promise.reject(error);
}
function stringifyFrame(frame: IGW_FRAME): string {
return JSON.stringify(frame, (key: string, value: any) => {
if (key.match(/password/i)) {
return "**********";
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return value;
}
});
}
}
/**
* Add a handler to listen for confirmations and notification.
* You can provide an optional filter to listen only to
* specific events.
*
* @param {Listener<IGW_FRAME_RCV>} handler Callback functions that is called for an event
* @param {GatewayCommand[]} [filter] Array of GatewayCommand entries you want to listen to. Optional.
* @returns {Disposable} Returns a Disposable that you can call to remove the handler.
*/
public on(handler: Listener<IGW_FRAME_RCV>, filter?: GatewayCommand[]): Disposable {
if (typeof filter === "undefined") {
return (this.klfProtocol as KLF200SocketProtocol).on(handler);
} else {
return (this.klfProtocol as KLF200SocketProtocol).on(async (frame) => {
if (filter.indexOf(frame.Command) >= 0) {
await Promise.resolve(handler(frame));
}
});
}
}
private _onFrameSent = new TypedEvent<IGW_FRAME_REQ>();
/**
* Add a handler to listen for sent frames.
* You can provide an optional filter to listen only to
* specific events.
*
* @param {Listener<IGW_FRAME_REQ>} handler Callback functions that is called for an event
* @param {GatewayCommand[]} [filter] Array of GatewayCommand entries you want to listen to. Optional.
* @returns {Disposable} Returns a Disposable that you can call to remove the handler.
*/
public onFrameSent(handler: Listener<IGW_FRAME_REQ>, filter?: GatewayCommand[]): Disposable {
if (typeof filter === "undefined") {
return this._onFrameSent.on(handler);
} else {
return this._onFrameSent.on((frame) => {
if (filter.indexOf(frame.Command) >= 0) {
handler(frame);
}
});
}
}
private async notifyFrameSent(frame: IGW_FRAME_REQ): Promise<void> {
await this._onFrameSent.emit(frame);
}
private keepAliveTimer?: NodeJS.Timeout;
private keepAliveInterval: number = 10 * 60 * 1000;
/**
* Start a keep-alive timer to send a message
* at least every [[interval]] minutes to the interface.
* The KLF-200 interface will close the connection
* after 15 minutes of inactivity.
*
* @param {number} [interval=600000] Keep-alive interval in minutes. Defaults to 10 min.
*/
public startKeepAlive(interval: number = 10 * 60 * 1000): void {
this.keepAliveInterval = interval;
this.keepAliveTimer = setInterval(() => {
this.sendKeepAlive().catch((error) =>
debug(`Error while sending keep alive: ${typeof error === "string" ? error : JSON.stringify(error)}`),
);
}, interval);
}
/**
* Stops the keep-alive timer.
* If not timer is set nothing happens.
*
*/
public stopKeepAlive(): void {
if (this.keepAliveTimer) {
clearInterval(this.keepAliveTimer);
this.keepAliveTimer = undefined;
}
}
/**
* Sends a keep-alive message to the interface
* to keep the socket connection open.
*
* @private
* @returns {Promise<void>} Resolves if successful, otherwise reject
*/
private async sendKeepAlive(): Promise<void> {
await this.sendFrameAsync(new GW_GET_STATE_REQ());
return;
}
/**
* Shifts the keep-alive timer to restart its counter.
* If no keep-alive timer is active nothing happens.
*
* @private
*/
private shiftKeepAlive(): void {
if (this.keepAliveTimer) {
clearInterval(this.keepAliveTimer);
this.startKeepAlive(this.keepAliveInterval);
}
}
private async initSocketAsync(): Promise<void> {
try {
if (this.sckt === undefined) {
return new Promise<void>((resolve, reject) => {
try {
const loginErrorHandler = (error: unknown): void => {
console.error(`loginErrorHandler: ${JSON.stringify(error)}`);
this.sckt = undefined;
reject(error);
};
this.sckt = connect(
KLF200_PORT,
this.host,
this.connectionOptions
? this.connectionOptions
: {
rejectUnauthorized: true,
ca: [this.CA],
checkServerIdentity: (host, cert) => this.checkServerIdentity(host, cert),
},
() => {
// Callback on event "secureConnect":
// Resolve promise if connection is authorized, otherwise reject it.
if (this.sckt?.authorized) {
// Remove login error handler
this.sckt?.off("error", loginErrorHandler);
resolve();
} else {
const err = this.sckt?.authorizationError;
this.sckt = undefined;
console.error(`AuthorizationError: ${err!.toString()}`);
reject(err);
}
},
);
// Add error handler to reject the promise on login problems
this.sckt?.on("error", loginErrorHandler);
this.sckt?.on("close", () => {
// Socket has been closed -> clean up everything
this.socketClosedEventHandler();
});
// Add additional error handler for the lifetime of the socket
this.sckt?.on("error", () => {
// Socket has an error -> clean up everything
this.socketClosedEventHandler();
});
// React to end events:
this.sckt?.on("end", () => {
if (this.sckt?.allowHalfOpen) {
this.sckt?.end(() => {
this.socketClosedEventHandler();
});
}
});
// Timeout of socket:
this.sckt?.on("timeout", () => {
this.sckt?.end(() => {
this.socketClosedEventHandler();
});
});
} catch (error) {
console.error(`initSocketAsync inner catch: ${JSON.stringify(error)}`);
reject(error);
}
});
} else {
return Promise.resolve();
}
} catch (error) {
console.error(`initSocketAsync outer catch: ${JSON.stringify(error)}`);
return Promise.reject(error);
}
}
private socketClosedEventHandler(): void {
// Socket has been closed -> clean up everything
this.stopKeepAlive();
this.klfProtocol = undefined;
this.sckt = undefined;
}
private checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined {
if (cert.fingerprint === this.fingerprint) return undefined;
else return checkServerIdentityOriginal(host, cert);
}
}