homematic-manager 3.4.2 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/data/cross-validations.json +14 -0
  2. package/data/easymode-time-selectors.json +1 -1
  3. package/data/manifest.json +12 -12
  4. package/data/master-forms.json +245 -24
  5. package/data/master-metadata.json +323 -9
  6. package/data/translations/de.json +12 -1
  7. package/data/translations/en.json +11 -0
  8. package/node_modules/@homematic-manager/backend/README.md +8 -1
  9. package/node_modules/@homematic-manager/backend/dist/api/backend.js +28 -5
  10. package/node_modules/@homematic-manager/backend/dist/cache/descriptions.d.ts +21 -2
  11. package/node_modules/@homematic-manager/backend/dist/cache/descriptions.js +50 -16
  12. package/node_modules/@homematic-manager/backend/dist/cache/store.d.ts +12 -2
  13. package/node_modules/@homematic-manager/backend/dist/cache/store.js +126 -11
  14. package/node_modules/@homematic-manager/backend/dist/meta/occuliteProvider.d.ts +8 -0
  15. package/node_modules/@homematic-manager/backend/dist/meta/occuliteProvider.js +20 -17
  16. package/node_modules/@homematic-manager/backend/dist/rega/scripts.d.ts +12 -6
  17. package/node_modules/@homematic-manager/backend/dist/rega/scripts.js +17 -8
  18. package/node_modules/@homematic-manager/backend/dist/util/jsonFile.d.ts +9 -2
  19. package/node_modules/@homematic-manager/backend/dist/util/jsonFile.js +39 -2
  20. package/node_modules/@homematic-manager/backend/dist/write/paramset.d.ts +10 -0
  21. package/node_modules/@homematic-manager/backend/dist/write/paramset.js +22 -1
  22. package/node_modules/@homematic-manager/backend/dist/write/repair.d.ts +7 -7
  23. package/node_modules/@homematic-manager/backend/dist/write/repair.js +5 -14
  24. package/node_modules/@homematic-manager/backend/package.json +1 -1
  25. package/node_modules/@homematic-manager/core/dist/api/types.d.ts +15 -0
  26. package/node_modules/@homematic-manager/core/dist/index.d.ts +2 -0
  27. package/node_modules/@homematic-manager/core/dist/index.js +2 -0
  28. package/node_modules/@homematic-manager/core/dist/interfaces/table.d.ts +14 -0
  29. package/node_modules/@homematic-manager/core/dist/interfaces/table.js +20 -0
  30. package/node_modules/@homematic-manager/core/dist/links/partnerFilter.d.ts +55 -0
  31. package/node_modules/@homematic-manager/core/dist/links/partnerFilter.js +235 -0
  32. package/node_modules/@homematic-manager/core/dist/paramset/cast.d.ts +37 -0
  33. package/node_modules/@homematic-manager/core/dist/paramset/cast.js +61 -1
  34. package/node_modules/@homematic-manager/core/dist/paramset/diff.d.ts +15 -0
  35. package/node_modules/@homematic-manager/core/dist/paramset/diff.js +16 -2
  36. package/node_modules/@homematic-manager/core/dist/paramset/powerMeter.d.ts +40 -0
  37. package/node_modules/@homematic-manager/core/dist/paramset/powerMeter.js +47 -0
  38. package/node_modules/@homematic-manager/core/dist/paramset/units.d.ts +11 -0
  39. package/node_modules/@homematic-manager/core/dist/paramset/units.js +19 -0
  40. package/node_modules/@homematic-manager/core/package.json +1 -1
  41. package/package.json +3 -3
  42. package/ui/assets/index-BGYochtr.js +21 -0
  43. package/ui/assets/index-Cd-Vx9ge.css +1 -0
  44. package/ui/index.html +2 -2
  45. package/ui/assets/index-BOEXCG42.css +0 -1
  46. package/ui/assets/index-Fj6yr6EG.js +0 -21
@@ -103,10 +103,17 @@ own directory; a test: a temporary one).
103
103
  | --- | --- | --- |
104
104
  | `config.json` | the `AppConfig` (connection only; the rest is derived) | on every `config.set`, atomically |
105
105
  | `cache/<host>/devices.json` | device descriptions per interface | debounced, on every change |
106
- | `cache/<host>/descriptions.json` | paramset descriptions by identity | debounced, when one was fetched |
106
+ | `cache/<host>/descriptions/<interface>/<type>.<hash>.json` | paramset descriptions by identity, one file per device type | debounced, only the type that gained one |
107
107
  | `cache/<host>/names.json` | the local names and the ReGa object ids | debounced, on every rename |
108
+ | `cache/<host>/unreach.json` | how often each device went unreachable | a minute after an outage, and on stop |
109
+ | `cache/<host>/occulite-meta.json` | the last metadata snapshot of openccu-lite | 5 s after a change, and on stop |
108
110
  | `cache/<host>/write-log.json` | the write log of the session | debounced, on every write |
109
111
 
