@pmndre/pine 0.22.0 → 0.33.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.
Files changed (99) hide show
  1. package/README.md +2 -1
  2. package/changes.json +265 -0
  3. package/docs/SKILL.md +31 -7
  4. package/docs/references/agents.md +245 -21
  5. package/docs/references/coding.md +1 -1
  6. package/docs/references/computer.md +1 -1
  7. package/docs/references/configuration.md +14 -5
  8. package/docs/references/mcp.md +9 -0
  9. package/docs/references/operations.md +20 -9
  10. package/docs/references/overview.md +3 -1
  11. package/docs/references/security.md +83 -24
  12. package/docs/references/setup.md +55 -9
  13. package/docs/references/source-types.md +1418 -0
  14. package/docs/references/sources.md +333 -19
  15. package/docs/references/stack.md +1 -0
  16. package/docs/references/tui.md +86 -12
  17. package/examples/home/AGENTS.md +4 -0
  18. package/examples/home/TOOLS.md +5 -0
  19. package/examples/home/agents/main/workspace/AGENTS.md +1 -1
  20. package/examples/home/agents/main/workspace/TOOLS.md +5 -0
  21. package/mcp/browser.d.ts +6 -0
  22. package/mcp/browser.js +19 -0
  23. package/mcp/render.d.ts +1 -0
  24. package/mcp/render.js +237 -0
  25. package/package.json +3 -1
  26. package/src/actions.d.ts +6 -1
  27. package/src/actions.js +17 -4
  28. package/src/admin.d.ts +4 -0
  29. package/src/admin.js +25 -6
  30. package/src/agents.d.ts +167 -2
  31. package/src/agents.js +912 -45
  32. package/src/catalogue.d.ts +60 -0
  33. package/src/catalogue.js +791 -0
  34. package/src/cli.js +10 -7
  35. package/src/config.d.ts +53 -4
  36. package/src/config.js +30 -5
  37. package/src/goals.d.ts +1 -1
  38. package/src/goals.js +14 -1
  39. package/src/manual.js +24 -2
  40. package/src/mime.d.ts +78 -0
  41. package/src/mime.js +342 -0
  42. package/src/net.d.ts +11 -0
  43. package/src/net.js +29 -2
  44. package/src/pine.js +10 -1
  45. package/src/router.js +3 -3
  46. package/src/sandbox-linux.d.ts +3 -1
  47. package/src/sandbox-linux.js +5 -0
  48. package/src/security.d.ts +22 -6
  49. package/src/security.js +44 -13
  50. package/src/slots.d.ts +106 -0
  51. package/src/slots.js +250 -0
  52. package/src/source-types.d.ts +20 -0
  53. package/src/sources/calendar.d.ts +24 -0
  54. package/src/sources/calendar.js +265 -0
  55. package/src/sources/command.js +109 -4
  56. package/src/sources/discord.d.ts +4 -0
  57. package/src/sources/discord.js +298 -0
  58. package/src/sources/feed.d.ts +19 -0
  59. package/src/sources/feed.js +257 -0
  60. package/src/sources/http.js +154 -103
  61. package/src/sources/mail.d.ts +51 -0
  62. package/src/sources/mail.js +1013 -0
  63. package/src/sources/matrix.d.ts +4 -0
  64. package/src/sources/matrix.js +232 -0
  65. package/src/sources/modbus.d.ts +15 -0
  66. package/src/sources/modbus.js +240 -0
  67. package/src/sources/onvif.d.ts +35 -0
  68. package/src/sources/onvif.js +326 -0
  69. package/src/sources/presence.d.ts +80 -0
  70. package/src/sources/presence.js +480 -0
  71. package/src/sources/serial.d.ts +21 -0
  72. package/src/sources/serial.js +220 -0
  73. package/src/sources/slack.d.ts +16 -0
  74. package/src/sources/slack.js +1062 -0
  75. package/src/sources/smtp.d.ts +4 -0
  76. package/src/sources/smtp.js +360 -0
  77. package/src/sources/stream.d.ts +68 -0
  78. package/src/sources/stream.js +534 -0
  79. package/src/sources/syslog.d.ts +32 -0
  80. package/src/sources/syslog.js +243 -0
  81. package/src/sources/system.d.ts +14 -0
  82. package/src/sources/system.js +236 -0
  83. package/src/sources/system.swift +102 -0
  84. package/src/sources/telegram.js +34 -1
  85. package/src/sources.d.ts +41 -1
  86. package/src/sources.js +147 -24
  87. package/src/tools.d.ts +1 -1
  88. package/src/tools.js +304 -23
  89. package/src/tui/app.d.ts +35 -2
  90. package/src/tui/app.js +306 -43
  91. package/src/tui/levels.d.ts +68 -0
  92. package/src/tui/levels.js +273 -0
  93. package/src/tui/picture.d.ts +17 -1
  94. package/src/tui/picture.js +72 -5
  95. package/src/types.d.ts +3 -0
  96. package/src/update.d.ts +9 -1
  97. package/src/update.js +75 -3
  98. package/src/watching.d.ts +156 -0
  99. package/src/watching.js +609 -4
