iobroker.sql 4.5.1 → 4.7.0

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.
package/README.md CHANGED
@@ -237,6 +237,13 @@ Structure:
237
237
 
238
238
  *Note:* MS-SQL uses BIT, and others use BOOLEAN. SQLite uses for ts INTEGER and all others BIGINT.
239
239
 
240
+ ## Messages for scripts and AI agents
241
+ `sendTo('sql.0', 'help', {})` answers `{help, commands}`: a description of all messages and of the tables for AI agents (e.g. ioBroker.pi-agent) and script authors, and the list of all commands with `write: true` for the ones that change something.
242
+
243
+ `getHistory`, `aggregate` and `lastChange` are standard commands of the shared catalog of sendTo commands (family `history`, marked with `standard` in the answer of `help`), the same in history, sql, influxdb and recorder:
244
+ - `aggregate {id, start, end?, fn, value?}` answers one number for a period, `{value, ts?, unit?, count}`. `fn`: `min`, `max`, `avg`, `sum`, `count` (with `value`: how often the state became it), `delta` (how much a counter rose, resets included), `first`, `last`, `integral` (value × hours, W gives Wh), `duration` (with `value`: seconds the state had it).
245
+ - `lastChange {id, value?, before?}` answers when the state last changed (to `value`): `{ts, val}`.
246
+
240
247
  ## Access values from Javascript adapter
241
248
  The sorted values can be accessed from JavaScript adapter.
242
249
 
@@ -664,6 +671,13 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
664
671
  -->
665
672
 
666
673
  ## Changelog
674
+ ### 4.7.0 (2026-11-23)
675
+ * (@GermanBluefox) Fixed: getHistory checks the range of `percentile` (0-100) and `quantile` (0-1) only for these aggregates (misplaced parentheses in the check)
676
+ * (@GermanBluefox) Added the standard commands of the shared catalog: history.aggregate (one number for a period: min, max, avg, sum, count, delta, first, last, integral, duration) and history.lastChange; getHistory is marked as history.getHistory
677
+
678
+ ### 4.6.0 (2026-11-19)
679
+ * (@GermanBluefox) Added the message "help": a description of all messages for AI agents (e.g. pi-agent), and `common.supportedMessages.help`
680
+
667
681
  ### 4.5.1 (2026-11-17)