112
+ A file whose content did not change is not written again (the device list after every `init`, the
113
+ names at every start, the metadata snapshot after every reconnect): on the addon the data directory
114
+ is the CCU's SD card. The single `descriptions.json` of 3.5 and older is split into the per-type
115
+ files on the first start and removed.
116
+
110
117
  The cache directory is keyed by host, so switching between two CCUs cannot mix their device lists.
111
118
  Every write goes through a temporary file and a rename: 2.x used `persist-json` without its
112
119
  `{secure: true}` option, so an interrupted write lost the configuration.
@@ -14,7 +14,7 @@
14
14
  * main process with it, issue #127).
15
15
  */
16
16
  import path from 'node:path';
17
- import { RPC_METHOD_NAMES, RSSI_UNKNOWN, countsAsServiceMessage, isAcknowledgeable, isKnownInterface, maintenanceAddress, mergeMethodHelp, methodsFor, callbackPinOption, normaliseDescription, repairMisdecodedUtf8, } from '@homematic-manager/core';
17
+ import { RPC_METHOD_NAMES, RSSI_UNKNOWN, countsAsServiceMessage, isAcknowledgeable, isKnownInterface, offersConfigMaintenance, maintenanceAddress, mergeMethodHelp, methodsFor, callbackPinOption, normaliseDescription, repairMisdecodedUtf8, } from '@homematic-manager/core';
18
18
  import { CacheStore } from '../cache/store.js';
19
19
  import { ConfigStore } from '../config/store.js';
20
20
  import { LinkTemplateStore } from '../config/linkTemplates.js';
