/
adapter.ts
12038 lines (10786 loc) · 470 KB
/
adapter.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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import net from 'node:net';
import fs from 'fs-extra';
import os from 'node:os';
import jwt from 'jsonwebtoken';
import { EventEmitter } from 'node:events';
import { tools, EXIT_CODES, password, logger } from '@iobroker/js-controller-common';
import pidUsage from 'pidusage';
import deepClone from 'deep-clone';
import { PluginHandler } from '@iobroker/plugin-base';
import semver from 'semver';
import path from 'node:path';
import { getObjectsConstructor, getStatesConstructor } from '@iobroker/js-controller-common-db';
import {
decryptArray,
encryptArray,
getSupportedFeatures,
isMessageboxSupported,
getAdapterScopedPackageIdentifier
} from '@/lib/adapter/utils.js';
// @ts-expect-error no ts file
import extend from 'node.extend';
import type { Client as StatesInRedisClient } from '@iobroker/db-states-redis';
import type { Client as ObjectsInRedisClient } from '@iobroker/db-objects-redis';
import type Winston from 'winston';
import type NodeSchedule from 'node-schedule';
import yargs from 'yargs/yargs';
// local version is always the same as controller version, since lerna exact: true is used
import packJson from '@iobroker/js-controller-adapter/package.json' assert { type: 'json' };
const controllerVersion = packJson.version;
import { Log } from '@/lib/adapter/log.js';
import { Validator } from './validator.js';
const { FORBIDDEN_CHARS } = tools;
import {
DEFAULT_SECRET,
ALIAS_STARTS_WITH,
SYSTEM_ADMIN_USER,
SYSTEM_ADMIN_GROUP,
ERROR_PERMISSION,
ACCESS_EVERY_READ,
ACCESS_EVERY_WRITE,
ACCESS_GROUP_WRITE,
ACCESS_GROUP_READ,
ACCESS_USER_WRITE,
ACCESS_USER_READ,
NO_PROTECT_ADAPTERS,
STATE_QUALITY,
type SupportedFeature
} from '@/lib/adapter/constants.js';
import type { PluginHandlerSettings } from '@iobroker/plugin-base/types';
import type {
AdapterOptions,
AliasDetails,
CalculatePermissionsCallback,
CheckGroupCallback,
CheckPasswordCallback,
CheckStateCommand,
CommandsPermissions,
GetCertificatesCallback,
GetEncryptedConfigCallback,
GetUserGroupsOptions,
InternalAddChannelToEnumOptions,
InternalAddStateToEnumOptions,
InternalCalculatePermissionsOptions,
InternalCheckGroupOptions,
InternalCheckPasswordOptions,
InternalCreateDeviceOptions,
InternalCreateStateOptions,
InternalDeleteChannelFromEnumOptions,
InternalDeleteChannelOptions,
InternalDeleteDeviceOptions,
InternalDeleteStateFromEnumOptions,
InternalDeleteStateOptions,
InternalDelObjectOptions,
InternalDelStateOptions,
InternalDestroySessionOptions,
InternalFormatDateOptions,
InternalGetAdapterObjectsOptions,
InternalGetCertificatesOptions,
InternalGetChannelsOfOptions,
InternalGetDevicesOptions,
InternalGetEncryptedConfigOptions,
InternalGetEnumOptions,
InternalGetEnumsOptions,
InternalGetHistoryOptions,
InternalGetObjectOptions,
InternalGetObjectsOptions,
InternalGetObjectViewOptions,
InternalGetPortOptions,
InternalGetSessionOptions,
InternalGetStateOptions,
InternalGetStatesOfOptions,
InternalGetStatesOptions,
InternalGetUserIDOptions,
InternalSendToHostOptions,
InternalSendToOptions,
InternalSetObjectOptions,
InternalSetPasswordOptions,
InternalSetSessionOptions,
InternalSetStateChangedOptions,
InternalSetStateOptions,
InternalSubscribeOptions,
InternalUpdateConfigOptions,
TimeoutCallback,
MaybePromise,
SetStateChangedResult,
CheckStatesResult,
Pattern,
MessageCallbackObject,
SendToOptions,
GetCertificatesPromiseReturnType,
InternalAdapterConfig,
UserInterfaceClientRemoveMessage,
SendToUserInterfaceClientOptions,
AllPropsUnknown,
IoPackageInstanceObject,
AliasTargetEntry,
SuitableLicense,
InstallNodeModuleOptions,
InternalInstallNodeModuleOptions,
StopParameters,
InternalStopParameters
} from '@/lib/_Types.js';
import { UserInterfaceMessagingController } from '@/lib/adapter/userInterfaceMessagingController.js';
import { SYSTEM_ADAPTER_PREFIX } from '@iobroker/js-controller-common/constants';
import type { CommandResult } from '@alcalzone/pak';
import * as url from 'node:url';
// eslint-disable-next-line unicorn/prefer-module
const thisDir = url.fileURLToPath(new URL('.', import.meta.url || 'file://' + __filename));
tools.ensureDNSOrder();
/**
* Here we define dynamically created methods
*/
export interface AdapterClass {
on(event: 'stateChange', listener: ioBroker.StateChangeHandler): this;
on(event: 'objectChange', listener: ioBroker.ObjectChangeHandler): this;
on(event: 'fileChange', listener: ioBroker.FileChangeHandler): this;
on(event: 'ready', listener: ioBroker.ReadyHandler): this;
on(event: 'install', listener: ioBroker.ReadyHandler): this;
on(event: 'unload', listener: ioBroker.UnloadHandler): this;
on(event: 'message', listener: ioBroker.MessageHandler): this;
/** Only emitted for compact instances */
on(event: 'exit', listener: (exitCode: number, reason: string) => Promise<void> | void): this;
on(event: 'log', listener: (info: any) => Promise<void> | void): this;
/**
* Extend an object and create it if it might not exist
*
* @deprecated use `adapter.extendObject` without callback instead
*/
extendObjectAsync(
id: string,
objPart: ioBroker.PartialObject,
options?: ioBroker.ExtendObjectOptions
): ioBroker.SetObjectPromise;
/** Set capabilities of the given executable. Only works on Linux systems. */
setExecutableCapabilities(
execPath: string,
capabilities: string[],
modeEffective?: boolean,
modePermitted?: boolean,
modeInherited?: boolean
): Promise<void>;
/** Extend an object (which might not belong to this adapter) and create it if it might not exist */
extendForeignObjectAsync<T extends string>(
id: T,
objPart: ioBroker.PartialObject<ioBroker.ObjectIdToObjectType<T, 'write'>>,
options?: ioBroker.ExtendObjectOptions
): ioBroker.SetObjectPromise;
/** Reads an object from the object db */
getObjectAsync(id: string, options?: unknown): ioBroker.GetObjectPromise;
/**
* Query a predefined object view (similar to SQL stored procedures) and return the results
* For a detailed description refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#object-fields
* or http://guide.couchdb.org/editions/1/en/views.html
*/
getObjectViewAsync<Design extends string = string, Search extends string = string>(
design: Design,
search: Search,
params: ioBroker.GetObjectViewParams | null | undefined,
options?: unknown
): ioBroker.GetObjectViewPromise<ioBroker.InferGetObjectViewItemType<Design, Search>>;
/** Returns a list of objects with id between params.startkey and params.endkey */
getObjectListAsync(
params: ioBroker.GetObjectListParams | null,
options?: { sorted?: boolean } | Record<string, any>
): ioBroker.GetObjectListPromise;
/** Returns the enum tree, filtered by the optional enum name */
getEnumAsync(name: string, options?: unknown): Promise<{ result: Record<string, any>; requestEnum: string }>;
/** Returns the enum tree, filtered by the optional enum name */
getEnumsAsync(enumList?: ioBroker.EnumList, options?: unknown): ioBroker.GetEnumsPromise;
/** Deletes an object from the object db */
delObjectAsync(id: string, options?: ioBroker.DelObjectOptions): Promise<void>;
/** Deletes an object (which might not belong to this adapter) from the object db */
delForeignObjectAsync(id: string, options?: ioBroker.DelObjectOptions): Promise<void>;
/** Subscribe to changes of objects in this instance */
subscribeObjectsAsync(pattern: string, options?: unknown): Promise<void>;
/** Unsubscribe from changes of objects in this instance */
unsubscribeObjectsAsync(pattern: string, options?: unknown): Promise<void>;
/** Read a value from the states DB. */
getStateAsync(id: string, options?: unknown): ioBroker.GetStatePromise;
/** Subscribe to changes of objects (which might not belong to this adapter) */
subscribeForeignObjectsAsync(pattern: string | string[], options?: unknown): Promise<void>;
/** Unsubscribe from changes of objects (which might not belong to this adapter) */
unsubscribeForeignObjectsAsync(pattern: string | string[], options?: unknown): Promise<void>;
/** Creates an object in the object db. Existing objects are not overwritten. */
setObjectNotExistsAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): ioBroker.SetObjectPromise;
/** Creates an object (which might not belong to this adapter) in the object db. Existing objects are not overwritten. */
setForeignObjectNotExistsAsync<T extends string>(
id: T,
obj: ioBroker.SettableObject<ioBroker.ObjectIdToObjectType<T, 'write'>>,
options?: unknown
): ioBroker.SetObjectPromise;
/** deletes a device, its channels and states */
deleteDeviceAsync(deviceName: string, options?: unknown): Promise<void>;
addChannelToEnumAsync(
enumName: string,
addTo: string,
parentDevice: string,
channelName: string,
options?: unknown
): Promise<void>;
deleteChannelFromEnumAsync(
enumName: string,
parentDevice: string,
channelName: string,
options?: unknown
): Promise<void>;
/** Returns a list of all devices in this adapter instance */
getDevicesAsync(options?: unknown): Promise<ioBroker.DeviceObject[]>;
addStateToEnumAsync(
enumName: string,
addTo: string,
parentDevice: string,
parentChannel: string,
stateName: string,
options?: unknown
): Promise<void>;
deleteStateFromEnumAsync(
enumName: string,
parentDevice: string,
parentChannel: string,
stateName: string,
options?: unknown
): Promise<void>;
/** Changes access rights of all files in the adapter directory */
chmodFileAsync(
adapter: string | null,
path: string,
options: { mode: number | string } | Record<string, any>
): Promise<{ entries: ioBroker.ChownFileResult[]; id: string }>;
// TODO: correct types
chownFileAsync(...args: any[]): Promise<any>;
/** reads the content of directory from DB for given adapter and path */
readDirAsync(adapterName: string | null, path: string, options?: unknown): ioBroker.ReadDirPromise;
/** Deletes a given file */
unlinkAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
/** Deletes a given file */
delFileAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
renameAsync(adapterName: string | null, oldName: string, newName: string, options?: unknown): Promise<void>;
mkdirAsync(adapterName: string | null, path: string, options?: unknown): Promise<void>;
/** reads the content of directory from DB for given adapter and path */
readFileAsync(adapterName: string | null, path: string, options?: unknown): ioBroker.ReadFilePromise;
writeFileAsync(adapterName: string | null, path: string, data: Buffer | string, options?: unknown): Promise<void>;
/** Checks if a file exists in the DB */
fileExistsAsync(adapterName: string | null, path: string, options?: unknown): Promise<boolean>;
// TODO correct types needed
getHistoryAsync(...args: any[]): Promise<any>;
/** Deletes a state from the states DB, but not the associated object. Consider using deleteState instead */
delStateAsync(id: string, options?: unknown): Promise<void>;
/** Deletes a state from the states DB, but not the associated object */
delForeignStateAsync(id: string, options?: unknown): Promise<void>;
/** Read all states of this adapter which match the given pattern */
getStatesAsync(pattern: string, options?: unknown): ioBroker.GetStatesPromise;
/** Read all states (which might not belong to this adapter) which match the given pattern */
getForeignStatesAsync(pattern: Pattern, options?: unknown): ioBroker.GetStatesPromise;
/** Subscribe to changes of states (which might not belong to this adapter) */
subscribeForeignStatesAsync(pattern: string | string[], options?: unknown): Promise<void>;
/** Subscribe from changes of states (which might not belong to this adapter) */
unsubscribeForeignStatesAsync(pattern: string | string[], options?: unknown): Promise<void>;
/** Subscribe to changes of states in this instance */
subscribeStatesAsync(pattern: Pattern, options?: unknown): Promise<void>;
/** Subscribe from changes of states in this instance */
unsubscribeStatesAsync(pattern: Pattern, options?: unknown): Promise<void>;
/**
* Helper function that looks for first free TCP port starting with the given one.
*/
getPortAsync(port: number): Promise<number>;
/** Read a value (which might not belong to this adapter) from the states DB. */
getForeignStateAsync(id: string, options?: unknown): ioBroker.GetStatePromise;
/** Validates username and password */
checkPasswordAsync(user: string, password: string, options?: unknown): Promise<boolean>;
/** Sets a new password for the given user */
setPasswordAsync(user: string, password: string, options?: unknown): Promise<void>;
/** <INTERNAL> Checks if a user exists and is in the given group. */
checkGroupAsync(user: string, group: string, options?: unknown): Promise<boolean>;
/** <INTERNAL> Determines the users permissions */
calculatePermissionsAsync(
user: string,
commandsPermissions: CommandsPermissions,
options?: unknown
): Promise<ioBroker.PermissionSet>;
/** Creates or overwrites an object in the object db */
setObjectAsync(id: string, obj: ioBroker.SettableObject, options?: unknown): ioBroker.SetObjectPromise;
/** Creates or overwrites an object (which might not belong to this adapter) in the object db */
setForeignObjectAsync<T extends string>(
id: T,
obj: ioBroker.SettableObject<ioBroker.ObjectIdToObjectType<T, 'write'>>,
options?: unknown
): ioBroker.SetObjectPromise;
// TODO: correct types
getCertificatesAsync(
publicName?: string,
privateName?: string,
chainedName?: string
): Promise<GetCertificatesPromiseReturnType>;
/** Get all states, channels, devices and folders of this adapter */
getAdapterObjectsAsync(): Promise<Record<string, ioBroker.AdapterScopedObject>>;
/** Reads an object (which might not belong to this adapter) from the object db*/
getForeignObjectAsync<T extends string>(id: T, options?: unknown): ioBroker.GetObjectPromise<T>;
/**
* Writes a value (which might not belong to this adapter) into the states DB only if it has changed.
*/
setForeignStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack?: boolean
): ioBroker.SetStateChangedPromise;
setForeignStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
options?: unknown
): ioBroker.SetStateChangedPromise;
setForeignStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack: boolean,
options: unknown
): ioBroker.SetStateChangedPromise;
/**
* Writes a value into the states DB only if it has changed.
*/
setStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack?: boolean
): ioBroker.SetStateChangedPromise;
setStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
options?: unknown
): ioBroker.SetStateChangedPromise;
setStateChangedAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack: boolean,
options: unknown
): ioBroker.SetStateChangedPromise;
/**
* Sends a message to a specific host or all hosts.
*/
sendToHostAsync(hostName: string, message: ioBroker.MessagePayload): Promise<ioBroker.Message | undefined>;
sendToHostAsync(
hostName: string,
command: string,
message: ioBroker.MessagePayload
): Promise<ioBroker.Message | undefined>;
/**
* Sends a message to a specific instance or all instances of some specific adapter.
*/
sendToAsync(instanceName: string, message: ioBroker.MessagePayload): Promise<ioBroker.Message | undefined>;
sendToAsync(
instanceName: string,
command: string,
message: ioBroker.MessagePayload,
options?: SendToOptions
): Promise<ioBroker.Message | undefined>;
/**
* Deletes a given file
*/
delFile(adapterName: string | null, path: string, callback: ioBroker.ErrnoCallback): void;
delFile(adapterName: string | null, path: string, options: unknown, callback: ioBroker.ErrnoCallback): void;
/**
* Writes a value into the states DB.
*
* @deprecated use `adapter.setState` without callback instead
*/
setStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack?: boolean
): ioBroker.SetStatePromise;
/** @deprecated use `adapter.setState` without callback instead */
setStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
options?: unknown
): ioBroker.SetStatePromise;
/** @deprecated use `adapter.setState` without callback instead */
setStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack: boolean,
options: unknown
): ioBroker.SetStatePromise;
/**
* Writes a value (which might not belong to this adapter) into the states DB.
*/
setForeignStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack?: boolean
): ioBroker.SetStatePromise;
setForeignStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
options?: unknown
): ioBroker.SetStatePromise;
setForeignStateAsync(
id: string,
state: ioBroker.State | ioBroker.StateValue | ioBroker.SettableState,
ack: boolean,
options: unknown
): ioBroker.SetStatePromise;
/**
* Get foreign objects by pattern, by specific type and resolve their enums.
*/
getForeignObjectsAsync<T extends ioBroker.ObjectType>(
pattern: Pattern,
type: T,
enums?: ioBroker.EnumList | null,
options?: unknown
): ioBroker.GetObjectsPromiseTyped<T>;
getForeignObjectsAsync<T extends ioBroker.ObjectType>(
pattern: Pattern,
type: T,
options?: unknown
): ioBroker.GetObjectsPromiseTyped<T>;
getForeignObjectsAsync(pattern: Pattern, options?: unknown): ioBroker.GetObjectsPromise;
/**
* creates an object with type device
*
* @deprecated use `extendObject` instead
*/
createDeviceAsync(deviceName: string, common?: Partial<ioBroker.DeviceCommon>): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createDeviceAsync(
deviceName: string,
common: Partial<ioBroker.DeviceCommon>,
native?: Record<string, any>
): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createDeviceAsync(
deviceName: string,
common: Partial<ioBroker.DeviceCommon>,
native: Record<string, any>,
options?: unknown
): ioBroker.SetObjectPromise;
/**
* Finds an object by its ID or name
*/
findForeignObjectAsync(idOrName: string, type: string): Promise<{ id: string; name: string }>;
/**
* Creates an object with type channel. It must be located under a device
*
* @deprecated use `extendObject` instead
*/
createChannelAsync(
parentDevice: string,
channelName: string,
roleOrCommon?: string | Partial<ioBroker.ChannelCommon>
): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createChannelAsync(
parentDevice: string,
channelName: string,
roleOrCommon: string | Partial<ioBroker.ChannelCommon>,
native?: Record<string, any>
): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createChannelAsync(
parentDevice: string,
channelName: string,
roleOrCommon: string | Partial<ioBroker.ChannelCommon>,
native: Record<string, any>,
options?: unknown
): ioBroker.SetObjectPromise;
/**
* Creates a state and the corresponding object. It must be located in a channel under a device
*
* @deprecated use `extendObject` instead
*/
createStateAsync(
parentDevice: string,
parentChannel: string,
stateName: string,
roleOrCommon?: string | Partial<ioBroker.StateCommon>
): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createStateAsync(
parentDevice: string,
parentChannel: string,
stateName: string,
roleOrCommon: string | Partial<ioBroker.StateCommon>,
native?: Record<string, any>
): ioBroker.SetObjectPromise;
/** @deprecated use `extendObject` instead */
createStateAsync(
parentDevice: string,
parentChannel: string,
stateName: string,
roleOrCommon: string | Partial<ioBroker.StateCommon>,
native: Record<string, any>,
options?: unknown
): ioBroker.SetObjectPromise;
/**
* Deletes a channel and its states. It must have been created with createChannel
*
* @deprecated use `this.delObject` instead
*/
deleteChannelAsync(channelName: string, options?: unknown): Promise<void>;
/** @deprecated use `this.delObject` instead */
deleteChannelAsync(parentDevice: string, channelName: string, options?: unknown): Promise<void>;
/**
* Deletes a state. It must have been created with createState
*
* @deprecated use `this.delObject` instead
*/
deleteStateAsync(stateName: string, options?: unknown): Promise<void>;
/** @deprecated use `this.delObject` instead */
deleteStateAsync(parentChannel: string, stateName: string, options?: unknown): Promise<void>;
/** @deprecated use `this.delObject` instead */
deleteStateAsync(parentDevice: string, parentChannel: string, stateName: string, options?: unknown): Promise<void>;
/**
* Returns a list of all channels in this adapter instance @param parentDevice (optional) Name
* of the parent device to filter the channels by @param options (optional) Some internal options.
*/
getChannelsOfAsync(): Promise<ioBroker.ChannelObject[]>;
getChannelsOfAsync(parentDevice: string, options?: unknown): Promise<ioBroker.ChannelObject[]>;
/**
* Returns a list of all channels in this adapter instance
*/
getChannels(callback: ioBroker.GetObjectsCallback3<ioBroker.ChannelObject>): void;
getChannels(parentDevice: string, callback: ioBroker.GetObjectsCallback3<ioBroker.ChannelObject>): void;
getChannels(
parentDevice: string,
options: unknown,
callback: ioBroker.GetObjectsCallback3<ioBroker.ChannelObject>
): void;
/**
* Returns a list of all channels in this adapter instance @param parentDevice (optional)
* Name of the parent device to filter the channels by @param options (optional) Some internal options.
*/
getChannelsAsync(): Promise<ioBroker.ChannelObject[]>;
getChannelsAsync(parentDevice: string, options?: unknown): Promise<ioBroker.ChannelObject[]>;
/**
* Returns a list of all states in this adapter instance @param parentDevice (optional)
* Name of the parent device to filter the channels by @param parentChannel (optional)
* Name of the parent channel to filter the channels by @param options (optional) Some internal options.
*/
getStatesOfAsync(): Promise<ioBroker.StateObject[]>;
getStatesOfAsync(parentDevice: string, parentChannel?: string): Promise<ioBroker.StateObject[]>;
getStatesOfAsync(parentDevice: string, parentChannel: string, options?: unknown): Promise<ioBroker.StateObject[]>;
}
/**
* Adapter class
*
* How the initialization happens:
* _initObjects => _initStates => _prepareInitAdapter => _initAdapter => _initLogging => _createInstancesObjects => ready
*
*/
export class AdapterClass extends EventEmitter {
/** Instance to access states DB */
#states?: StatesInRedisClient | null;
/** Instance to access objects DB */
#objects?: ObjectsInRedisClient | null;
/** States DB constructor */
private States?: typeof StatesInRedisClient;
/** Objects DB constructor */
private Objects?: typeof ObjectsInRedisClient;
/** Contents of iobroker.json */
private readonly _config: Record<string, any>;
private readonly _options: AdapterOptions;
private readonly startedInCompactMode: boolean;
/** List of instances which want our logs */
private readonly logList = new Set<string>();
private readonly aliases = new Map<string, AliasDetails>();
private readonly aliasPatterns = new Set<string>();
private enums: Record<string, any> = {};
private eventLoopLags: number[] = [];
private overwriteLogLevel: boolean = false;
adapterReady: boolean = false;
/** Callbacks from sendTo */
private readonly messageCallbacks = new Map<number, MessageCallbackObject>();
/**
* Contains a live cache of the adapter's states.
* NOTE: This is only defined if the adapter was initialized with the option states: true.
*/
oStates?: Record<string, ioBroker.State | undefined>;
/**
* Contains a live cache of the adapter's objects.
* NOTE: This is only defined if the adapter was initialized with the option objects: true.
*/
oObjects?: Record<string, ioBroker.Object | undefined>;
private _stopInProgress: boolean = false;
private _callbackId: number = 1;
private _firstConnection: boolean = true;
private readonly _timers = new Set<NodeJS.Timeout>();
private readonly _intervals = new Set<NodeJS.Timeout>();
private readonly _delays = new Set<NodeJS.Timeout>();
/** For ease of use the log property is always defined, however it is only available after `ready` has been called. */
log!: Log;
performStrictObjectChecks: boolean;
private readonly _logger: Winston.Logger;
private _restartScheduleJob: any;
private _schedule?: typeof NodeSchedule;
private namespaceLog: string;
namespace: `${string}.${number}`;
name: string;
private _systemSecret?: string;
/** Whether the adapter has already terminated */
private terminated: boolean = false;
/** The cache of usernames */
private usernames: Record<string, { id: string }> = {};
/** A RegExp to test for forbidden chars in object IDs */
readonly FORBIDDEN_CHARS: RegExp = FORBIDDEN_CHARS;
private inputCount: number = 0;
private outputCount: number = 0;
/** The cache of users */
private users: Record<ioBroker.ObjectIDs.User, { groups: any; acl: any }> = {}; // todo
/** The cache of user groups */
private groups: Record<string, Partial<ioBroker.GroupObject>> = {};
/** An array of instances, that support auto subscribe */
private autoSubscribe: string[] = [];
private defaultHistory: null | string = null;
private pluginHandler?: InstanceType<typeof PluginHandler>;
private _reportInterval?: null | NodeJS.Timer;
private getPortRunning: null | InternalGetPortOptions = null;
private readonly _namespaceRegExp: RegExp;
instance?: number;
// @ts-expect-error decide how to handle it
private _utils: Validator;
/** contents of io-package.json */
adapterConfig?: AdapterOptions | ioBroker.InstanceObject | null;
connected?: boolean;
adapterDir: string;
/** contents of package.json */
pack?: Record<string, any>;
/** contents of io-package.json */
ioPack: Record<string, any>; // contents of io-package.json TODO difference to adapterConfig?
private _initializeTimeout?: NodeJS.Timeout | null;
private inited?: boolean;
/** contents of iobroker.json if required via AdapterOptions */
systemConfig?: Record<string, any>;
/** the configured date format of system.config, only available if requested via AdapterOptions `useFormatDate` */
dateFormat?: any;
/** if float comma instead of dot is used, only available if requested via AdapterOptions `useFormatDate` */
isFloatComma?: boolean;
/** configured language of system.config, only available if requested via AdapterOptions `useFormatDate` */
language?: ioBroker.Languages;
/** longitude configured in system.config, only available if requested via AdapterOptions `useFormatDate`*/
longitude?: string;
/** latitude configured in system.config, only available if requested via AdapterOptions `useFormatDate`*/
latitude?: string;
private _defaultObjs?: Record<string, Partial<ioBroker.StateCommon>>;
private _aliasObjectsSubscribed?: boolean;
config: ioBroker.AdapterConfig = {};
host?: string;
common?: ioBroker.InstanceCommon;
private mboxSubscribed?: boolean;
/** Stop the adapter */
stop?: (params?: StopParameters) => Promise<void>;
version?: string;
/** Stop the adapter only defined in compact, not for external usage */
protected kill?: () => Promise<void>;
processLog?: (msg: any) => void;
/**
* Start or stop subscribing to log messages
* The method is only available if logTransporter is active via io-pack or adapter options
* Note, that stopping will stop after 10 seconds, not immediately
*
* @param isActive - if log subscription should be activated or deactivated
* @param options - options passed to setState e.g. user permissions
*/
requireLog?: (isActive: boolean, options?: Partial<GetUserGroupsOptions>) => Promise<void> | void;
private logOffTimer?: NodeJS.Timeout | null;
private logRequired?: boolean;
private patterns?: Record<string, { regex: string }>;
private statesConnectedTime?: number;
/** Constants for frequent use in adapters */
readonly constants = {
STATE_QUALITY
} as const;
/** Features supported by the running instance */
private readonly SUPPORTED_FEATURES = getSupportedFeatures();
/** Controller for messaging related functionality */
private readonly uiMessagingController: UserInterfaceMessagingController;
constructor(options: AdapterOptions | string) {
super();
// enable "const adapter = require(__dirname + '/../../lib/adapter.js')('adapterName');" call
if (typeof options === 'string') {
this._options = { name: options };
} else {
this._options = options;
}
const configFileName = tools.getConfigFileName();
if (fs.pathExistsSync(configFileName)) {
this._config = fs.readJsonSync(configFileName);
this._config.states = this._config.states || { type: 'jsonl' };
this._config.objects = this._config.objects || { type: 'jsonl' };
// Make sure the DB has enough time (5s). JsonL can take a bit longer if the process just crashed before
// because the lockfile might not have been freed.
this._config.states.connectTimeout = Math.max(this._config.states.connectTimeout || 0, 5_000);
this._config.objects.connectTimeout = Math.max(this._config.objects.connectTimeout || 0, 5_000);
} else {
throw new Error(`Cannot find ${configFileName}`);
}
if (!this._options) {
throw new Error('Configuration not set!');
}
if (this._options.config && !this._options.config.log) {
this._options.config.log = this._config.log;
}
this._config = this._options.config || this._config;
this.startedInCompactMode = !!this._options.compact;
const parsedArgs = yargs(process.argv.slice(2))
.options({
loglevel: {
describe: 'Define adapter log level',
type: 'string'
},
silent: {
describe: 'If is install run',
type: 'boolean'
},
install: {
describe: 'If is install run',
type: 'boolean'
},
logs: {
describe: 'If console output desired',
type: 'boolean'
},
console: {
describe: 'If console output desired',
type: 'boolean'
},
force: {
describe: 'If force start even if disabled',
type: 'boolean'
},
debug: {
describe: 'Same as --force combined with --console',
type: 'boolean'
},
instance: {
describe: 'Instance id, e.g. 0',
type: 'string'
}
})
.parseSync();
if (parsedArgs.loglevel && ['info', 'debug', 'error', 'warn', 'silly'].includes(parsedArgs.loglevel)) {
this._config.log.level = parsedArgs.loglevel;
this.overwriteLogLevel = true;
}
if (parsedArgs.silent || parsedArgs.install) {
this._config.isInstall = true;
}
if (parsedArgs.logs || parsedArgs.console) {
this._config.consoleOutput = true;
}
if (parsedArgs.force) {
this._config.forceIfDisabled = true;
}
if (parsedArgs.debug) {
this._config.forceIfDisabled = true;
this._config.consoleOutput = true;
if (this._config.log.level !== 'silly') {
this._config.log.level = 'debug';
this.overwriteLogLevel = true;
}
}
if (parsedArgs.instance && parseInt(parsedArgs.instance, 10).toString() === parsedArgs.instance) {
this._config.instance = parseInt(parsedArgs.instance, 10);
}
this._config.log.level = this._config.log.level || 'info';
this._config.log.noStdout = !this._config.consoleOutput;
this.performStrictObjectChecks = this._options.strictObjectChecks !== false;
this.name = this._options.name;
if (!this.name) {
throw new Error('No name of adapter!');
}
const instance = parseInt(
this._options.compactInstance !== undefined
? this._options.compactInstance
: this._options.instance !== undefined
? this._options.instance
: this._config.instance || 0,
10
);
this.namespace = `${this.name}.${instance}`;
this.namespaceLog = this.namespace + (this.startedInCompactMode ? ' (COMPACT)' : ` (${process.pid})`);
this._namespaceRegExp = new RegExp(`^${`${this.namespace}.`.replace(/\./g, '\\.')}`); // cache the regex object 'adapter.0.'
this._logger = logger(this._config.log);
// compatibility
if (!this._logger.silly) {
this._logger.silly = this._logger.debug;
}
// If installed as npm module
if (this._options.dirname) {
this.adapterDir = this._options.dirname.replace(/\\/g, '/');
} else {
const adapterDir = tools.getAdapterDir(this.name);
if (!adapterDir) {
this._logger.error(`${this.namespaceLog} Cannot find directory of adapter ${this.name}`);
this.terminate(EXIT_CODES.CANNOT_FIND_ADAPTER_DIR);
}
this.adapterDir = adapterDir;
}
if (fs.existsSync(`${this.adapterDir}/io-package.json`)) {
this.ioPack = fs.readJSONSync(`${this.adapterDir}/io-package.json`);
} else {
this._logger.error(`${this.namespaceLog} Cannot find: ${this.adapterDir}/io-package.json`);
this.terminate(EXIT_CODES.CANNOT_FIND_ADAPTER_DIR);
}
this.uiMessagingController = new UserInterfaceMessagingController({
adapter: this,
subscribeCallback: this._options.uiClientSubscribe,
unsubscribeCallback: this._options.uiClientUnsubscribe
});
// Create dynamic methods
/**
* Promise-version of `Adapter.getPort`
*/
this.getPortAsync = tools.promisifyNoError(this.getPort, this);
/**
* Promise-version of `Adapter.checkPassword`
*/
this.checkPasswordAsync = tools.promisifyNoError(this.checkPassword, this);
/**
* Promise-version of `Adapter.setPassword`
*/
this.setPasswordAsync = tools.promisify(this.setPassword, this);
/**
* Promise-version of `Adapter.checkGroup`
*/
this.checkGroupAsync = tools.promisifyNoError(this.checkGroup, this);
/**
* Promise-version of `Adapter.calculatePermissions`
*/
this.calculatePermissionsAsync = tools.promisifyNoError(this.calculatePermissions, this);
/**
* Promise-version of `Adapter.getCertificates`
*/
this.getCertificatesAsync = tools.promisify(this.getCertificates, this);
/**
* Promise-version of `Adapter.setObject`
*/
this.setObjectAsync = tools.promisify(this.setObject, this);
/**
* Promise-version of `Adapter.getAdapterObjects`
*/
this.getAdapterObjectsAsync = tools.promisifyNoError(this.getAdapterObjects, this);
/**
* Promise-version of `Adapter.extendObject`
*/
this.extendObjectAsync = tools.promisify(this.extendObject, this);
/**
* Promise-version of `Adapter.setForeignObject`
*/
this.setForeignObjectAsync = tools.promisify(this.setForeignObject, this);
/**
* Promise-version of `Adapter.extendForeignObject`
*/
this.extendForeignObjectAsync = tools.promisify(this.extendForeignObject, this);
/**
* Promise-version of `Adapter.getObject`
*/
this.getObjectAsync = tools.promisify(this.getObject, this);
/**
* Promise-version of `Adapter.getObjectView`
*/
this.getObjectViewAsync = tools.promisify(this.getObjectView, this);
/**
* Promise-version of `Adapter.getObjectList`
*/
this.getObjectListAsync = tools.promisify(this.getObjectList, this);
/**
* Promise-version of `Adapter.getEnum`
*/
this.getEnumAsync = tools.promisify(this.getEnum, this, ['result', 'requestEnum']);
/**
* Promise-version of `Adapter.getEnums`
*/
this.getEnumsAsync = tools.promisify(this.getEnums, this);
/**
* Promise-version of `Adapter.getForeignObjects`
*/
this.getForeignObjectsAsync = tools.promisify(this.getForeignObjects, this);
/**
* Promise-version of `Adapter.findForeignObject`
*/
this.findForeignObjectAsync = tools.promisify(this.findForeignObject, this, ['id', 'name']);
/**
* Promise-version of `Adapter.getForeignObject`
*/
this.getForeignObjectAsync = tools.promisify(this.getForeignObject, this);
/**
* Promise-version of `Adapter.delObject`
*/
this.delObjectAsync = tools.promisify(this.delObject, this);
/**
* Promise-version of `Adapter.delForeignObject`
*/
this.delForeignObjectAsync = tools.promisify(this.delForeignObject, this);
/**
* Promise-version of `Adapter.subscribeObjects`
*/
this.subscribeObjectsAsync = tools.promisify(this.subscribeObjects, this);
/**