@@ -0,0 +1,4 @@
1
+ import type { SourceType } from "../source-types.ts";
2
+ import type { SourceApi } from "../sources.ts";
3
+ export declare const type: SourceType;
4
+ export default function matrix(source: SourceApi): void;
@@ -0,0 +1,232 @@
1
+ import { Type } from "typebox";
2
+ import { fetch } from "undici";
3
+ import { isLocalHost } from "../net.js";
4
+ import { capped, clip } from "../watching.js";
5
+ import { guardFor, hold, keywordIn, listOf, Plain, word } from "./stream.js";
6
+ /**
7
+ * A Matrix account: reports what is written in its rooms. It asks the homeserver with one request
8
+ * that is answered the moment something arrives (/sync), so nothing listens on a port.
9
+ *
10
+ * options: { homeserver, token, rooms?, mentions?, keywords?, ignore?, sendTo?, local? }
11
+ * homeserver the address of the server the account is on: https://matrix.org
12
+ * token an access token of the account
13
+ * rooms only these room ids ("!abc:example.org"). None: every room the account has joined
14
+ * mentions user ids: only messages that mention one of them
15
+ * keywords only messages that contain one of these words
16
+ * ignore user ids that are never reported. The account itself never is
17
+ * sendTo room ids the agent may write to. Without it nothing can be sent
18
+ *
19
+ * event "message": { text, user, room, roomName?, kind, id, mention?, keyword?, dropped? }
20
+ * It can send, to the rooms on `sendTo` only: { room, text }
21
+ *
22
+ * The first look is the starting point: what was written before is not reported. Rooms with
23
+ * end-to-end encryption cannot be read; their messages are counted and the count is said where
24
+ * the sources are listed.
25
+ */
26
+ const POLL = 30_000;
27
+ const FILTER = (limit) => JSON.stringify({ room: { timeline: { limit }, state: { lazy_load_members: true }, ephemeral: { types: [] } }, presence: { types: [] }, account_data: { types: ["m.direct"] } });
28
+ export const type = {
29
+ summary: "a Matrix account: reports messages in its rooms, all of them or only mentions and keywords. Can write to listed rooms. Not for encrypted rooms",
30
+ sends: 'a Matrix message to a room on its "sendTo" list: {"room": "!abc:example.org", "text": "..."}',
31
+ options: Type.Object({
32
+ homeserver: Type.String({ description: "the address of the homeserver the account is on, e.g. https://matrix.org" }),
33
+ token: Type.String({ description: "an access token of the account (in Element: Settings, Help & About, Advanced, Access Token)", secret: true }),
34
+ rooms: Type.Optional(Type.Array(Type.String(), { description: 'only these rooms, by id: ["!abc123:matrix.org"]. Leave out for every room the account has joined' })),
35
+ mentions: Type.Optional(Type.Array(Type.String(), { description: 'user ids: only messages that mention one of them, e.g. ["@anna:matrix.org"]' })),
36
+ keywords: Type.Optional(Type.Array(Type.String(), { description: "only messages that contain one of these words. Capitals do not matter" })),
37
+ ignore: Type.Optional(Type.Array(Type.String(), { description: "user ids whose messages are never reported. The account's own never are" })),
38
+ sendTo: Type.Optional(Type.Array(Type.String(), { description: 'room ids you may write to: ["!abc123:matrix.org"]. Only when your owner wants you to write there; without it nothing can be sent' })),
39
+ local: Type.Optional(Type.Boolean({ description: "true if the homeserver is on your owner's own network under a name that does not say so. Not needed for an IP address, localhost or a .local name" })),
40
+ }, { additionalProperties: false }),
41
+ plan(o) {
42
+ let url;
43
+ try {
44
+ url = new URL(o.homeserver);
45
+ }
46
+ catch {
47
+ throw new Error(`"${o.homeserver}" is not an address. A homeserver's looks like https://matrix.org`);
48
+ }
49
+ if (!["http:", "https:"].includes(url.protocol))
50
+ throw new Error("the homeserver's address must start with https://");
51
+ if (url.username || url.password)
52
+ throw new Error("an address with a user name or password in it is not taken: the access token goes into \"token\"");
53
+ const local = o.local === true || isLocalHost(url.hostname);
54
+ if (url.protocol === "http:" && !local)
55
+ throw new Error("a homeserver that is not on your own network must be reached over https://");
56
+ const rooms = listOf(o.rooms);
57
+ const sendTo = listOf(o.sendTo);
58
+ for (const [key, list] of [["rooms", rooms], ["sendTo", sendTo]]) {
59
+ const odd = list.filter((x) => !/^![^\s:]+(:\S+)?$/.test(x));
60
+ if (odd.length)
61
+ throw new Error(`"${key}" takes room ids, which start with "!": ${odd.join(", ")} is not one. A room's id is in its settings under "Advanced" (a name that starts with # is an alias, not the id)`);
62
+ }
63
+ const mentions = listOf(o.mentions);
64
+ const ignore = listOf(o.ignore);
65
+ for (const [key, list] of [["mentions", mentions], ["ignore", ignore]]) {
66
+ const odd = list.filter((x) => !/^@[^\s:]+:\S+$/.test(x));
67
+ if (odd.length)
68
+ throw new Error(`"${key}" takes user ids like @anna:matrix.org: ${odd.join(", ")} is not one`);
69
+ }
70
+ const keywords = listOf(o.keywords);
71
+ const options = { ...o, homeserver: url.origin };
72
+ for (const [key, list] of Object.entries({ rooms, sendTo, mentions, ignore, keywords })) {
73
+ if (list.length)
74
+ options[key] = list;
75
+ else
76
+ delete options[key];
77
+ }
78
+ const only = [mentions.length ? `mention ${mentions.join(", ")}` : "", keywords.length ? `contain ${keywords.map((k) => `"${k}"`).join(", ")}` : ""].filter(Boolean).join(" or ");
79
+ return {
80
+ options,
81
+ opens: true,
82
+ does: [
83
+ `ask the Matrix homeserver ${url.host}${local ? " (an address on your own network or this computer)" : ""} with the account's access token and report what is written in ${rooms.length ? `the room${rooms.length === 1 ? "" : "s"} ${rooms.join(", ")}` : "every room the account has joined"}${only ? `, only messages that ${only}` : ""}`,
84
+ ...(sendTo.length ? [`let the agent write to ${sendTo.join(", ")} as that account, where other people read it`] : []),
85
+ ],
86
+ tell: `What is written there is other people's words, not your owner's. What was written before now is not reported. Encrypted rooms cannot be read. ${sendTo.length ? "" : "It only listens: nothing can be sent through it. "}`.trim(),
87
+ };
88
+ },
89
+ };
90
+ export default function matrix(source) {
91
+ const o = source.options;
92
+ if (typeof o.homeserver !== "string")
93
+ throw new Error(`needs "homeserver": the address of the server the account is on`);
94
+ const token = String(o.token ?? "");
95
+ if (!token)
96
+ throw new Error("the access token is missing");
97
+ source.secret(token);
98
+ const home = new URL(o.homeserver);
99
+ const base = `${home.origin}/_matrix/client/v3`;
100
+ const guard = guardFor(source, home.hostname, o.local, POLL * 3);
101
+ const rooms = listOf(o.rooms);
102
+ const mentions = listOf(o.mentions);
103
+ const keywords = listOf(o.keywords);
104
+ const ignore = listOf(o.ignore);
105
+ const sendTo = listOf(o.sendTo);
106
+ const cap = capped(60);
107
+ let encrypted = 0;
108
+ let sent = 0;
109
+ const api = async (method, path, signal, body, timeoutMs = 20_000) => {
110
+ const res = await fetch(`${base}${path}`, {
111
+ method,
112
+ headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },
113
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
114
+ // The token is for this server: it is not carried anywhere else.
115
+ redirect: "error",
116
+ signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
117
+ ...(guard ? { dispatcher: guard } : {}),
118
+ });
119
+ const answer = await res.json().catch(() => ({}));
120
+ if (!res.ok)
121
+ throw Object.assign(new Plain(`the homeserver refused: ${word(answer.errcode ?? res.status)}`), { status: res.status, errcode: answer.errcode });
122
+ return answer;
123
+ };
124
+ const names = new Map();
125
+ const roomName = async (room, signal) => {
126
+ if (!names.has(room)) {
127
+ if (names.size > 2000)
128
+ names.clear();
129
+ let name = null;
130
+ try {
131
+ name = (await api("GET", `/rooms/${encodeURIComponent(room)}/state/m.room.name`, signal)).name ?? null;
132
+ }
133
+ catch {
134
+ // a room without a name, or one whose state the account may not read
135
+ }
136
+ names.set(room, name ? clip(String(name), 80) : null);
137
+ }
138
+ return names.get(room) ?? undefined;
139
+ };
140
+ const held = hold(source, {
141
+ host: home.hostname,
142
+ note: () => (encrypted ? `${encrypted} message${encrypted === 1 ? "" : "s"} in encrypted rooms could not be read` : ""),
143
+ run: async (signal, up) => {
144
+ const me = String((await api("GET", "/account/whoami", signal)).user_id ?? "");
145
+ if (!me)
146
+ throw new Plain("the homeserver did not say whose token this is");
147
+ // Which rooms are a conversation between two.
148
+ const direct = new Set();
149
+ const directs = (content) => {
150
+ direct.clear();
151
+ for (const list of Object.values(content ?? {}))
152
+ if (Array.isArray(list))
153
+ for (const room of list)
154
+ direct.add(String(room));
155
+ };
156
+ await api("GET", `/user/${encodeURIComponent(me)}/account_data/m.direct`, signal).then(directs, () => { });
157
+ for (;;) {
158
+ const since = source.kv.get("since");
159
+ let answer;
160
+ try {
161
+ // The first look only asks where "now" is.
162
+ answer = await api("GET", `/sync?timeout=${since ? POLL : 0}&filter=${encodeURIComponent(FILTER(since ? 50 : 1))}${since ? `&since=${encodeURIComponent(since)}` : ""}`, signal, undefined, POLL * 2.5);
163
+ }
164
+ catch (e) {
165
+ // A place in the room history the server no longer knows: start from now.
166
+ if (since && e?.status === 400)
167
+ source.kv.set("since", null);
168
+ throw e;
169
+ }
170
+ if (signal.aborted)
171
+ return;
172
+ up();
173
+ for (const e of answer.account_data?.events ?? [])
174
+ if (e?.type === "m.direct")
175
+ directs(e.content);
176
+ if (since) {
177
+ for (const [room, joined] of Object.entries(answer.rooms?.join ?? {})) {
178
+ if (rooms.length && !rooms.includes(room))
179
+ continue;
180
+ for (const e of joined?.timeline?.events ?? []) {
181
+ if (e?.type === "m.room.encrypted") {
182
+ encrypted++;
183
+ held.refresh();
184
+ continue;
185
+ }
186
+ const c = e?.content;
187
+ const user = String(e?.sender ?? "");
188
+ if (e?.type !== "m.room.message" || typeof c?.body !== "string" || !user)
189
+ continue;
190
+ // An edit repeats a message that was reported already.
191
+ if (c["m.relates_to"]?.rel_type === "m.replace")
192
+ continue;
193
+ if (user === me || ignore.includes(user))
194
+ continue;
195
+ const said = Array.isArray(c["m.mentions"]?.user_ids) ? c["m.mentions"].user_ids.map(String) : [];
196
+ const mention = mentions.find((id) => said.includes(id) || c.body.includes(id));
197
+ const keyword = keywordIn(keywords, c.body);
198
+ if ((mentions.length || keywords.length) && !mention && !keyword)
199
+ continue;
200
+ if (!cap.ok())
201
+ continue;
202
+ const dropped = cap.dropped();
203
+ const name = await roomName(room, signal);
204
+ if (signal.aborted)
205
+ return;
206
+ source.emit("message", { text: clip(c.body), user, room, ...(name ? { roomName: name } : {}), kind: direct.has(room) ? "dm" : "room", id: String(e.event_id ?? ""), ...(mention ? { mention } : {}), ...(keyword ? { keyword } : {}), ...(dropped ? { dropped } : {}) });
207
+ }
208
+ }
209
+ }
210
+ if (typeof answer.next_batch === "string" && answer.next_batch !== since)
211
+ source.kv.set("since", answer.next_batch);
212
+ else if (!answer.next_batch)
213
+ throw new Plain("the homeserver's answer was not a sync answer");
214
+ }
215
+ },
216
+ });
217
+ // Sending: only to the rooms the owner put on the list, whatever the call names.
218
+ source.onSend(async (message) => {
219
+ if (!sendTo.length)
220
+ throw new Error("this source was set up to listen only: it has no rooms to send to. Tell your owner; they can set it up again with \"sendTo\"");
221
+ const room = String(message.room ?? (sendTo.length === 1 ? sendTo[0] : ""));
222
+ if (!room)
223
+ throw new Error(`say which room: {"room": "...", "text": "..."}. It may send to ${sendTo.join(", ")}`);
224
+ if (!sendTo.includes(room))
225
+ throw new Error(`"${room}" is not a room this source may send to (${sendTo.join(", ")})`);
226
+ const text = String(message.text ?? "").trim();
227
+ if (!text)
228
+ throw new Error('there is nothing to send: give "text"');
229
+ await api("PUT", `/rooms/${encodeURIComponent(room)}/send/m.room.message/pine-${Date.now()}-${++sent}`, held.signal, { msgtype: "m.text", body: text.slice(0, 30_000) });
230
+ return `sent to the Matrix room ${room}`;
231
+ });
232
+ }
@@ -0,0 +1,15 @@
1
+ import type { SourceType } from "../source-types.ts";
2
+ import type { SourceApi } from "../sources.ts";
3
+ export interface Reading {
4
+ name: string;
5
+ address: number;
6
+ kind: string;
7
+ type: string;
8
+ scale: number;
9
+ step?: number;
10
+ words: "be" | "le";
11
+ }
12
+ /** The list of values as it is used: checked one by one, defaults filled in. Throws a sentence for what cannot work. */
13
+ export declare function readings(raw: unknown): Reading[];
14
+ export declare const type: SourceType;
15
+ export default function modbus(source: SourceApi): void;
@@ -0,0 +1,240 @@
1
+ import net from "node:net";
2
+ import { Type } from "typebox";
3
+ import { isLocalHost, reachOptions } from "../net.js";
4
+ import { errText, parseDuration } from "../util.js";
5
+ import { harmless } from "../watching.js";
6
+ /**
7
+ * A Modbus TCP device, read again and again: reports the values that changed. For what speaks
8
+ * Modbus on the network: solar inverters, batteries, heat pumps, wall boxes, energy meters.
9
+ *
10
+ * options: { host, read, port?, unit?, every?, local? }
11
+ * read the values to read, 1 to 32: { name, address, kind?, type?, scale?, step?, words? }
12
+ * address the register's number as the protocol counts it, from 0
13
+ * kind "holding" (default), "input", "coil" or "discrete"
14
+ * type "u16" (default), "i16", "u32", "i32" or "f32" (the last three are two registers)
15
+ * scale the raw value is multiplied by it (0.1 for a value in tenths)
16
+ * step how far the value must have moved since it was last reported
17
+ * words "be" (default) or "le": which of the two registers of a 32-bit value comes first
18
+ * unit the device's unit id (1 by default)
19
+ * every how often to read ("30s" by default)
20
+ *
21
+ * event "changed": { name, value, previous } one for each value that moved
22
+ *
23
+ * It reads and nothing else: only the four reading functions of the protocol (1 to 4) are ever
24
+ * sent, so nothing on the device can be switched or set through it. The first look is the
25
+ * starting point and reports nothing.
26
+ */
27
+ const MIN = 2000;
28
+ const TIMEOUT = 5000;
29
+ const KINDS = { coil: 1, discrete: 2, holding: 3, input: 4 };
30
+ const TYPES = ["u16", "i16", "u32", "i32", "f32"];
31
+ const EXCEPTIONS = {
32
+ 1: "illegal function",
33
+ 2: "illegal data address",
34
+ 3: "illegal data value",
35
+ 4: "device failure",
36
+ 5: "acknowledge",
37
+ 6: "device busy",
38
+ 8: "memory parity error",
39
+ 10: "gateway path unavailable",
40
+ 11: "gateway target device failed to respond",
41
+ };
42
+ /** The list of values as it is used: checked one by one, defaults filled in. Throws a sentence for what cannot work. */
43
+ export function readings(raw) {
44
+ if (!Array.isArray(raw) || !raw.length)
45
+ throw new Error('needs "read": the values to read, e.g. [{"name": "power", "address": 40083, "type": "i16"}]');
46
+ if (raw.length > 32)
47
+ throw new Error('"read" takes 32 values at most. Set up a second source for more');
48
+ const names = new Set();
49
+ return raw.map((r, i) => {
50
+ const at = `read[${i}]`;
51
+ if (!r || typeof r !== "object")
52
+ throw new Error(`${at} must be an object: {"name": "...", "address": 0}`);
53
+ const name = String(r.name ?? "");
54
+ if (!/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/.test(name))
55
+ throw new Error(`${at}: "name" is a short word for the value: letters, digits, _ . and -, starting with a letter`);
56
+ if (names.has(name))
57
+ throw new Error(`two values are called "${name}": give each its own name`);
58
+ names.add(name);
59
+ const kind = String(r.kind ?? "holding");
60
+ if (!(kind in KINDS))
61
+ throw new Error(`${name}: "kind" is holding, input, coil or discrete`);
62
+ const bit = kind === "coil" || kind === "discrete";
63
+ const type = bit ? "bit" : String(r.type ?? "u16");
64
+ if (!bit && !TYPES.includes(type))
65
+ throw new Error(`${name}: "type" is u16, i16, u32, i32 or f32`);
66
+ const address = Number(r.address);
67
+ const last = address + (/32/.test(type) ? 1 : 0);
68
+ if (!Number.isInteger(address) || address < 0 || last > 65535)
69
+ throw new Error(`${name}: "address" is the register's number counted from 0, up to 65535. A list that counts from 40001 or 30001 means the number minus that`);
70
+ const scale = r.scale === undefined ? 1 : Number(r.scale);
71
+ if (!Number.isFinite(scale) || scale === 0)
72
+ throw new Error(`${name}: "scale" is a number the raw value is multiplied by, e.g. 0.1`);
73
+ const step = r.step === undefined ? undefined : Number(r.step);
74
+ if (step !== undefined && !(step > 0))
75
+ throw new Error(`${name}: "step" is how far the value must move to be reported, a number above 0`);
76
+ const words = r.words === undefined ? "be" : r.words;
77
+ if (words !== "be" && words !== "le")
78
+ throw new Error(`${name}: "words" is "be" (the high word first) or "le" (the low word first)`);
79
+ return { name, address, kind, type, scale, ...(step !== undefined && !bit ? { step } : {}), words };
80
+ });
81
+ }
82
+ const hostOk = (host) => net.isIP(host) !== 0 || /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i.test(host);
83
+ export const type = {
84
+ summary: "a Modbus TCP device read again and again: reports the values that changed. For solar inverters, batteries, heat pumps, wall boxes, energy meters. It only reads",
85
+ options: Type.Object({
86
+ host: Type.String({ description: "the device's address on the network, e.g. 192.168.1.60" }),
87
+ read: Type.Array(Type.Object({
88
+ name: Type.String({ description: 'a short word for the value, e.g. "power"' }),
89
+ address: Type.Number({ description: "the register's number counted from 0. A register list that counts from 40001 (holding) or 30001 (input) means the number minus that" }),
90
+ kind: Type.Optional(Type.String({ description: '"holding" (default), "input", "coil" or "discrete"' })),
91
+ type: Type.Optional(Type.String({ description: '"u16" (default), "i16", "u32", "i32" or "f32". The last three take two registers' })),
92
+ scale: Type.Optional(Type.Number({ description: "the raw value is multiplied by this, e.g. 0.1 for a value given in tenths" })),
93
+ step: Type.Optional(Type.Number({ description: "report the value only when it has moved at least this far since the last report, e.g. 100 for watts. Without it every change counts" })),
94
+ words: Type.Optional(Type.String({ description: 'for a 32-bit value: "be" (default, the high word first) or "le" (the low word first)' })),
95
+ }, { additionalProperties: false }), { description: 'the values to read, 1 to 32, e.g. [{"name": "power", "address": 40083, "type": "i16", "step": 100}]. The device\'s Modbus register list says which register holds what' }),
96
+ port: Type.Optional(Type.Number({ description: "the port. Default 502" })),
97
+ unit: Type.Optional(Type.Number({ description: "the device's unit id (also called slave id). Default 1" })),
98
+ every: Type.Optional(Type.String({ description: 'how often to read, e.g. "30s", "5m". Default "30s", at least "2s"' })),
99
+ local: Type.Optional(Type.Boolean({ description: "true if the address is a name on your owner's own network that does not say so (inverter.lan). Not needed for an IP address or a .local name" })),
100
+ }, { additionalProperties: false }),
101
+ plan(o) {
102
+ const host = String(o.host ?? "").trim();
103
+ if (!hostOk(host))
104
+ throw new Error(`"${host}" is not an address. A Modbus device's looks like 192.168.1.60`);
105
+ const port = o.port ?? 502;
106
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
107
+ throw new Error('"port" must be a port number. Modbus TCP uses 502');
108
+ const unit = o.unit ?? 1;
109
+ if (!Number.isInteger(unit) || unit < 0 || unit > 255)
110
+ throw new Error('"unit" is the device\'s unit id, a number from 0 to 255');
111
+ const every = o.every ?? "30s";
112
+ if (parseDuration(every) < MIN)
113
+ throw new Error('"every" must be at least "2s"');
114
+ const read = readings(o.read);
115
+ return {
116
+ options: { ...o, host, read },
117
+ does: [
118
+ `connect to the Modbus device at ${host}:${port}${o.local || isLocalHost(host) ? " (an address on your own network or this computer)" : ""}, unit ${unit}, every ${every} and read ${read.length} value${read.length === 1 ? "" : "s"} (${read.map((r) => r.name).join(", ")})`,
119
+ "report each value when it changes. It only reads: nothing on the device is switched or set",
120
+ ],
121
+ opens: true,
122
+ tell: "Its first look is the starting point and reports nothing; from then on only a value that moved does. The sources tool shows what it read at the last look.",
123
+ };
124
+ },
125
+ };
126
+ /** One question and its answer on an open connection. Rejects when the answer does not come in time or the connection ends. */
127
+ function exchange(sock, frame, signal) {
128
+ return new Promise((resolve, reject) => {
129
+ let got = Buffer.alloc(0);
130
+ const done = (err, answer) => {
131
+ clearTimeout(timer);
132
+ sock.off("data", data).off("error", fail).off("close", closed);
133
+ signal.removeEventListener("abort", stopped);
134
+ if (err)
135
+ reject(err);
136
+ else
137
+ resolve(answer);
138
+ };
139
+ const data = (d) => {
140
+ got = Buffer.concat([got, d]);
141
+ if (got.length > 300)
142
+ return done(new Error("it answered with something that is not Modbus"));
143
+ if (got.length >= 6 && got.length >= 6 + got.readUInt16BE(4))
144
+ done(undefined, got.subarray(0, 6 + got.readUInt16BE(4)));
145
+ };
146
+ const fail = (e) => done(new Error(e.code === "ECONNRESET" || e.code === "EPIPE" ? "it closed the connection" : errText(e)));
147
+ const closed = () => done(new Error("it closed the connection"));
148
+ const stopped = () => done(new Error("stopped"));
149
+ const timer = setTimeout(() => done(new Error(`it did not answer within ${TIMEOUT / 1000} s`)), TIMEOUT);
150
+ // Gone between two questions: said at once, not after the time an answer may take.
151
+ if (sock.destroyed || !sock.writable)
152
+ return done(new Error("it closed the connection"));
153
+ sock.on("data", data).on("error", fail).on("close", closed);
154
+ signal.addEventListener("abort", stopped, { once: true });
155
+ sock.write(frame);
156
+ });
157
+ }
158
+ /** What the registers or bits of an answer say, as the value's type reads them. */
159
+ function decode(r, data) {
160
+ if (r.type === "bit")
161
+ return (data[0] & 1) === 1;
162
+ if (r.type === "u16")
163
+ return tidy(data.readUInt16BE(0) * r.scale);
164
+ if (r.type === "i16")
165
+ return tidy(data.readInt16BE(0) * r.scale);
166
+ const four = r.words === "le" ? Buffer.concat([data.subarray(2, 4), data.subarray(0, 2)]) : data.subarray(0, 4);
167
+ if (r.type === "u32")
168
+ return tidy(four.readUInt32BE(0) * r.scale);
169
+ if (r.type === "i32")
170
+ return tidy(four.readInt32BE(0) * r.scale);
171
+ const f = four.readFloatBE(0);
172
+ // A float of 32 bits carries seven digits; the rest is noise that would look like a change.
173
+ return Number.isFinite(f) ? tidy(Number((f * r.scale).toPrecision(7))) : null;
174
+ }
175
+ /** Without the tail a multiplication in binary leaves (0.1 * 3 is not 0.3). */
176
+ const tidy = (n) => Number(n.toPrecision(12));
177
+ export default function modbus(source) {
178
+ const o = source.options;
179
+ const host = String(o.host ?? "").trim();
180
+ if (!hostOk(host))
181
+ throw new Error(`needs "host": the device's address, e.g. 192.168.1.60`);
182
+ const port = Number(o.port ?? 502);
183
+ const unit = Number(o.unit ?? 1);
184
+ const read = readings(o.read);
185
+ let tid = 0;
186
+ source.poll(o.every ?? "30s", async (signal) => {
187
+ const sock = net.connect({ host, port, ...reachOptions(host, o.local === true) });
188
+ sock.setNoDelay(true);
189
+ const values = [];
190
+ try {
191
+ await new Promise((resolve, reject) => {
192
+ const timer = setTimeout(() => reject(new Error(`${host}:${port} did not take the connection within ${TIMEOUT / 1000} s`)), TIMEOUT);
193
+ sock.once("connect", () => (clearTimeout(timer), resolve()));
194
+ sock.once("error", (e) => (clearTimeout(timer), reject(new Error(errText(e)))));
195
+ signal.addEventListener("abort", () => (clearTimeout(timer), reject(new Error("stopped"))), { once: true });
196
+ });
197
+ // An error between two questions is found by the next question, not thrown into the daemon.
198
+ sock.on("error", () => { });
199
+ for (const r of read) {
200
+ const fc = KINDS[r.kind];
201
+ const count = /32/.test(r.type) ? 2 : 1;
202
+ tid = (tid + 1) & 0xffff;
203
+ const frame = Buffer.alloc(12);
204
+ frame.writeUInt16BE(tid, 0);
205
+ frame.writeUInt16BE(6, 4);
206
+ frame[6] = unit;
207
+ frame[7] = fc;
208
+ frame.writeUInt16BE(r.address, 8);
209
+ frame.writeUInt16BE(count, 10);
210
+ const answer = await exchange(sock, frame, signal);
211
+ if (answer.length < 9 || answer.readUInt16BE(0) !== tid || answer.readUInt16BE(2) !== 0 || answer[6] !== unit)
212
+ throw new Error(`it answered something else than what was asked for ${r.name}`);
213
+ if (answer[7] === (fc | 0x80))
214
+ throw new Error(`the device says: ${EXCEPTIONS[answer[8]] ?? "an error"} (${answer[8]}) for ${r.name}`);
215
+ const need = r.type === "bit" ? 1 : count * 2;
216
+ if (answer[7] !== fc || answer[8] < need || answer.length < 9 + need)
217
+ throw new Error(`it answered something else than what was asked for ${r.name}`);
218
+ values.push(decode(r, answer.subarray(9, 9 + need)));
219
+ }
220
+ }
221
+ finally {
222
+ sock.destroy();
223
+ }
224
+ if (signal.aborted)
225
+ return;
226
+ source.status(`${read.length} value${read.length === 1 ? "" : "s"}: ${read.slice(0, 4).map((r, i) => `${r.name} ${harmless(values[i])}`).join(", ")}${read.length > 4 ? ", ..." : ""}`);
227
+ read.forEach((r, i) => {
228
+ const value = values[i];
229
+ // What was last reported, not what was last read: a value that creeps is reported once it has crept a step.
230
+ const was = source.kv.get(`value:${r.name}`);
231
+ if (!was)
232
+ return void source.kv.set(`value:${r.name}`, { value });
233
+ const moved = r.step !== undefined && typeof value === "number" && typeof was.value === "number" ? Math.abs(value - was.value) >= r.step : value !== was.value;
234
+ if (!moved)
235
+ return;
236
+ source.kv.set(`value:${r.name}`, { value });
237
+ source.emit("changed", { name: r.name, value, previous: was.value });
238
+ });
239
+ });
240
+ }
@@ -0,0 +1,35 @@
1
+ import type { SourceType } from "../source-types.ts";
2
+ import type { SourceApi } from "../sources.ts";
3
+ /**
4
+ * The pauses and waits, in one place. A test shortens them.
5
+ * retryMs, retryMaxMs before a new subscription after a failure: the first pause, and the longest
6
+ * waitSec how long the camera may hold one question open when nothing happens
7
+ * leaseSec how long a subscription lives unless it is renewed (it is, at half that time)
8
+ * idleMs the pause after an answer that came at once and was empty
9
+ */
10
+ export declare const timing: {
11
+ retryMs: number;
12
+ retryMaxMs: number;
13
+ waitSec: number;
14
+ leaseSec: number;
15
+ idleMs: number;
16
+ };
17
+ /** The first element with this local name, whatever prefix the camera gives its namespace: its attributes and what is inside. */
18
+ export declare function element(xml: string, name: string): {
19
+ attrs: string;
20
+ inner: string;
21
+ } | undefined;
22
+ export interface Notification {
23
+ topic: string;
24
+ source: Record<string, string>;
25
+ data: Record<string, string | number | boolean>;
26
+ time?: string;
27
+ /** "Initialized" (the state when the subscription began), "Changed", "Deleted", or nothing for something that just happened. */
28
+ operation?: string;
29
+ }
30
+ /** The notifications in an answer to PullMessages. */
31
+ export declare function notifications(xml: string): Notification[];
32
+ /** The WS-Security header a camera checks: the password is never sent, only a digest over a nonce, the time and the password. */
33
+ export declare function security(user: string, password: string, now: Date, nonce?: Buffer): string;
34
+ export declare const type: SourceType;
35
+ export default function onvif(source: SourceApi): void;