@sedge-hq/mqtt 0.0.0-stage → 0.1.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 +14 -2
- package/package.json +48 -5
- package/src/mqtt.ts +127 -0
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sedge-hq/mqtt
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MQTT for [sedge](https://sedge.sh), the always-on agent. One signal, **`mqtt`**: it subscribes to
|
|
4
|
+
topics on your broker (Mosquitto, Home Assistant's, EMQX, HiveMQ), with `+` and `#` wildcards, and
|
|
5
|
+
each message wakes sedge with its topic and payload.
|
|
6
|
+
|
|
7
|
+
- `mqtt://`, `mqtts://` (TLS) and `wss://` (WebSocket) brokers; a password goes to your keychain.
|
|
8
|
+
- A session kept on the broker: messages sent while sedge was stopped arrive when it's back.
|
|
9
|
+
- Retained values, sent again on every subscribe, aren't reported.
|
|
10
|
+
|
|
11
|
+
In `sedge`, say "tell me when the basil's soil sensor on home/basil/soil reads dry, at most every
|
|
12
|
+
hour". sedge's `match`, `ignore` and `batch` settings keep a chatty sensor from waking it for every
|
|
13
|
+
reading.
|
|
14
|
+
|
|
15
|
+
[Channels and signals](https://github.com/sedge-hq/sedge/blob/main/docs/channels-and-signals.md) · MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@sedge-hq/mqtt",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MQTT for sedge: wake it when a message arrives on a topic, from a sensor, a home hub or a device.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"iot",
|
|
7
|
+
"mqtt",
|
|
8
|
+
"sedge",
|
|
9
|
+
"sedge-kit"
|
|
10
|
+
],
|
|
11
|
+
"homepage": "https://sedge.sh",
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/sedge-hq/sedge.git",
|
|
16
|
+
"directory": "packages/mqtt"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"!src/**/*.test.ts"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": "./src/mqtt.ts"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"typecheck": "tsc --noEmit",
|
|
31
|
+
"test": "bun --bun vitest run --passWithNoTests"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@sedge-hq/kit": "0.3.2",
|
|
35
|
+
"mqtt": "5.16.1"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@sedge-hq/config": "0.0.0",
|
|
39
|
+
"@types/bun": "1.4.4",
|
|
40
|
+
"aedes": "1.2.0",
|
|
41
|
+
"typescript": "7.0.2",
|
|
42
|
+
"vitest": "5.1.1"
|
|
43
|
+
},
|
|
44
|
+
"sedge": {
|
|
45
|
+
"plugins": [
|
|
46
|
+
"./src/mqtt.ts"
|
|
47
|
+
]
|
|
48
|
+
}
|
|
49
|
+
}
|
package/src/mqtt.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { defineSignal, field, type Happening, secret } from '@sedge-hq/kit';
|
|
2
|
+
import mqtt from 'mqtt';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const KEEP = 20_000;
|
|
6
|
+
|
|
7
|
+
const clip = (text: string) =>
|
|
8
|
+
text.length > KEEP ? `${text.slice(0, KEEP)}\n… (${text.length - KEEP} more characters)` : text;
|
|
9
|
+
|
|
10
|
+
/** A payload as the agent reads it: JSON laid out, text as it is, binary only by its size. */
|
|
11
|
+
export const readable = (payload: Uint8Array): string => {
|
|
12
|
+
let text: string;
|
|
13
|
+
try {
|
|
14
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(payload);
|
|
15
|
+
} catch {
|
|
16
|
+
return `(${payload.length} bytes of binary)`;
|
|
17
|
+
}
|
|
18
|
+
if (text.includes('\u0000')) return `(${payload.length} bytes of binary)`;
|
|
19
|
+
try {
|
|
20
|
+
const value: unknown = JSON.parse(text);
|
|
21
|
+
if (typeof value === 'object' && value !== null)
|
|
22
|
+
return clip(JSON.stringify(value, null, 2));
|
|
23
|
+
} catch {
|
|
24
|
+
// Not JSON: plain text.
|
|
25
|
+
}
|
|
26
|
+
return clip(text);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/** One event per message: the topic, then what was sent. */
|
|
30
|
+
export const happening = (topic: string, payload: Uint8Array): Happening => {
|
|
31
|
+
const body = readable(payload);
|
|
32
|
+
return { text: body.includes('\n') ? `${topic}\n${body}` : `${topic}: ${body}` };
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** A sensor, a home hub, a device: anything that publishes to an MQTT broker. */
|
|
36
|
+
export default defineSignal({
|
|
37
|
+
name: 'mqtt',
|
|
38
|
+
summary: 'messages on MQTT topics: sensors, home automation, devices',
|
|
39
|
+
settings: {
|
|
40
|
+
url: field.text(
|
|
41
|
+
'The broker, like mqtt://localhost:1883, mqtts://broker.example.com:8883 (TLS) or wss://… (WebSocket).',
|
|
42
|
+
),
|
|
43
|
+
topics: field.list(
|
|
44
|
+
'Topics to subscribe to. + matches one level and # the rest: home/+/soil, sensors/#.',
|
|
45
|
+
),
|
|
46
|
+
username: field.optional(field.text('The username, if the broker asks for one.')),
|
|
47
|
+
password: field.optional(secret('The password, if the broker asks for one.')),
|
|
48
|
+
},
|
|
49
|
+
watch: ({ url, topics, username, password }, kit) => {
|
|
50
|
+
const items: Array<Happening> = [];
|
|
51
|
+
let wake: (() => void) | undefined;
|
|
52
|
+
let failure: Error | undefined;
|
|
53
|
+
const poke = () => {
|
|
54
|
+
wake?.();
|
|
55
|
+
wake = undefined;
|
|
56
|
+
};
|
|
57
|
+
const fail = (error: Error) => {
|
|
58
|
+
failure ??= error;
|
|
59
|
+
poke();
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
async *[Symbol.asyncIterator]() {
|
|
64
|
+
// The same client id every time, with a session the broker keeps: messages at
|
|
65
|
+
// QoS 1 that arrive while sedge is stopped are delivered when it's back.
|
|
66
|
+
let clientId = await kit.memo.get('client-id');
|
|
67
|
+
if (!clientId) {
|
|
68
|
+
clientId = `sedge-${randomBytes(6).toString('hex')}`;
|
|
69
|
+
await kit.memo.set('client-id', clientId);
|
|
70
|
+
}
|
|
71
|
+
const client = mqtt.connect(url, {
|
|
72
|
+
clientId,
|
|
73
|
+
clean: false,
|
|
74
|
+
// A lost connection ends this watch; the kit starts it again, backing off.
|
|
75
|
+
reconnectPeriod: 0,
|
|
76
|
+
connectTimeout: 30_000,
|
|
77
|
+
...(username ? { username } : {}),
|
|
78
|
+
...(password ? { password } : {}),
|
|
79
|
+
});
|
|
80
|
+
const stop = () => {
|
|
81
|
+
client.end(true);
|
|
82
|
+
poke();
|
|
83
|
+
};
|
|
84
|
+
kit.signal.addEventListener('abort', stop);
|
|
85
|
+
client.on('connect', () => {
|
|
86
|
+
client.subscribe([...topics], { qos: 1 }, (error, granted) => {
|
|
87
|
+
if (error) return fail(error);
|
|
88
|
+
const refused = (granted ?? []).filter((g) => g.qos === 128);
|
|
89
|
+
if (refused.length > 0) {
|
|
90
|
+
return fail(
|
|
91
|
+
new Error(
|
|
92
|
+
`the broker refused ${refused.map((g) => g.topic).join(', ')}`,
|
|
93
|
+
),
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
kit.status(`subscribed to ${topics.join(', ')} on ${new URL(url).host}`);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
client.on('message', (topic, payload, packet) => {
|
|
100
|
+
// A retained message is the topic's last value, sent again on every
|
|
101
|
+
// subscribe: it's news only the first time, so it isn't reported.
|
|
102
|
+
if (packet.retain) return;
|
|
103
|
+
items.push(happening(topic, payload));
|
|
104
|
+
poke();
|
|
105
|
+
});
|
|
106
|
+
client.on('error', fail);
|
|
107
|
+
client.on('close', () => {
|
|
108
|
+
if (!kit.signal.aborted) fail(new Error(`lost the connection to ${url}`));
|
|
109
|
+
});
|
|
110
|
+
try {
|
|
111
|
+
while (!kit.signal.aborted) {
|
|
112
|
+
const item = items.shift();
|
|
113
|
+
if (item) {
|
|
114
|
+
yield item;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (failure) throw failure;
|
|
118
|
+
await new Promise<void>((resolve) => (wake = resolve));
|
|
119
|
+
}
|
|
120
|
+
} finally {
|
|
121
|
+
kit.signal.removeEventListener('abort', stop);
|
|
122
|
+
client.end(true);
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
},
|
|
127
|
+
});
|