668
682
  * (@Schimi1983) "Clean up" no longer deletes the history of datapoints that are logged under an alias name, and stops with an error instead of deleting everything when the object database cannot be read (#587)
669
683
  * (@Schimi1983) MySQL/MariaDB: new tables use `utf8mb4`, so values, IDs and sources with emojis are stored instead of failing, and the names compare case-sensitively (`utf8mb4_bin`), also in a database created by a hoster. Existing tables are not changed; the README explains how to convert them (#588)
@@ -678,37 +692,6 @@ sendTo('sql.0', 'getEnabledDPs', {}, function (result) {
678
692
  * (@GermanBluefox) phpMyAdmin container: new instances listen on `127.0.0.1` by default instead of on all network interfaces. Existing instances keep their setting; to reach phpMyAdmin from another machine, choose the IP in the instance settings (#587)
679
693
  * (@Schimi1983) PostgreSQL: text values, datapoint IDs and sources are written as escape string literals (`E'...'`), so a backslash can no longer end a value early when `standard_conforming_strings` is off for the database or the user (#587)
680
694
 
681
- ### 4.4.0 (2026-11-05)
682
- * (@Schimi1983) Booleans are stored the same in all databases: `on`/`yes`/`true`/`1` as true, `off`/`no`/`false`/`0` and an empty text as false, any other text as NULL. Before, PostgreSQL failed the whole batch on such a text or a number, SQLite and MS SQL stored `off` as true. `storeState` says "values are kept, do not send them again" also when its values were written together with others of the same datapoint (#587)
683
- * (@Schimi1983) Messages are checked before they reach the database: `update`, `delete`, `deleteRange`, `deleteAll`, `storeState`, `getHistory` and `getCounter` refuse an entry without an ID, with a timestamp that is not a point in time, or with a value that does not fit the stored type, and report it in the answer instead of writing it into the SQL. Before, a `deleteRange` with an unparsable `start` deleted the whole history of the datapoint, a `delete` without an ID the history of the first datapoint of the table, a `start` given as a numeric string became `NaN`, and a value with a quote or a quote in a datapoint ID broke the statement (PostgreSQL, SQLite, MSSQL: quotes are now stored as they are instead of being removed, `Infinity` is stored as NULL). `storeState` with a value that is not a number for a numeric datapoint is answered again instead of waiting forever; a list of entries is answered after the last entry was written, with the errors of the entries that failed; a message with an unexpected shape no longer stops the adapter; "Maximum concurrent connections" of 0 no longer blocks every write (#587)
684
- * (@Schimi1983) MySQL: if the server's `sql_mode` contains `NO_BACKSLASH_ESCAPES`, the adapter removes it for its own connections and says so in the log - with that mode, values with `'` or `\` cannot be stored safely. The server's setting and other clients are not changed. Booleans: `on`/`yes`/`true`/`1` are stored as true, `off`/`no`/`false`/`0` and an empty text as false, any other text as NULL instead of true; a number is true unless it is 0 (#587)
685
- * (@Schimi1983) Stopping with many datapoints no longer loses values: the buffers of all datapoints are written at once instead of 50 per second, which did not finish within the 10 s stop timeout beyond about 450 datapoints. SQLite: buffered values of more than 100 datapoints no longer hit the task limit ("Cannot queue new requests"), a datapoint has one queued insert that takes further values (#587)
686
- * (@Schimi1983) MySQL: values, datapoint IDs and sources are passed as bound parameters instead of being inlined. Text values keep their single quotes (`it's` was stored as `its`), a value ending with a backslash no longer makes the whole batch fail, and the `delete`/`update`/`storeState` messages cannot inject SQL any more. `NaN`/`Infinity` are stored as NULL instead of failing the batch (#587)
687
- * (copilot) Adapter requires node.js >= 22.19.0 now
688
- * (@GermanBluefox) Fixed: values stored without `from` were missing in `getHistory` with `from: true`, e.g. in the history data of admin
689
- * (@Schimi1983) A failed write is no longer silently dropped: the error is passed on, so `storeState` reports it instead of `success: true`. If the database was not reachable, the values are kept and written with the next write of the datapoint (at most 2000 per datapoint, the oldest are dropped first, with a warning). Pooled connections that were idle for more than 60 s are closed and replaced, so a server-side `wait_timeout` no longer resets them; the warning "SQL connection lost" every few minutes on hosted databases is gone (#587)
690
- * (@GermanBluefox) The values kept while the database is not reachable are also limited to 200000 for all datapoints together (about 70 MB), so a long outage with many datapoints can no longer exhaust the memory. The warning about them is one line per minute for all datapoints instead of one per datapoint, and the error of `storeState` says when the values were kept, so they are not sent twice (#587)
691
- * (@GermanBluefox) Data browser: the values of a datapoint can be exported as CSV (e.g. for Excel) or as JSON (the format of `storeState`) for the selected time range. `getRawEntries` returns up to 5000 entries per call and accepts `noTotal` to skip the count
692
- * (@GermanBluefox) Data browser: PostgreSQL and MS SQL showed the time of a value as a bare number, because `getRawEntries` returned `ts` as string there
693
- * (@GermanBluefox) MySQL/MariaDB and MS SQL: datapoints whose IDs differ only in case (e.g. `alias.0.Licht` and `alias.0.licht`) or by trailing spaces no longer write into one series with the type of the first one. The second one gets its own row from now on; values that were already mixed stay where they are (#588)
694
- * (@GermanBluefox) MS SQL: `@azure/msal-node`, a dependency of the driver, was updated to 7.2.0 because of CVE-2026-109461 (GHSA-xcx6-jx8p-x3h5). It concerns the Azure authorization code flow, which the adapter does not use
695
-
696
- ### 4.3.0 (2026-10-29)
697
- * (@GermanBluefox) `getHistory` accepts `intervalBorders`: the client can send the borders of the intervals itself, e.g. the local days of a chart. With `count` or `step` every interval after a switch of the daylight saving time ended an hour away from the midnight, so a value written at 23:59:59 was shown on the next day (ioBroker/ioBroker.echarts#1311)
698
- * (@Schimi1983) Fixed every write failing with "Can't add new command when connection is in closed state" until a restart: a connection the server closed while a statement was running was handed out again, because mysql2 reports that only to the statement and not as a connection error. Such a connection is also no longer handed to a write that waits for a free connection, and the reconnect is logged as a warning in this case too (#587)
699
- * (@Schimi1983) Fixed "Record changes only" storing every string value again: the reference value was overwritten with the SQL literal, or with the converted value when a storage type is set (#587)
700
- * (@Schimi1983) "Reset DB" no longer drops the whole database when "Do not create database" is set, only the adapter's tables. MSSQL: `DBCC FREEPROCCACHE` is then skipped too, as it needs server rights (#587)
701
- * (@Schimi1983) "Ignore values below/above" now also works with the limit 0 (users who set 0 now get the filter they configured) and accepts a decimal comma (#587)
702
- * (@Schimi1983) PostgreSQL: the password is no longer printed in the connection log (#587)
703
- * (@Schimi1983) Fixed a crash when a datapoint is disabled while its database ID is being looked up (#587)
704
- * (@Schimi1983) Disabling the logging of a datapoint with an alias ID works again (#587)
705
- * (@Schimi1983) Admin: every input has size attributes for all screen widths, "Do not create database" no longer grows wider on large screens (#583)
706
- * (@Schimi1983) Added the Ukrainian title and description, admin >= 7.6.20 is required (#583)
707
- * (@Schimi1983) `password` and `dockerMysql.rootPassword` are no longer readable by other adapters (`protectedNative`, #583). Note: a script that reads `system.adapter.sql.0` with `getObject` and writes it back with `setObject` now deletes both passwords; use `extendObject` instead
708
- * (@Schimi1983) README: the reinstall hint for SQLite uses `iobroker rebuild sqlite3` instead of `npm install` (#583)
709
- * (@Schimi1983) CI: the job with the unit and SQLite tests is named `adapter-tests`, as the repository checker expects, and also runs on Node.js 26 (#583)
710
- * (@GermanBluefox) Updated packages, `@iobroker/aggregate` 1.1.0
711
-
712
695
  [Older changelogs can be found there](CHANGELOG_OLD.md)
713
696
 
714
697
  ## License
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ /**
3
+ * The answer of the message `help`: what the instance answers, written for an AI agent (e.g. ioBroker.pi-agent, or
4
+ * the MCP server with `send_to`) and for script authors. Keep it in sync with `#dispatchMessage` in main.ts.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.HELP = exports.COMMANDS = void 0;
8
+ /**
9
+ * Every command `#dispatchMessage` answers; `write` = it changes data, settings or the instance; `standard` = it
10
+ * follows the shared catalog of sendTo commands (HELP.md of ioBroker.assistant), the same in history, sql, influxdb
11
+ * and recorder
12
+ */
13
+ exports.COMMANDS = [
14
+ { command: 'help', write: false },
15
+ { command: 'getHistory', write: false, standard: 'history.getHistory' },
16
+ { command: 'getCounter', write: false },
17
+ { command: 'aggregate', write: false, standard: 'history.aggregate' },
18
+ { command: 'lastChange', write: false, standard: 'history.lastChange' },
19
+ { command: 'getEnabledDPs', write: false },
20
+ { command: 'getDatapoints', write: false },
21
+ { command: 'getDpOverview', write: false },
22
+ { command: 'getRawEntries', write: false },
23
+ { command: 'getDpStatistics', write: false },
24
+ { command: 'features', write: false },
25
+ { command: 'test', write: false },
26
+ { command: 'query', write: true },
27
+ { command: 'enableHistory', write: true },
28
+ { command: 'disableHistory', write: true },
29
+ { command: 'storeState', write: true },
30
+ { command: 'update', write: true },
31
+ { command: 'delete', write: true },
32
+ { command: 'deleteRange', write: true },
33
+ { command: 'deleteAll', write: true },
34
+ { command: 'cleanupOrphaned', write: true },
35
+ { command: 'destroy', write: true },
36
+ { command: 'stopInstance', write: true },
37
+ ];
38
+ exports.HELP = `ioBroker.sql: stores the history of the states that are enabled for it (per state in the object settings) in an
39
+ SQL database: MySQL/MariaDB, PostgreSQL, MS SQL Server or SQLite (native.dbtype of system.adapter.sql.0). An agent
40
+ can read the course of a state (the stored values or one value per interval), the consumption of a counter, list
41
+ the logged states and the stored data, run a SELECT and, only on the user's request, enable or disable the
42
+ logging and store, change or delete values.
43
+
44
+ Times (start, end, ts): milliseconds since 1970 or a date text such as "2026-11-19T08:00" (local time of the host).
45
+ Times in the answers and in the tables are milliseconds since 1970.
46
+
47
+ Tables (native.dbname of the instance, default "iobroker", qualifies them in MySQL and MS SQL only):
48
+ - MySQL: \`iobroker\`.datapoints; MS SQL: iobroker.dbo.datapoints; PostgreSQL and SQLite: datapoints.
49
+ - datapoints (id, name = the state ID, type: 0 number, 1 string, 2 boolean); sources (id, name = state.from).
50
+ - ts_number, ts_string, ts_bool (id = datapoints.id, ts in ms, val, ack, _from = sources.id, q): the values, in
51
+ the table of the type. ts_counter (id, ts, val): the readings around a reset or an exchange of a counter.
52
+ - ack and the values of ts_bool: 0/1 in MySQL and SQLite, BOOLEAN in PostgreSQL, BIT in MS SQL. String values
53
+ (objects as JSON) are in ts_string. Dialects: LIMIT n in MySQL, PostgreSQL and SQLite, SELECT TOP n in MS SQL;
54
+ strings in single quotes. Example (MySQL): SELECT ts, val FROM \`iobroker\`.ts_number WHERE id = (SELECT id
55
+ FROM \`iobroker\`.datapoints WHERE name = 'hm-rpc.0.ABC.1.TEMPERATURE') ORDER BY ts DESC LIMIT 10
56
+
57
+ Commands (sendTo sql.0): getHistory, aggregate and lastChange are standard commands of the shared catalog of
58
+ ioBroker (family history): the same names, parameters and answers in history, sql, influxdb and recorder.
59
+ - getHistory {id, options: {start?, end?, aggregate?, count?, step?, ...}}: the course of one state:
60
+ {result: [{ts, val, ack?, from?, q?, id?}], step, sessionId}, on an error {result: [], error}. options is
61
+ required (may be {}).
62
+ aggregate: average (default), min, max, minmax (min and max of each interval), total, count, percentile
63
+ {percentile 0-100, default 50}, quantile {quantile 0-1, default 0.5}, integral {integralUnit in s, default 60,
64
+ 3600 gives Wh from W; integralInterpolation none (default) | linear}: one value per interval;
65
+ none or onchange: the stored values. id "*" with none or onchange: the values of all datapoints, id = the
66
+ number in the table datapoints.
67
+ start: without it (or 0) only the newest count values are read. end: default now + 5000 s.
68
+ count: the number of intervals (default 500), with none/onchange the number of values (default limit).
69
+ step: the interval in ms instead of count. intervalBorders: [ms, ...] ascending borders of the intervals
70
+ (e.g. local days), replaces start, end and step. limit: at most this many intervals or values (default
71
+ count, else 2000). returnNewestEntries: true = the newest values instead of the oldest when count cuts.
72
+ ack, from, q, addId: true adds these fields (from = the name of the source). round: digits after the decimal
73
+ point (default the setting of the state). ignoreNull: false (default, null stays), true (replaced by the
74
+ value before), 0 (replaced by 0). removeBorderValues: true drops the values before start and after end that
75
+ are added for charts. sessionId: returned as it is.
76
+ - getCounter {id, options?: {start?, end?}}: how much a counter (a rising meter reading, e.g. kWh) rose between
77
+ start (default: the beginning) and end (default now), a reset or a replaced meter included (setting "counter"
78
+ of the state): {result: number}. Only for a logged state, else {error: "Not enabled"}.
79
+ - aggregate {id, start, end?, fn, value?}: one number for a period: {value, ts?, unit?, count}. fn: min, max (ts =
80
+ when), avg (the mean of the stored values), sum, count (with value: how often the state became it, e.g. true),
81
+ delta (how much a counter rose, resets included), first, last, integral (value × hours: W gives Wh), duration
82
+ (with value: how many seconds the state had it). end: default now. count: the stored values in the period, at
83
+ most 50000 (else reason TOO_MANY_VALUES). Errors: {error, reason} (reason BAD_REQUEST for a wrong parameter).
84
+ Computed from the values of getHistory (aggregate none).
85
+ - lastChange {id, value?, before?}: when the state last changed (to value): {ts, val}; before: only the values
86
+ before this time. A value logged again does not count as a change. Reason NOT_FOUND if it never had the value;
87
+ only the newest 10000 stored values are searched: limited true = it had it already then.
88
+ - getEnabledDPs {}: the states this instance logs: {[id]: their settings (enabled, changesOnly, debounceTime,
89
+ blockTime, changesMinDelta, changesRelogInterval, retention in s, maxLength, counter, storageType, aliasId,
90
+ ...)}.
91
+ - getDatapoints {}: every row of the table datapoints, also the ones no longer logged:
92
+ {success, result: [{id, index (datapoints.id), type: Number | String | Boolean | null}]}.
93
+ - getDpOverview {}: like getDatapoints with the time of the first value, slow (5 s pause per table):
94
+ {success, result: {[id]: {type: number | string | boolean | undefined, ts}}}.
95
+ - getRawEntries {id, start?, end?, limit? (1-5000, default 100), offset? (default 0), sort? desc (default) | asc,
96
+ noTotal?}: the rows exactly as stored (ack and booleans as the database returns them, from null if unknown):
97
+ {id, index, type, table, total, limit, offset, sort, result: [{ts, val, ack, q, from}]}; noTotal: true skips
98
+ the counting (total is missing then).
99
+ - getDpStatistics {}: per datapoint the rows and the estimated size: {success, result: [{id, index, type, table,
100
+ count, firstTs, lastTs, estimatedBytes, status}], summary: {datapoints, rows, estimatedBytes, byStatus}}.
101
+ status: active, loggingDisabled (not logged, the object or its settings exist), objectMissing.
102
+ - features {}: {supportedFeatures: ["update", "delete", "deleteRange", "deleteAll", "storeState"]}.
103
+ - query "SQL text" (the message is the string itself): runs it as it is: {error, result: rows}. It runs ANY
104
+ statement (also DELETE, UPDATE, DROP); use it only for SELECT. ts in the rows is a number.
105
+ - enableHistory {id, options?}: logs the state from now on; options = its settings as in getEnabledDPs (the
106
+ defaults of the instance otherwise): {success} or {error}.
107
+ - disableHistory {id}: stops logging the state, the stored values stay: {success} or {error}.
108
+ - storeState {id, state: {ts?, val, ack?, q?, from?} or a list of them, rules?} or [{id, state, rules?}]: writes
109
+ values into the database, also of a state that is not logged (ts default now); rules: true applies the logging
110
+ settings (only for a logged state): {success, successCount} or {error, errors, successCount}.
111
+ - update {id, state: {ts, val?, ack?, q?, from?}} or [{id, state}] or {id, state: [...]}: changes the stored row
112
+ with exactly this ts: {success} or {error, errors}.
113
+ - delete {id, ts} or [{id, ts}] or {id, ts: [ts, ...]} (also as {id, state: {ts}}): deletes the rows with
114
+ exactly these ts: {success} or {error, errors}.
115
+ - deleteRange {id, start, end?} or [{id, start, end?}]: deletes the rows with start <= ts <= end (end default
116
+ now): {success} or {error, errors}.
117
+ - deleteAll {id} or [{id}]: deletes every stored row of these states: {success} or {error, errors}.
118
+ - cleanupOrphaned {scope?: {objectMissing? (default true), loggingDisabled? (default false)}, confirm?}: the
119
+ rows of datapoints that are not logged any more. Without confirm: true only the preview {dryRun: true,
120
+ datapoints, rows, estimatedBytes, items}; with confirm: true it deletes them and adds {deleted}.
121
+ - destroy {}: drops all tables (and the database, if the adapter created it), then restarts the instance:
122
+ {result: "deleted"} or {error}. Every stored value is lost.
123
+ - test {config}, stopInstance: for the settings and js-controller, not for agents.
124
+
125
+ How to talk to the user:
126
+ - Find the state first (search the objects); name states by their name, give times in local time and values
127
+ with their unit.
128
+ - A state has a history only if it is or was logged (getEnabledDPs, getDatapoints). For a longer period request
129
+ one value per interval (e.g. aggregate average with count 24 to 200) instead of every stored value. For one
130
+ number of a period (the highest value, how often, how long, how much) use the command aggregate, for "when was
131
+ it last ..." lastChange. Prefer these and getHistory; write a SELECT only for what they cannot answer, and read
132
+ dbtype and dbname from the instance first.
133
+ - Send only SELECT statements with query. Any other statement only on the user's explicit request.
134
+ - query (other than SELECT), delete, deleteRange, deleteAll, update, storeState, cleanupOrphaned, destroy,
135
+ enableHistory, disableHistory and stopInstance change the database, the settings or the instance: never
136
+ without the user's explicit request. Deleted values cannot be restored: name the state and the range and ask
137
+ for confirmation first; show the preview of cleanupOrphaned (without confirm) before deleting; for destroy
138
+ say that the whole history is lost.`;
139
+ //# sourceMappingURL=help.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"help.js","sourceRoot":"","sources":["../../src/lib/help.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH;;;;GAIG;AACU,QAAA,QAAQ,GAA6D;IAC9E,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE;IACjC,EAAE,OAAO,EAAE,YAAY,EAAE,K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iB,EAAE,KAAK,EAAE,IAAI,EAAE;IAC3C,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,IAAI,EAAE;IACnC,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,IAAI,EAAE;CAC3C,CAAC;AAEW,QAAA,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sCAoGkB,CAAC"}
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ /**
3
+ * The commands `aggregate` and `lastChange` of the shared catalog of sendTo commands (family "history", see HELP.md
4
+ * of ioBroker.assistant): one number for a period, and the time of the last change of a state. Both are computed
5
+ * from the stored values as the adapter reads them anyway (for `getHistory` or `getRawEntries`), so they need no
6
+ * database query of their own.
7
+ *
8
+ * The same file is used by ioBroker.history, ioBroker.sql, ioBroker.influxdb and ioBroker.recorder: keep it identical.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.MAX_SCAN = exports.MAX_VALUES = exports.AGGREGATE_FUNCTIONS = void 0;
12
+ exports.aggregate = aggregate;
13
+ exports.lastChange = lastChange;
14
+ exports.readThroughGetHistory = readThroughGetHistory;
15
+ /** The values of `fn` of `aggregate` */
16
+ exports.AGGREGATE_FUNCTIONS = [
17
+ 'min',
18
+ 'max',
19
+ 'avg',
20
+ 'sum',
21
+ 'count',
22
+ 'delta',
23
+ 'first',
24
+ 'last',
25
+ 'integral',
26
+ 'duration',
27
+ ];
28
+ /** `aggregate` reads at most so many values: a longer period gives the error TOO_MANY_VALUES */
29
+ exports.MAX_VALUES = 50_000;
30
+ /** `lastChange` reads the values backwards in pages of this size ... */
31
+ const PAGE = 1_000;
32
+ /** ... and stops after so many values */
33
+ exports.MAX_SCAN = 10_000;
34
+ const HOUR = 3_600_000;
35
+ function fail(error, reason) {
36
+ return { error, reason };
37
+ }
38
+ /** ms since 1970 from a number, a numeric text or a date text (a text without a zone is local time) */
39
+ function toTimestamp(value) {
40
+ if (typeof value === 'number') {
41
+ return Number.isFinite(value) ? value : undefined;
42
+ }
43
+ if (typeof value !== 'string' || !value.trim()) {
44
+ return undefined;
45
+ }
46
+ const text = value.trim();
47
+ if (/^\d+$/.test(text)) {
48
+ return parseInt(text, 10);
49
+ }
50
+ // Date reads a date without a time as UTC, the catalog means the local midnight
51
+ const ts = new Date(/^\d{4}-\d{2}-\d{2}$/.test(text) ? `${text}T00:00` : text).getTime();
52
+ return Number.isFinite(ts) ? ts : undefined;
53
+ }
54
+ function isGiven(value) {
55
+ return value !== undefined && value !== null && value !== '';
56
+ }
57
+ /** A value as number (true = 1, false = 0, a numeric text), null if it is none */
58
+ function toNumber(val) {
59
+ if (typeof val === 'boolean') {
60
+ return val ? 1 : 0;
61
+ }
62
+ const n = typeof val === 'number' ? val : typeof val === 'string' && val.trim() ? Number(val) : NaN;
63
+ return Number.isFinite(n) ? n : null;
64
+ }
65
+ /** A value to compare: true, 1 and "true" are the same, as are 5 and "5"; texts without case */
66
+ function comparable(val) {
67
+ if (typeof val === 'boolean') {
68
+ return val ? 1 : 0;
69
+ }
70
+ if (typeof val === 'string') {
71
+ const text = val.trim().toLowerCase();
72
+ if (text === 'true' || text === 'false') {
73
+ return text === 'true' ? 1 : 0;
74
+ }
75
+ return text && Number.isFinite(Number(text)) ? Number(text) : text;
76
+ }
77
+ return val;
78
+ }
79
+ function same(a, b) {
80
+ return comparable(a) === comparable(b);
81
+ }
82
+ function round(value) {
83
+ return Math.round(value * 1000) / 1000;
84
+ }
85
+ /** The values in [start, end] without the gaps (null), sorted by ts */
86
+ function inRange(values, start, end) {
87
+ return values
88
+ .filter(v => v && v.ts >= start && v.ts <= end && v.val !== null && v.val !== undefined)
89
+ .sort((a, b) => a.ts - b.ts);
90
+ }
91
+ function errorText(e) {
92
+ return e instanceof Error ? e.message : String(e);
93
+ }
94
+ /** The value of one function; `before` = the last value before start, `end` = the end, but not after now */
95
+ function compute(fn, values, before, wanted, start, end) {
96
+ const numbers = values
97
+ .map(v => ({ ts: v.ts, n: toNumber(v.val) }))
98
+ .filter((v) => v.n !== null);
99
+ const sum = numbers.reduce((total, v) => total + v.n, 0);
100
+ switch (fn) {
101
+ case 'first':
102
+ case 'last': {
103
+ const v = fn === 'first' ? values[0] : values[values.length - 1];
104
+ return v ? { value: v.val, ts: v.ts } : { value: null };
105
+ }
106
+ case 'min':
107
+ case 'max': {
108
+ let best;
109
+ for (const v of numbers) {
110
+ if (!best || (fn === 'min' ? v.n < best.n : v.n > best.n)) {
111
+ best = v;
112
+ }
113
+ }
114
+ return best ? { value: best.n, ts: best.ts } : { value: null };
115
+ }
116
+ case 'avg':
117
+ return { value: numbers.length ? round(sum / numbers.length) : null };
118
+ case 'sum':
119
+ return { value: round(sum) };
120
+ case 'count': {
121
+ if (!isGiven(wanted)) {
122
+ return { value: values.length };
123
+ }
124
+ // how often the state became the value: the values before it do not count again
125
+ let count = 0;
126
+ let previous = before?.val;
127
+ for (const v of values) {
128
+ if (same(v.val, wanted) && (previous === undefined || !same(previous, wanted))) {
129
+ count++;
130
+ }
131
+ previous = v.val;
132
+ }
133
+ return { value: count };
134
+ }
135
+ case 'delta': {
136
+ // how much a counter rose: a value below the one before is a reset, it rose from 0 to this value
137
+ const series = (before ? [before, ...values] : values)
138
+ .map(v => toNumber(v.val))
139
+ .filter((n) => n !== null);
140
+ let rise = 0;
141
+ for (let i = 1; i < series.length; i++) {
142
+ rise += series[i] >= series[i - 1] ? series[i] - series[i - 1] : series[i];
143
+ }
144
+ return { value: series.length ? round(rise) : null };
145
+ }
146
+ default: {
147
+ // integral and duration: every value holds until the next one, the last one until the end
148
+ const line = before ? [{ ts: start, val: before.val }, ...values] : values;
149
+ let total = 0;
150
+ for (let i = 0; i < line.length; i++) {
151
+ const from = Math.max(line[i].ts, start);
152
+ const to = Math.min(i + 1 < line.length ? line[i + 1].ts : end, end);
153
+ if (to > from) {
154
+ if (fn === 'duration') {
155
+ total += same(line[i].val, wanted) ? to - from : 0;
156
+ }
157
+ else {
158
+ total += (toNumber(line[i].val) ?? 0) * (to - from);
159
+ }
160
+ }
161
+ }
162
+ if (!line.length) {
163
+ return { value: null };
164
+ }
165
+ return { value: fn === 'duration' ? Math.round(total / 1000) : round(total / HOUR) };
166
+ }
167
+ }
168
+ }
169
+ /**
170
+ * `aggregate {id, start, end?, fn, value?}`: one number for a period, `{value, ts?, unit?, count}`.
171
+ * fn: min, max (ts = when), avg, sum, count (with value: how often the state became it), delta (how much a counter
172
+ * rose, resets included), first, last (ts = when), integral (value × hours, e.g. W → Wh), duration (with value:
173
+ * seconds the state had it). count = the number of stored values in the period.
174
+ *
175
+ * @param message the message of sendTo
176
+ * @param source the stored values
177
+ * @param now the current time
178
+ */
179
+ async function aggregate(message, source, now = Date.now()) {
180
+ const m = (message && typeof message === 'object' ? message : {});
181
+ const id = m.id;
182
+ const fn = m.fn;
183
+ if (typeof id !== 'string' || !id) {
184
+ return fail('id is missing', 'BAD_REQUEST');
185
+ }
186
+ if (typeof fn !== 'string' || !exports.AGGREGATE_FUNCTIONS.includes(fn)) {
187
+ return fail(`fn must be one of ${exports.AGGREGATE_FUNCTIONS.join(', ')}`, 'BAD_REQUEST');
188
+ }
189
+ const start = toTimestamp(m.start);
190
+ const end = isGiven(m.end) ? toTimestamp(m.end) : now;
191
+ if (start === undefined || end === undefined || start > end) {
192
+ return fail('start and end must be times (ms or a date text) and start not after end', 'BAD_REQUEST');
193
+ }
194
+ if (fn === 'duration' && !isGiven(m.value)) {
195
+ return fail('fn duration needs the value', 'BAD_REQUEST');
196
+ }
197
+ try {
198
+ const read = await source.read(id, { start, end, count: exports.MAX_VALUES + 1 });
199
+ if (read.length > exports.MAX_VALUES) {
200
+ return fail(`More than ${exports.MAX_VALUES} stored values in this period: ask for a shorter one`, 'TOO_MANY_VALUES');
201
+ }
202
+ const values = inRange(read, start, end);
203
+ // what the state was at start, for the changes, the counter and the time line
204
+ let before;
205
+ if ((fn === 'count' && isGiven(m.value)) || fn === 'delta' || fn === 'integral' || fn === 'duration') {
206
+ before = inRange(await source.read(id, { end: start - 1, count: 10 }), -Infinity, start - 1).pop();
207
+ }
208
+ const result = compute(fn, values, before, m.value, start, Math.min(end, now));
209
+ const answer = { value: result.value, count: values.length };
210
+ if (result.ts !== undefined) {
211
+ answer.ts = result.ts;
212
+ }
213
+ const unit = fn === 'duration' ? 's' : fn === 'count' ? undefined : await source.unit?.(id);
214
+ if (unit) {
215
+ answer.unit = fn === 'integral' ? `${unit}h` : unit;
216
+ }
217
+ return answer;
218
+ }
219
+ catch (e) {
220
+ return { error: errorText(e) };
221
+ }
222
+ }
223
+ /**
224
+ * `lastChange {id, value?, before?}`: when the state last changed (to value), `{ts, val}`: the first of the newest
225
+ * stored values that are the same as the newest one (or as value). before: only the values before this time.
226
+ * At most MAX_SCAN values are read: if the state had the value longer, ts is the oldest one read and limited true.
227
+ *
228
+ * @param message the message of sendTo
229
+ * @param source the stored values
230
+ * @param now the current time
231
+ */
232
+ async function lastChange(message, source, now = Date.now()) {
233
+ const m = (message && typeof message === 'object' ? message : {});
234
+ const id = m.id;
235
+ if (typeof id !== 'string' || !id) {
236
+ return fail('id is missing', 'BAD_REQUEST');
237
+ }
238
+ let end = isGiven(m.before) ? toTimestamp(m.before) : now;
239
+ if (end === undefined) {
240
+ return fail('before must be a time (ms or a date text)', 'BAD_REQUEST');
241
+ }
242
+ let wanted = m.value;
243
+ // the oldest value read of the newest run of values that are the same as the wanted one
244
+ let run;
245
+ try {
246
+ for (let scanned = 0; scanned < exports.MAX_SCAN;) {
247
+ const page = await source.read(id, { end, count: PAGE });
248
+ const values = inRange(page, -Infinity, end);
249
+ for (let i = values.length - 1; i >= 0; i--) {
250
+ if (!isGiven(wanted)) {
251
+ wanted = values[i].val;
252
+ }
253
+ if (same(values[i].val, wanted)) {
254
+ run = values[i];
255
+ }
256
+ else if (run) {
257
+ return { ts: run.ts, val: run.val };
258
+ }
259
+ }
260
+ if (page.length < PAGE) {
261
+ // no older values: the state has had it since the first stored value
262
+ return run ? { ts: run.ts, val: run.val } : fail(`${id} has no such stored value`, 'NOT_FOUND');
263
+ }
264
+ scanned += page.length;
265
+ end = Math.min(...page.map(v => v.ts)) - 1;
266
+ }
267
+ }
268
+ catch (e) {
269
+ return { error: errorText(e) };
270
+ }
271
+ return run
272
+ ? { ts: run.ts, val: run.val, limited: true }
273
+ : fail(`${id} has no such value in its newest ${exports.MAX_SCAN} stored values`, 'NOT_FOUND');
274
+ }
275
+ /**
276
+ * The `read` of a `ValueSource` through the adapter's own `getHistory` (aggregate none, without border values).
277
+ *
278
+ * @param ask sends `getHistory` with this message to the own instance and resolves with the answer
279
+ */
280
+ function readThroughGetHistory(ask) {
281
+ return async (id, query) => {
282
+ const answer = (await ask({
283
+ id,
284
+ options: {
285
+ start: query.start,
286
+ end: query.end,
287
+ count: query.count,
288
+ limit: query.count,
289
+ aggregate: 'none',
290
+ returnNewestEntries: query.start === undefined,
291
+ removeBorderValues: true,
292
+ },
293
+ }));
294
+ if (answer instanceof Error) {
295
+ throw answer;
296
+ }
297
+ if (answer?.error) {
298
+ throw new Error(typeof answer.error === 'string' ? answer.error : JSON.stringify(answer.error));
299
+ }
300
+ return Array.isArray(answer?.result) ? answer.result : [];
301
+ };
302
+ }
303
+ //# sourceMappingURL=standardHistory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"standardHistory.js","sourceRoot":"","sources":["../../src/lib/standardHistory.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AA4MH,8BAkDC;AAWD,gCA4CC;AAOD,sDAwBC;AA9TD,wCAAwC;AAC3B,QAAA,mBAAmB,GAAG;IAC/B,KAAK;IACL,KAAK;IACL,KAAK;IACL,KAAK;IACL,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM;IACN,UAAU;IACV,UAAU;CACb,CAAC;AAEF,gGAAgG;AACnF,QAAA,UAAU,GAAG,MAAM,CAAC;AACjC,wEAA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BACjB,mBAAmB,EAAE,KAAK,CAAC,KAAK,KAAK,SAAS;gBAC9C,kBAAkB,EAAE,IAAI;aAC3B;SACJ,CAAC,CAA2E,CAAC;QAC9E,IAAI,MAAM,YAAY,KAAK,EAAE,CAAC;YAC1B,MAAM,MAAM,CAAC;QACjB,CAAC;QACD,IAAI,MAAM,EAAE,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CAAC,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QACpG,CAAC;QACD,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;IAC9D,CAAC,CAAC;AACN,CAAC"}
package/build/main.js CHANGED
@@ -54,6 +54,8 @@ const statistics_1 = require("./lib/statistics");
54
54
  const postgresql_client_1 = require("./lib/postgresql-client");
55
55
  const sqlite3_client_1 = require("./lib/sqlite3-client");
56
56
  const errors_1 = require("./lib/errors");
57
+ const help_1 = require("./lib/help");
58
+ const standardHistory_1 = require("./lib/standardHistory");
57
59
  const write_buffer_1 = require("./lib/write-buffer");
58
60
  const SQLFuncs = {
59
61
  mssql: {
@@ -207,6 +209,8 @@ const KEPT_LOG_INTERVAL = 60_000;
207
209
  const MAX_RAW_ENTRIES = 5000;
208
210
  /** How often an unchanged connection error is repeated as error in the log */
209
211
  const REPEATED_ERROR_INTERVAL = 3_600_000;
212
+ /** How long `aggregate` and `lastChange` wait for the answer of the own `getHistory` */
213
+ const STANDARD_TIMEOUT = 120_000;
210
214
  function sortByTs(a, b) {
211
215
  const aTs = a.ts;
212
216
  const bTs = b.ts;
@@ -1378,7 +1382,13 @@ class SqlAdapter extends adapter_core_1.Adapter {
1378
1382
  this.sendTo(msg.from, msg.command, notInitialized, msg.callback);
1379
1383
  return;
1380
1384
  }
1381
- if (msg.command === 'features') {
1385
+ if (msg.command === 'help') {
1386
+ // what the instance answers, for AI agents and script authors; needs no database
1387
+ if (msg.callback) {
1388
+ this.sendTo(msg.from, msg.command, { help: help_1.HELP, commands: help_1.COMMANDS }, msg.callback);
1389
+ }
1390
+ }
1391
+ else if (msg.command === 'features') {
1382
1392
  this.sendTo(msg.from, msg.command, { supportedFeatures: ['update', 'delete', 'deleteRange', 'deleteAll', 'storeState'] }, msg.callback);
1383
1393
  }
1384
1394
  else if (msg.command === 'getHistory') {
@@ -1387,6 +1397,12 @@ class SqlAdapter extends adapter_core_1.Adapter {
1387
1397
  else if (msg.command === 'getCounter') {
1388
1398
  this.getCounterDiff(msg);
1389
1399
  }
1400
+ else if (msg.command === 'aggregate') {
1401
+ void this.answerStandard(msg, standardHistory_1.aggregate);
1402
+ }
1403
+ else if (msg.command === 'lastChange') {
1404
+ void this.answerStandard(msg, standardHistory_1.lastChange);
1405
+ }
1390
1406
  else if (msg.command === 'test') {
1391
1407
  void this.testConnection(msg);
1392
1408
  }
@@ -2932,6 +2948,19 @@ class SqlAdapter extends adapter_core_1.Adapter {
2932
2948
  this.#getDataFromDB(query, options, callback);
2933
2949
  }
2934
2950
  }
2951
+ /**
2952
+ * Answer `aggregate` or `lastChange` of the shared catalog of sendTo commands (family history): computed from the
2953
+ * stored values, read with the own `getHistory` (as a message to this instance, so getHistory stays as it is)
2954
+ */
2955
+ async answerStandard(msg, command) {
2956
+ const answer = await command(msg.message, {
2957
+ read: (0, standardHistory_1.readThroughGetHistory)(message => this.sendToAsync(this.namespace, 'getHistory', message, { timeout: STANDARD_TIMEOUT })),
2958
+ unit: async (id) => (await this.getForeignObjectAsync(id))?.common?.unit,
2959
+ });
2960
+ if (msg.callback) {
2961
+ this.sendTo(msg.from, msg.command, answer, msg.callback);
2962
+ }
2963
+ }
2935
2964
  getCounterDiff(msg) {
2936
2965
  const id = msg.message?.id;
2937
2966
  const opts = msg.message?.options || {};
@@ -3063,11 +3092,11 @@ class SqlAdapter extends adapter_core_1.Adapter {
3063
3092
  else {
3064
3093
  options.round = configuredRound;
3065
3094
  }
3066
- if ((options.aggregate === 'percentile' && options.percentile < 0) || options.percentile > 100) {
3095
+ if (options.aggregate === 'percentile' && (options.percentile < 0 || options.percentile > 100)) {
3067
3096
  this.log.error(`Invalid percentile value: ${options.percentile}, use 50 as default`);
3068
3097
  options.percentile = 50;
3069
3098
  }
3070
- if ((options.aggregate === 'quantile' && options.quantile < 0) || options.quantile > 1) {
3099
+ if (options.aggregate === 'quantile' && (options.quantile < 0 || options.quantile > 1)) {
3071
3100
  this.log.error(`Invalid quantile value: ${options.quantile}, use 0.5 as default`);
3072
3101
  options.quantile = 0.5;
3073
3102
  }