@@ -192,6 +192,7 @@ export class Backend {
192
192
  describe: (interfaceName, address, paramset) => this.#describe(interfaceName, address, paramset),
193
193
  read: (interfaceName, method, params) => this.#read(interfaceName, method, params),
194
194
  write: (interfaceName, method, params) => this.#write(interfaceName, method, params),
195
+ offers: (interfaceName, method) => this.#offersConfigMaintenance(interfaceName, method),
195
196
  onProgress: (progress) => {
196
197
  this.events.emit('write.progress', progress);
197
198
  },
@@ -390,6 +391,10 @@ export class Backend {
390
391
  case 'interfaces.reconnect':
391
392
  await this.#requireManager().reconnect(p[0]);
392
393
  return null;
394
+ case 'interfaces.methodNames': {
395
+ const listed = await this.#methodList(p[0]);
396
+ return listed === undefined ? null : [...listed];
397
+ }
393
398
  case 'rega.state':
394
399
  return this.#rega?.state ?? { enabled: this.#config.connection.rega, reachable: false, names: 0 };
395
400
  case 'devices.list':
@@ -403,10 +408,10 @@ export class Backend {
403
408
  case 'devices.reportValueUsage':
404
409
  return Number(await this.#write(p[0], 'reportValueUsage', [p[1], p[2], p[3]]));
405
410
  case 'devices.restoreConfig':
406
- await this.#write(p[0], 'restoreConfigToDevice', [p[1]]);
411
+ await this.#configMaintenance(p[0], 'restoreConfigToDevice', p[1]);
407
412
  return null;
408
413
  case 'devices.clearConfigCache':
409
- await this.#write(p[0], 'clearConfigCache', [p[1]]);
414
+ await this.#configMaintenance(p[0], 'clearConfigCache', p[1]);
410
415
  return null;
411
416
  case 'devices.repairConfig':
412
417
  return this.#repair.repair(p[0], p[1], params[2] ?? {});
@@ -1782,8 +1787,9 @@ export class Backend {
1782
1787
  return listed === undefined || listed.has('getServiceMessages');
1783
1788
  }
1784
1789
  /**
1785
- * B-26 (#158): the methods a user-defined interface lists in `system.listMethods`, or
1786
- * `undefined` when it gave no usable list.
1790
+ * B-26 (#158): the methods an interface lists in `system.listMethods`, or `undefined` when it
1791
+ * gave no usable list. Used for user-defined interfaces' service messages and, since task 115,
1792
+ * for the BidCos maintenance calls of every interface.
1787
1793
  *
1788
1794
  * Asked once and shared by concurrent callers; the answer is dropped when the interface
1789
1795
  * subscribes again. A process that does not have `system.listMethods` either is remembered for
@@ -1813,6 +1819,22 @@ export class Backend {
1813
1819
  this.#listedMethods.set(interfaceName, pending);
1814
1820
  return pending;
1815
1821
  }
1822
+ /**
1823
+ * Task 115: does this interface offer `restoreConfigToDevice` / `clearConfigCache`? Its own
1824
+ * `system.listMethods` decides, never on HmIP; see `offersConfigMaintenance`.
1825
+ */
1826
+ async #offersConfigMaintenance(interfaceName, method) {
1827
+ const listed = await this.#methodList(interfaceName);
1828
+ const type = this.#manager?.states().find((state) => state.name === interfaceName)?.type ?? '';
1829
+ return offersConfigMaintenance(interfaceName, type, method, listed);
1830
+ }
1831
+ /** `devices.restoreConfig` and `devices.clearConfigCache`: refused where the interface lacks the method. */
1832
+ async #configMaintenance(interfaceName, method, address) {
1833
+ if (!(await this.#offersConfigMaintenance(interfaceName, method))) {
1834
+ throw validationError(`${interfaceName} does not offer ${method}`);
1835
+ }
1836
+ await this.#write(interfaceName, method, [address]);
1837
+ }
1816
1838
  /** Reads the BidCos service messages of one interface into the store. */
1817
1839
  async #refreshServiceMessages(interfaceName) {
1818
1840
  if (!(await this.#hasServiceMessages(interfaceName))) {
@@ -2183,6 +2205,7 @@ export const API_METHOD_NAMES = [
2183
2205
  'connection.pairCancel',
2184
2206
  'interfaces.list',
2185
2207
  'interfaces.reconnect',
2208
+ 'interfaces.methodNames',
2186
2209
  'rega.state',
2187
2210
  'devices.list',
2188
2211
  'devices.description',
@@ -10,16 +10,32 @@
10
10
  * with 100 devices is a minute of RPC traffic, and it is the same answer every time. The identity
11
11
  * carries the firmware and the version, so a device that was updated gets a new key rather than a
12
12
  * stale description - and it is the same key `multiApplyEligibility()` compares (task 6.3).
13
+ *
14
+ * **Stored in shards, one per interface and device type.** A CCU with a few dozen device types
15
+ * has megabytes of descriptions; kept in one file, every description fetched for a type not seen
16
+ * before rewrote all of them, on the addon to the CCU's SD card. Each shard is its own file now
17
+ * (`CacheStore` decides where), and only the shards that gained something are written. A device
18
+ * of a type that is cached already writes nothing at all.
13
19
  */
14
20
  import { type DeviceDescription, type ParamsetDescription } from '@homematic-manager/core';
15
21
  /** What is written to `<cache>/descriptions.json`: identity -> description. */
16
22
  export type DescriptionCacheSnapshot = Record<string, ParamsetDescription>;
23
+ /**
24
+ * The shard an identity belongs to: its interface and device type (`BidCos-RF/HM-LC-Sw1-Pl`).
25
+ * Only a bucket - the identity itself is what a shard file is keyed by.
26
+ */
27
+ export declare function shardOf(identity: string): string;
17
28
  export declare class ParamsetDescriptionCache {
18
29
  #private;
19
30
  get size(): number;
20
- /** True when something was stored since the last `markClean()`. */
31
+ /** True when something was stored since the last `takeDirty()`. */
21
32
  get dirty(): boolean;
22
- markClean(): void;
33
+ /** The shards that changed since the last call, and forgets them. */
34
+ takeDirty(): string[];
35
+ /** Every shard that holds something. */
36
+ shards(): string[];
37
+ /** What is written to the file of one shard: identity -> description; empty when it holds nothing. */
38
+ shardSnapshot(shard: string): DescriptionCacheSnapshot;
23
39
  /**
24
40
  * The identity of a paramset, or `undefined` when the device is not in the index - which is the
25
41
  * case for a channel whose parent has not been listed yet, and means "do not cache this".
@@ -31,6 +47,9 @@ export declare class ParamsetDescriptionCache {
31
47
  /** Drops everything, or everything of one interface (the identity starts with its name). */
32
48
  clear(interfaceName?: string): void;
33
49
  toJSON(): DescriptionCacheSnapshot;
50
+ /** Replaces everything with one snapshot (a shard file, or the single file of 3.5 and older). */
34
51
  load(snapshot: unknown): void;
52
+ /** Adds a snapshot to what is there, without marking anything changed: it came from disk. */
53
+ merge(snapshot: unknown): void;
35
54
  }
36
55
  //# sourceMappingURL=descriptions.d.ts.map
@@ -10,20 +10,51 @@
10
10
  * with 100 devices is a minute of RPC traffic, and it is the same answer every time. The identity
11
11
  * carries the firmware and the version, so a device that was updated gets a new key rather than a
12
12
  * stale description - and it is the same key `multiApplyEligibility()` compares (task 6.3).
13
+ *
14
+ * **Stored in shards, one per interface and device type.** A CCU with a few dozen device types
15
+ * has megabytes of descriptions; kept in one file, every description fetched for a type not seen
16
+ * before rewrote all of them, on the addon to the CCU's SD card. Each shard is its own file now
17
+ * (`CacheStore` decides where), and only the shards that gained something are written. A device
18
+ * of a type that is cached already writes nothing at all.
13
19
  */
14
20
  import { paramsetIdentity } from '@homematic-manager/core';
21
+ /**
22
+ * The shard an identity belongs to: its interface and device type (`BidCos-RF/HM-LC-Sw1-Pl`).
23
+ * Only a bucket - the identity itself is what a shard file is keyed by.
24
+ */
25
+ export function shardOf(identity) {
26
+ const [interfaceName = '', deviceType = ''] = identity.split('/');
27
+ return `${interfaceName}/${deviceType}`;
28
+ }
15
29
  export class ParamsetDescriptionCache {
16
30
  #byIdentity = new Map();
17
- #dirty = false;
31
+ #dirtyShards = new Set();
18
32
  get size() {
19
33
  return this.#byIdentity.size;
20
34
  }
21
- /** True when something was stored since the last `markClean()`. */
35
+ /** True when something was stored since the last `takeDirty()`. */
22
36
  get dirty() {
23
- return this.#dirty;
37
+ return this.#dirtyShards.size > 0;
38
+ }
39
+ /** The shards that changed since the last call, and forgets them. */
40
+ takeDirty() {
41
+ const shards = [...this.#dirtyShards];
42
+ this.#dirtyShards.clear();
43
+ return shards;
44
+ }
45
+ /** Every shard that holds something. */
46
+ shards() {
47
+ return [...new Set([...this.#byIdentity.keys()].map((identity) => shardOf(identity)))];
24
48
  }
25
- markClean() {
26
- this.#dirty = false;
49
+ /** What is written to the file of one shard: identity -> description; empty when it holds nothing. */
50
+ shardSnapshot(shard) {
51
+ const snapshot = {};
52
+ for (const [identity, description] of this.#byIdentity) {
53
+ if (shardOf(identity) === shard) {
54
+ snapshot[identity] = description;
55
+ }
56
+ }
57
+ return snapshot;
27
58
  }
28
59
  /**
29
60
  * The identity of a paramset, or `undefined` when the device is not in the index - which is the
@@ -44,31 +75,35 @@ export class ParamsetDescriptionCache {
44
75
  if (identity === undefined) {
45
76
  return;
46
77
  }
78
+ const known = this.#byIdentity.get(identity);
47
79
  this.#byIdentity.set(identity, description);
48
- this.#dirty = true;
80
+ if (known === undefined || JSON.stringify(known) !== JSON.stringify(description)) {
81
+ this.#dirtyShards.add(shardOf(identity));
82
+ }
49
83
  }
50
84
  has(identity) {
51
85
  return identity !== undefined && this.#byIdentity.has(identity);
52
86
  }
53
87
  /** Drops everything, or everything of one interface (the identity starts with its name). */
54
88
  clear(interfaceName) {
55
- if (interfaceName === undefined) {
56
- this.#byIdentity.clear();
57
- }
58
- else {
59
- for (const identity of [...this.#byIdentity.keys()]) {
60
- if (identity.startsWith(`${interfaceName}/`)) {
61
- this.#byIdentity.delete(identity);
62
- }
89
+ for (const identity of [...this.#byIdentity.keys()]) {
90
+ if (interfaceName === undefined || identity.startsWith(`${interfaceName}/`)) {
91
+ this.#byIdentity.delete(identity);
92
+ this.#dirtyShards.add(shardOf(identity));
63
93
  }
64
94
  }
65
- this.#dirty = true;
66
95
  }
67
96
  toJSON() {
68
97
  return Object.fromEntries(this.#byIdentity);
69
98
  }
99
+ /** Replaces everything with one snapshot (a shard file, or the single file of 3.5 and older). */
70
100
  load(snapshot) {
71
101
  this.#byIdentity.clear();
102
+ this.#dirtyShards.clear();
103
+ this.merge(snapshot);
104
+ }
105
+ /** Adds a snapshot to what is there, without marking anything changed: it came from disk. */
106
+ merge(snapshot) {
72
107
  if (typeof snapshot === 'object' && snapshot !== null) {
73
108
  for (const [identity, description] of Object.entries(snapshot)) {
74
109
  if (typeof description === 'object' && description !== null && !Array.isArray(description)) {
@@ -76,7 +111,6 @@ export class ParamsetDescriptionCache {
76
111
  }
77
112
  }
78
113
  }
79
- this.#dirty = false;
80
114
  }
81
115
  }
82
116
  //# sourceMappingURL=descriptions.js.map
@@ -8,7 +8,12 @@
8
8
  * that is thrown away on restart answers no question at all.
9
9
  *
10
10
  * The files are written debounced (`DebouncedJsonFile`), so a CCU that reports 400 devices in one
11
- * burst causes one write, not 400 as 2.x did.
11
+ * burst causes one write, not 400 as 2.x did, and a file whose content did not change is not
12
+ * written at all (`writeJsonFile`). The paramset descriptions are one file per interface and device
13
+ * type under `descriptions/`; the single `descriptions.json` of 3.5 and older is read once, split
14
+ * and removed. The unreach counters wait a minute before they are written: a device that flaps
15
+ * produces an edge per minute or more, and losing the last minute of counts to a power cut costs
16
+ * less than writing the file after each one.
12
17
  */
13
18
  import { RingBuffer, RssiStore, ServiceMessageStore, type EventRecord, type ServiceMessage } from '@homematic-manager/core';
14
19
  import { DeviceCache } from './devices.js';
@@ -24,9 +29,13 @@ export interface CacheStoreOptions {
24
29
  readonly eventBufferSize?: number;
25
30
  /** Debounce of the cache files. */
26
31
  readonly writeDelayMs?: number;
32
+ /** Debounce of `unreach.json`; a minute by default, `writeDelayMs` when only that is given. */
33
+ readonly unreachWriteDelayMs?: number;
27
34
  /** A cache that cannot be written is reported, never thrown. */
28
35
  readonly onError?: (error: unknown) => void;
29
36
  }
37
+ /** How long the unreach counters wait before they are written. */
38
+ export declare const UNREACH_WRITE_DELAY_MS = 60000;
30
39
  /** The caches of one connection. */
31
40
  export declare class CacheStore {
32
41
  #private;
@@ -40,9 +49,10 @@ export declare class CacheStore {
40
49
  constructor(options: CacheStoreOptions);
41
50
  /** The RSSI matrix of one interface; created on first use. */
42
51
  rssi(interfaceName: string): RssiStore;
43
- /** Reads the three persisted caches. Never throws; a missing file means "nothing cached". */
52
+ /** Reads the persisted caches. Never throws; a missing file means "nothing cached". */
44
53
  load(): Promise<void>;
45
54
  saveDevices(): void;
55
+ /** Writes the shards that gained (or lost) something, and only those. */
46
56
  saveDescriptions(): void;
47
57
  saveNames(): void;
48
58
  saveUnreach(): void;
@@ -8,14 +8,60 @@
8
8
  * that is thrown away on restart answers no question at all.
9
9
  *
10
10
  * The files are written debounced (`DebouncedJsonFile`), so a CCU that reports 400 devices in one
11
- * burst causes one write, not 400 as 2.x did.
11
+ * burst causes one write, not 400 as 2.x did, and a file whose content did not change is not
12
+ * written at all (`writeJsonFile`). The paramset descriptions are one file per interface and device
13
+ * type under `descriptions/`; the single `descriptions.json` of 3.5 and older is read once, split
14
+ * and removed. The unreach counters wait a minute before they are written: a device that flaps
15
+ * produces an edge per minute or more, and losing the last minute of counts to a power cut costs
16
+ * less than writing the file after each one.
12
17
  */
18
+ import { createHash } from 'node:crypto';
19
+ import fs from 'node:fs/promises';
20
+ import path from 'node:path';
13
21
  import { RingBuffer, RssiStore, ServiceMessageStore, } from '@homematic-manager/core';
14
- import { DebouncedJsonFile } from '../util/jsonFile.js';
22
+ import { DebouncedJsonFile, readJsonFile, removeFile, writeJsonFile } from '../util/jsonFile.js';
15
23
  import { DeviceCache } from './devices.js';
16
24
  import { ParamsetDescriptionCache } from './descriptions.js';
17
25
  import { NameStore } from './names.js';
18
26
  import { UnreachCache } from './unreach.js';
27
+ /** How long the unreach counters wait before they are written. */
28
+ export const UNREACH_WRITE_DELAY_MS = 60_000;
29
+ /** A file name made of anything: letters, digits, `-` and `_` stay, the rest is `%xx`, lower-cased. */
30
+ function safeName(name) {
31
+ const safe = [...Buffer.from(name, 'utf8')]
32
+ .map((byte) => {
33
+ const char = String.fromCharCode(byte);
34
+ return /[A-Za-z0-9_-]/.test(char) ? char : `%${byte.toString(16).padStart(2, '0')}`;
35
+ })
36
+ .join('');
37
+ return (safe === '' ? '%' : safe).toLowerCase();
38
+ }
39
+ /** The `.json` files one level below the shard directory; none when it does not exist. */
40
+ async function shardFiles(dir) {
41
+ const files = [];
42
+ let interfaces;
43
+ try {
44
+ interfaces = await fs.readdir(dir);
45
+ }
46
+ catch {
47
+ return files;
48
+ }
49
+ for (const interfaceDir of interfaces.sort()) {
50
+ let names;
51
+ try {
52
+ names = await fs.readdir(path.join(dir, interfaceDir));
53
+ }
54
+ catch {
55
+ continue;
56
+ }
57
+ for (const name of names.sort()) {
58
+ if (name.endsWith('.json')) {
59
+ files.push(path.join(dir, interfaceDir, name));
60
+ }
61
+ }
62
+ }
63
+ return files;
64
+ }
19
65
  /** The caches of one connection. */
20
66
  export class CacheStore {
21
67
  devices = new DeviceCache();
@@ -28,9 +74,11 @@ export class CacheStore {
28
74
  #rssi = new Map();
29
75
  #now;
30
76
  #deviceFile;
31
- #descriptionFile;
77
+ #descriptionFiles = new Map();
32
78
  #nameFile;
33
79
  #unreachFile;
80
+ #cacheDir;
81
+ #fileOptions;
34
82
  constructor(options) {
35
83
  this.#now = options.now ?? (() => Date.now());
36
84
  this.serviceMessages = new ServiceMessageStore({ now: this.#now });
@@ -39,10 +87,40 @@ export class CacheStore {
39
87
  delayMs: options.writeDelayMs ?? 500,
40
88
  ...(options.onError ? { onError: options.onError } : {}),
41
89
  };
90
+ this.#cacheDir = options.cacheDir;
91
+ this.#fileOptions = fileOptions;
42
92
  this.#deviceFile = new DebouncedJsonFile(`${options.cacheDir}/devices.json`, fileOptions);
43
- this.#descriptionFile = new DebouncedJsonFile(`${options.cacheDir}/descriptions.json`, fileOptions);
44
93
  this.#nameFile = new DebouncedJsonFile(`${options.cacheDir}/names.json`, fileOptions);
45
- this.#unreachFile = new DebouncedJsonFile(`${options.cacheDir}/unreach.json`, fileOptions);
94
+ this.#unreachFile = new DebouncedJsonFile(`${options.cacheDir}/unreach.json`, {
95
+ ...fileOptions,
96
+ delayMs: options.unreachWriteDelayMs ?? options.writeDelayMs ?? UNREACH_WRITE_DELAY_MS,
97
+ });
98
+ }
99
+ /** The directory of the description shards. */
100
+ get #descriptionDir() {
101
+ return path.join(this.#cacheDir, 'descriptions');
102
+ }
103
+ /** The single description file of 3.5 and older. */
104
+ get #legacyDescriptionFile() {
105
+ return path.join(this.#cacheDir, 'descriptions.json');
106
+ }
107
+ /**
108
+ * The file of one shard: `descriptions/<interface>/<type>.<hash>.json`. The name is the device
109
+ * type made safe for every file system, lower-cased, and the hash of the exact type keeps two
110
+ * types that differ only in case (`HMIP-eTRV`, `HmIP-eTRV`) apart where names do not.
111
+ */
112
+ #descriptionFile(shard) {
113
+ const existing = this.#descriptionFiles.get(shard);
114
+ if (existing) {
115
+ return existing;
116
+ }
117
+ const separator = shard.indexOf('/');
118
+ const interfaceName = shard.slice(0, separator);
119
+ const deviceType = shard.slice(separator + 1);
120
+ const hash = createHash('sha256').update(deviceType).digest('hex').slice(0, 8);
121
+ const file = new DebouncedJsonFile(path.join(this.#descriptionDir, safeName(interfaceName), `${safeName(deviceType)}.${hash}.json`), this.#fileOptions);
122
+ this.#descriptionFiles.set(shard, file);
123
+ return file;
46
124
  }
47
125
  /** The RSSI matrix of one interface; created on first use. */
48
126
  rssi(interfaceName) {
@@ -54,19 +132,51 @@ export class CacheStore {
54
132
  this.#rssi.set(interfaceName, store);
55
133
  return store;
56
134
  }
57
- /** Reads the three persisted caches. Never throws; a missing file means "nothing cached". */
135
+ /** Reads the persisted caches. Never throws; a missing file means "nothing cached". */
58
136
  async load() {
59
137
  this.devices.load(await this.#deviceFile.read());
60
- this.descriptions.load(await this.#descriptionFile.read());
138
+ await this.#loadDescriptions();
61
139
  this.names.load(await this.#nameFile.read());
62
140
  this.unreach.load(await this.#unreachFile.read());
63
141
  }
142
+ /** Every shard file, then the single file of 3.5 and older, which is split once and removed. */
143
+ async #loadDescriptions() {
144
+ this.descriptions.load(undefined);
145
+ for (const file of await shardFiles(this.#descriptionDir)) {
146
+ this.descriptions.merge(await readJsonFile(file));
147
+ }
148
+ const legacy = await readJsonFile(this.#legacyDescriptionFile);
149
+ if (legacy === undefined) {
150
+ return;
151
+ }
152
+ this.descriptions.merge(legacy);
153
+ this.descriptions.takeDirty();
154
+ try {
155
+ await Promise.all(this.descriptions
156
+ .shards()
157
+ .map((shard) => writeJsonFile(this.#descriptionFile(shard).file, this.descriptions.shardSnapshot(shard))));
158
+ await removeFile(this.#legacyDescriptionFile);
159
+ }
160
+ catch (error) {
161
+ // the old file stays and is split again next time; the cache in memory is complete
162
+ this.#fileOptions.onError?.(error);
163
+ }
164
+ }
64
165
  saveDevices() {
65
166
  this.#deviceFile.save(this.devices.toJSON());
66
167
  }
168
+ /** Writes the shards that gained (or lost) something, and only those. */
67
169
  saveDescriptions() {
68
- this.#descriptionFile.save(this.descriptions.toJSON());
69
- this.descriptions.markClean();
170
+ for (const shard of this.descriptions.takeDirty()) {
171
+ const snapshot = this.descriptions.shardSnapshot(shard);
172
+ const file = this.#descriptionFile(shard);
173
+ if (Object.keys(snapshot).length === 0) {
174
+ void file.remove();
175
+ }
176
+ else {
177
+ file.save(snapshot);
178
+ }
179
+ }
70
180
  }
71
181
  saveNames() {
72
182
  this.#nameFile.save(this.names.toJSON());
@@ -78,7 +188,7 @@ export class CacheStore {
78
188
  async flush() {
79
189
  await Promise.all([
80
190
  this.#deviceFile.flush(),
81
- this.#descriptionFile.flush(),
191
+ ...[...this.#descriptionFiles.values()].map((file) => file.flush()),
82
192
  this.#nameFile.flush(),
83
193
  this.#unreachFile.flush(),
84
194
  ]);
@@ -94,12 +204,17 @@ export class CacheStore {
94
204
  for (const interfaceName of this.serviceMessages.list().map((message) => message.interfaceName)) {
95
205
  this.serviceMessages.replaceInterface(interfaceName, []);
96
206
  }
207
+ this.descriptions.takeDirty();
97
208
  await Promise.all([
98
209
  this.#deviceFile.remove(),
99
- this.#descriptionFile.remove(),
210
+ ...[...this.#descriptionFiles.values()].map((file) => file.remove()),
100
211
  this.#nameFile.remove(),
101
212
  this.#unreachFile.remove(),
213
+ removeFile(this.#legacyDescriptionFile),
102
214
  ]);
215
+ this.#descriptionFiles.clear();
216
+ // shards of another session (a type this one never touched) go with the directory
217
+ await fs.rm(this.#descriptionDir, { recursive: true, force: true }).catch(() => undefined);
103
218
  }
104
219
  /** The service messages in the shape the contract asks for. */
105
220
  listServiceMessages(interfaceName) {
@@ -38,6 +38,12 @@ export interface OcculiteProviderOptions extends MetaProviderEvents {
38
38
  readonly system: SystemLink;
39
39
  /** `<cacheDir>/occulite-meta.json`: the last snapshot, so a restart without the box has names. */
40
40
  readonly cacheFile?: string;
41
+ /**
42
+ * How long changes to the cache file are collected before it is written. The box holds the
43
+ * store; the file is only what a restart without the box shows, so a burst of changes (an
44
+ * import, a room assigned to fifty channels) is one write, not fifty. `stop()` writes it.
45
+ */
46
+ readonly cacheWriteDelayMs?: number;
41
47
  /** `occulited 0.1.0`, from the detection call. */
42
48
  readonly implementation?: string;
43
49
  readonly reconnectMinMs?: number;
@@ -45,6 +51,8 @@ export interface OcculiteProviderOptions extends MetaProviderEvents {
45
51
  /** Injected by the tests in place of `setTimeout`. */
46
52
  readonly wait?: (ms: number, signal: AbortSignal) => Promise<void>;
47
53
  }
54
+ /** How long changes to the cache file are collected; see `cacheWriteDelayMs`. */
55
+ export declare const CACHE_WRITE_DELAY_MS = 5000;
48
56
  export declare class OcculiteProvider implements MetadataProvider {
49
57
  #private;
50
58
  readonly kind: "occulite";
@@ -28,11 +28,13 @@
28
28
  */
29
29
  import { applyEvent, emptyDocument, isMetaError, parseDocument, summariseAll, } from '@homematic-manager/core';
30
30
  import { errorMessage } from '../errors.js';
31
- import { readJsonFile, writeJsonFile } from '../util/jsonFile.js';
31
+ import { DebouncedJsonFile } from '../util/jsonFile.js';
32
32
  /** First wait before the event stream is opened again, in milliseconds. */
33
33
  export const RECONNECT_MIN_MS = 2000;
34
34
  /** Longest wait between two attempts. A box that is being updated is back well inside a minute. */
35
35
  export const RECONNECT_MAX_MS = 60_000;
36
+ /** How long changes to the cache file are collected; see `cacheWriteDelayMs`. */
37
+ export const CACHE_WRITE_DELAY_MS = 5000;
36
38
  export class OcculiteProvider {
37
39
  kind = 'occulite';
38
40
  #options;
@@ -47,9 +49,19 @@ export class OcculiteProvider {
47
49
  #lastNotice = '';
48
50
  /** Ends the wait between two attempts at the event stream; set while the loop is sleeping. */
49
51
  #wake;
52
+ #cache;
50
53
  constructor(options) {
51
54
  this.#options = options;
52
55
  this.#system = options.system;
56
+ this.#cache =
57
+ options.cacheFile === undefined
58
+ ? undefined
59
+ : new DebouncedJsonFile(options.cacheFile, {
60
+ delayMs: options.cacheWriteDelayMs ?? CACHE_WRITE_DELAY_MS,
61
+ onError: (error) => {
62
+ options.onNotice('warn', `the metadata cache could not be written: ${errorMessage(error)}`);
63
+ },
64
+ });
53
65
  }
54
66
  state() {
55
67
  return {
@@ -90,6 +102,7 @@ export class OcculiteProvider {
90
102
  // the loop ends by being aborted; that is not a failure
91
103
  }
92
104
  this.#loop = undefined;
105
+ await this.#cache?.flush();
93
106
  }
94
107
  /**
95
108
  * A fresh snapshot, on demand - the credential changed, or a host asked for one.
@@ -196,7 +209,7 @@ export class OcculiteProvider {
196
209
  // change nobody announced
197
210
  this.#options.onStateChanged(this.state());
198
211
  this.#options.onChanged();
199
- await this.#saveCache();
212
+ this.#saveCache();
200
213
  }
201
214
  catch (error) {
202
215
  this.#fail(error);
@@ -235,7 +248,7 @@ export class OcculiteProvider {
235
248
  this.#document = next;
236
249
  this.#options.onStateChanged(this.state());
237
250
  this.#options.onChanged();
238
- await this.#saveCache();
251
+ this.#saveCache();
239
252
  }
240
253
  }
241
254
  catch (error) {
@@ -267,10 +280,7 @@ export class OcculiteProvider {
267
280
  }
268
281
  }
269
282
  async #loadCache() {
270
- if (this.#options.cacheFile === undefined) {
271
- return;
272
- }
273
- const raw = await readJsonFile(this.#options.cacheFile);
283
+ const raw = await this.#cache?.read();
274
284
  if (raw === undefined) {
275
285
  return;
276
286
  }
@@ -283,16 +293,9 @@ export class OcculiteProvider {
283
293
  // next snapshot and nobody needs to hear about it
284
294
  }
285
295
  }
286
- async #saveCache() {
287
- if (this.#options.cacheFile === undefined) {
288
- return;
289
- }
290
- try {
291
- await writeJsonFile(this.#options.cacheFile, this.#document);
292
- }
293
- catch (error) {
294
- this.#options.onNotice('warn', `the metadata cache could not be written: ${errorMessage(error)}`);
295
- }
296
+ /** Debounced; a snapshot that equals the file (every reconnect) is not written at all. */
297
+ #saveCache() {
298
+ this.#cache?.save(this.#document);
296
299
  }
297
300
  #sleep(ms, signal) {
298
301
  if (this.#options.wait) {
@@ -84,9 +84,14 @@ export declare function acknowledgeAlarmScript(interfaceName: string, address: s
84
84
  * B-74 (#150): an alarm stays oncoming until it is receipted, whatever the interface process
85
85
  * reports meanwhile - rfd forgets a `STICKY_UNREACH` at a restart, ReGa does not - so the
86
86
  * WebUI lists messages `getServiceMessages` does not. The value is what such a message is shown
87
- * with.
87
+ * with. *
88
+ * Task 119: the name and the value go out through `WriteURL()`, like every other name this
89
+ * application reads from ReGa, so a tab or a line break in either cannot shift the fields or split
90
+ * the line (the CCU WebUI's lists broke on such names, OpenCCU-Base #304 and others). The value is
91
+ * `Value().ToString()`, which prints what `Write(Value())` printed: `true`/`false`, `21.500000`,
92
+ * an ENUM's index (checked on the lab's stock OpenCCU 3.89.8).
88
93
  */
89
- export declare const REGA_ALARMS_SCRIPT = "string sId;\nforeach (sId, dom.GetObject(ID_SERVICES).EnumIDs()) {\n object oAlarm = dom.GetObject(sId);\n if (oAlarm) {\n if (oAlarm.IsTypeOf(OT_ALARMDP) && (oAlarm.Used() == true) && (oAlarm.Enabled() == true) && (oAlarm.AlState() == asOncoming)) {\n object oTrigger = dom.GetObject(oAlarm.AlTriggerDP());\n if (oTrigger) {\n Write(oTrigger.Name() # \"\\t\" # oAlarm.AlOccurrenceTime().ToInteger() # \"\\t\" # oAlarm.Timestamp().ToInteger() # \"\\t\" # oTrigger.Value() # \"\\n\");\n }\n }\n }\n}\n";
94
+ export declare const REGA_ALARMS_SCRIPT = "string sId;\nforeach (sId, dom.GetObject(ID_SERVICES).EnumIDs()) {\n object oAlarm = dom.GetObject(sId);\n if (oAlarm) {\n if (oAlarm.IsTypeOf(OT_ALARMDP) && (oAlarm.Used() == true) && (oAlarm.Enabled() == true) && (oAlarm.AlState() == asOncoming)) {\n object oTrigger = dom.GetObject(oAlarm.AlTriggerDP());\n if (oTrigger) {\n WriteURL(oTrigger.Name());\n Write(\"\\t\" # oAlarm.AlOccurrenceTime().ToInteger() # \"\\t\" # oAlarm.Timestamp().ToInteger() # \"\\t\");\n WriteURL(oTrigger.Value().ToString());\n Write(\"\\n\");\n }\n }\n }\n}\n";
90
95
  /** One pending ReGa service message: whose datapoint, its value, first and last reported (epoch ms). */
91
96
  export interface RegaAlarm {
92
97
  readonly interfaceName: string;
@@ -98,10 +103,11 @@ export interface RegaAlarm {
98
103
  readonly last: number;
99
104
  }
100
105
  /**
101
- * Reads what {@link REGA_ALARMS_SCRIPT} wrote. A line whose name is not `<interface>.<channel>.<datapoint>`
102
- * (a system alarm, a CUxD name with more dots) or whose time is no positive number is skipped. The
103
- * value column is ReGa's text of the value: `true`/`false`, a number as it prints it (an ENUM by
104
- * its index), anything else stays a string; a line without it means `true`.
106
+ * Reads what {@link REGA_ALARMS_SCRIPT} wrote. Name and value are `WriteURL()`-escaped and decoded
107
+ * here (task 119). A line whose name is not `<interface>.<channel>.<datapoint>` (a system alarm, a
108
+ * CUxD name with more dots) or whose time is no positive number is skipped. The value column is
109
+ * ReGa's text of the value: `true`/`false`, a number as it prints it (an ENUM by its index),
110
+ * anything else stays a string; a line without it means `true`.
105
111
  */
106
112
  export declare function parseRegaAlarms(output: string): RegaAlarm[];
107
113
  /**