zigbee2mqtt-mcp 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/LICENSE +21 -0
- package/README.md +156 -0
- package/dist/client.js +293 -0
- package/dist/config.js +81 -0
- package/dist/devices.js +187 -0
- package/dist/index.js +70 -0
- package/dist/tools.js +770 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alex Pfau
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
# zigbee2mqtt-mcp
|
|
2
|
+
|
|
3
|
+
A [Model Context Protocol](https://modelcontextprotocol.io) server for **administering** a Zigbee2MQTT estate.
|
|
4
|
+
|
|
5
|
+
Most Zigbee integrations already let an assistant turn a light on. This one is for the layer underneath: mesh health, weak links, devices that keep rejoining, stale batteries, firmware updates, pairing, binding, reporting intervals and device options — the things you normally open the Zigbee2MQTT frontend for.
|
|
6
|
+
|
|
7
|
+
It talks directly to the Zigbee2MQTT [MQTT bridge API](https://www.zigbee2mqtt.io/guide/usage/mqtt_topics_and_messages.html), so it works with any Zigbee2MQTT 1.17+ installation regardless of whether you use Home Assistant, Node-RED, openHAB or nothing at all.
|
|
8
|
+
|
|
9
|
+
## Why this exists
|
|
10
|
+
|
|
11
|
+
If you already run Home Assistant, your Zigbee devices are exposed there and an assistant can control them. What Home Assistant does *not* expose is the bridge itself: link quality, mesh topology, interview state, OTA availability, `permit_join`, device options, bindings and reporting configuration. This server fills exactly that gap.
|
|
12
|
+
|
|
13
|
+
## Design
|
|
14
|
+
|
|
15
|
+
- **No database.** Zigbee2MQTT publishes its bridge topics as retained messages, so a fresh subscription yields a complete picture in a few hundred milliseconds. The server keeps only the latest payload per topic in memory.
|
|
16
|
+
- **No daemon.** Pure stdio. It starts and dies with the MCP session.
|
|
17
|
+
- **Correlated requests.** Every `bridge/request/*` carries a `transaction` id and is matched to its `bridge/response/*`, so concurrent calls cannot cross wires.
|
|
18
|
+
- **Tiered writes.** Destructive operations are gated behind a write mode *and* an explicit `confirm` argument.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
Requires Node.js 20 or newer and network access to the MQTT broker that Zigbee2MQTT uses.
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npx zigbee2mqtt-mcp
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### VS Code / GitHub Copilot
|
|
29
|
+
|
|
30
|
+
Add to your MCP configuration:
|
|
31
|
+
|
|
32
|
+
```jsonc
|
|
33
|
+
{
|
|
34
|
+
"servers": {
|
|
35
|
+
"zigbee2mqtt": {
|
|
36
|
+
"command": "npx",
|
|
37
|
+
"args": ["-y", "zigbee2mqtt-mcp"],
|
|
38
|
+
"env": {
|
|
39
|
+
"Z2M_MQTT_URL": "mqtt://192.168.1.10:1883",
|
|
40
|
+
"Z2M_MQTT_USERNAME": "mqtt",
|
|
41
|
+
"Z2M_MQTT_PASSWORD": "${input:z2mPassword}"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Claude Desktop
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"mcpServers": {
|
|
53
|
+
"zigbee2mqtt": {
|
|
54
|
+
"command": "npx",
|
|
55
|
+
"args": ["-y", "zigbee2mqtt-mcp"],
|
|
56
|
+
"env": {
|
|
57
|
+
"Z2M_MQTT_URL": "mqtt://192.168.1.10:1883"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
> Point `Z2M_MQTT_URL` at your **MQTT broker**, not at the Zigbee2MQTT frontend port. If Zigbee2MQTT's `configuration.yaml` says `mqtt.server: mqtt://192.168.1.10:1883`, use that value verbatim.
|
|
65
|
+
|
|
66
|
+
## Configuration
|
|
67
|
+
|
|
68
|
+
| Variable | Default | Purpose |
|
|
69
|
+
| --- | --- | --- |
|
|
70
|
+
| `Z2M_MQTT_URL` | *required* | Broker URL. `mqtt://`, `mqtts://`, `ws://`, `wss://` |
|
|
71
|
+
| `Z2M_MQTT_USERNAME` / `Z2M_MQTT_PASSWORD` | – | Broker credentials |
|
|
72
|
+
| `Z2M_BASE_TOPIC` | `zigbee2mqtt` | Must match `mqtt.base_topic` |
|
|
73
|
+
| `Z2M_WRITE_MODE` | `full` | `off`, `safe` or `full` |
|
|
74
|
+
| `Z2M_LOG_LEVEL` | `error` | Diagnostics on stderr |
|
|
75
|
+
| `Z2M_WEAK_LINK_THRESHOLD` | `30` | Link quality below this is flagged |
|
|
76
|
+
| `Z2M_LOW_BATTERY_THRESHOLD` | `20` | Battery percentage below this is flagged |
|
|
77
|
+
| `Z2M_STALE_HOURS` | `24` | Hours of silence before a device is stale |
|
|
78
|
+
| `Z2M_CONNECT_TIMEOUT_MS` | `10000` | Broker connect timeout |
|
|
79
|
+
| `Z2M_REQUEST_TIMEOUT_MS` | `15000` | Default bridge request timeout |
|
|
80
|
+
| `Z2M_MQTT_REJECT_UNAUTHORIZED` | `true` | Set `false` for self-signed TLS |
|
|
81
|
+
| `Z2M_MQTT_CA` / `_CERT` / `_KEY` | – | Paths to TLS material |
|
|
82
|
+
|
|
83
|
+
## Write modes
|
|
84
|
+
|
|
85
|
+
Tools above the active tier are not registered at all, so a model cannot reach for them.
|
|
86
|
+
|
|
87
|
+
| Mode | Exposes |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `off` | Read-only tools |
|
|
90
|
+
| `safe` | Read plus non-destructive writes: pairing, options, rename, configure, interview, binding, reporting, groups, state |
|
|
91
|
+
| `full` | Everything, including device removal, OTA flashing, Touchlink and bridge restart |
|
|
92
|
+
|
|
93
|
+
Irreversible tools (`z2m_remove_device`, `z2m_ota_update`, `z2m_touchlink`, `z2m_restart_bridge`, `z2m_set_bridge_options`) additionally require `confirm: true` on every call.
|
|
94
|
+
|
|
95
|
+
## Tools
|
|
96
|
+
|
|
97
|
+
### Read
|
|
98
|
+
|
|
99
|
+
| Tool | Purpose |
|
|
100
|
+
| --- | --- |
|
|
101
|
+
| `z2m_bridge_info` | Version, coordinator, channel, PAN ID, permit_join, restart_required, runtime stats |
|
|
102
|
+
| `z2m_list_devices` | Filter and sort devices by type, availability, link quality, battery, pending update |
|
|
103
|
+
| `z2m_get_device` | Exposes, settable options, endpoints, bindings, configured reportings, current state |
|
|
104
|
+
| `z2m_health_report` | Whole-estate audit in one call |
|
|
105
|
+
| `z2m_network_map` | Mesh topology with parent, depth, link quality, orphan detection |
|
|
106
|
+
| `z2m_list_groups` | Groups, members and scenes |
|
|
107
|
+
| `z2m_get_logs` | Bridge logs and lifecycle events, buffered or watched live |
|
|
108
|
+
|
|
109
|
+
### Safe writes
|
|
110
|
+
|
|
111
|
+
`z2m_check_updates`, `z2m_permit_join`, `z2m_set_device_options`, `z2m_rename_device`, `z2m_configure_device`, `z2m_interview_device`, `z2m_set_state`, `z2m_manage_group`, `z2m_bind`, `z2m_configure_reporting`
|
|
112
|
+
|
|
113
|
+
### Full writes
|
|
114
|
+
|
|
115
|
+
`z2m_remove_device`, `z2m_ota_update`, `z2m_restart_bridge`, `z2m_set_bridge_options`, `z2m_coordinator_check`, `z2m_touchlink`
|
|
116
|
+
|
|
117
|
+
## Data availability caveats
|
|
118
|
+
|
|
119
|
+
Some fields depend on your Zigbee2MQTT configuration. The server detects what is available and tells you rather than silently returning nothing.
|
|
120
|
+
|
|
121
|
+
| Field | Requires | If missing |
|
|
122
|
+
| --- | --- | --- |
|
|
123
|
+
| `last_seen` | `advanced.last_seen` set to e.g. `ISO_8601` (default is `disable`) | Staleness checks are skipped and a hint is returned |
|
|
124
|
+
| `availability` | `availability.enabled: true` | Offline detection is skipped and a hint is returned |
|
|
125
|
+
| `linkquality`, `battery`, `update` | Live device traffic — Zigbee2MQTT does not retain device state topics | Pass `collect_seconds` to listen briefly, or use `z2m_network_map` for authoritative link quality |
|
|
126
|
+
| `z2m_coordinator_check` | A Texas Instruments adapter (CC2652/CC1352) | Returns an error on other adapters; `z2m_bridge_info` reports whether it is supported |
|
|
127
|
+
|
|
128
|
+
## Example prompts
|
|
129
|
+
|
|
130
|
+
- "Is my Zigbee network healthy?"
|
|
131
|
+
- "Which devices have the weakest signal?"
|
|
132
|
+
- "Which batteries need replacing?"
|
|
133
|
+
- "Any firmware updates available?"
|
|
134
|
+
- "Open the network for pairing via the kitchen router for two minutes."
|
|
135
|
+
- "This sensor stopped reporting temperature — fix it."
|
|
136
|
+
- "Bind the hallway remote to the hallway light so it works if the bridge is down."
|
|
137
|
+
|
|
138
|
+
## Development
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
npm install
|
|
142
|
+
npm run build
|
|
143
|
+
npm run watch
|
|
144
|
+
|
|
145
|
+
# Manual smoke test against a real instance
|
|
146
|
+
Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs
|
|
147
|
+
Z2M_MQTT_URL=mqtt://192.168.1.10:1883 node scripts/smoke.mjs z2m_list_devices '{"only_problems":true}'
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Safety
|
|
151
|
+
|
|
152
|
+
This server can remove devices from your network and flash firmware. Both are irreversible and OTA failures can brick hardware. Run with `Z2M_WRITE_MODE=safe` or `off` if you do not want an assistant able to do that. Broker credentials are read from the environment and never logged.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
MIT
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import mqtt from "mqtt";
|
|
2
|
+
const LOG_BUFFER = 1000;
|
|
3
|
+
const EVENT_BUFFER = 200;
|
|
4
|
+
/**
|
|
5
|
+
* Zigbee2MQTT publishes its bridge topics as retained messages, so a fresh
|
|
6
|
+
* subscription yields a complete picture within milliseconds. This client keeps
|
|
7
|
+
* only the latest payload per topic in memory - there is deliberately no
|
|
8
|
+
* database and no message history.
|
|
9
|
+
*/
|
|
10
|
+
export class Z2MClient {
|
|
11
|
+
config;
|
|
12
|
+
log;
|
|
13
|
+
client = null;
|
|
14
|
+
connectPromise = null;
|
|
15
|
+
transactionCounter = 0;
|
|
16
|
+
lastMessageAt = 0;
|
|
17
|
+
bridge = new Map();
|
|
18
|
+
deviceState = new Map();
|
|
19
|
+
availability = new Map();
|
|
20
|
+
logs = [];
|
|
21
|
+
events = [];
|
|
22
|
+
waiters = new Map();
|
|
23
|
+
constructor(config, log) {
|
|
24
|
+
this.config = config;
|
|
25
|
+
this.log = log;
|
|
26
|
+
}
|
|
27
|
+
// ---------------------------------------------------------------- lifecycle
|
|
28
|
+
async connect() {
|
|
29
|
+
if (this.client?.connected)
|
|
30
|
+
return;
|
|
31
|
+
if (!this.connectPromise) {
|
|
32
|
+
this.connectPromise = this.doConnect().finally(() => {
|
|
33
|
+
this.connectPromise = null;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return this.connectPromise;
|
|
37
|
+
}
|
|
38
|
+
doConnect() {
|
|
39
|
+
const { config } = this;
|
|
40
|
+
const options = {
|
|
41
|
+
username: config.username,
|
|
42
|
+
password: config.password,
|
|
43
|
+
clientId: config.clientId,
|
|
44
|
+
// A clean session avoids leaving orphaned subscriptions on the broker
|
|
45
|
+
// every time the MCP server restarts. Retained messages arrive regardless.
|
|
46
|
+
clean: true,
|
|
47
|
+
reconnectPeriod: 5_000,
|
|
48
|
+
connectTimeout: config.connectTimeoutMs,
|
|
49
|
+
rejectUnauthorized: config.rejectUnauthorized,
|
|
50
|
+
ca: config.ca,
|
|
51
|
+
cert: config.cert,
|
|
52
|
+
key: config.key,
|
|
53
|
+
};
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
this.log.debug(`connecting to ${config.mqttUrl}`);
|
|
56
|
+
const client = mqtt.connect(config.mqttUrl, options);
|
|
57
|
+
this.client = client;
|
|
58
|
+
let settled = false;
|
|
59
|
+
const fail = (error) => {
|
|
60
|
+
if (settled)
|
|
61
|
+
return;
|
|
62
|
+
settled = true;
|
|
63
|
+
client.end(true);
|
|
64
|
+
this.client = null;
|
|
65
|
+
reject(error);
|
|
66
|
+
};
|
|
67
|
+
const timer = setTimeout(() => fail(new Error(`Timed out connecting to ${config.mqttUrl} after ${config.connectTimeoutMs}ms`)), config.connectTimeoutMs);
|
|
68
|
+
client.on("error", (error) => {
|
|
69
|
+
this.log.error("mqtt error:", error.message);
|
|
70
|
+
fail(new Error(`MQTT connection to ${config.mqttUrl} failed: ${error.message}`));
|
|
71
|
+
});
|
|
72
|
+
client.on("message", (topic, payload) => this.handleMessage(topic, payload));
|
|
73
|
+
client.on("connect", () => {
|
|
74
|
+
this.log.debug("connected, subscribing");
|
|
75
|
+
client.subscribe(`${config.baseTopic}/#`, { qos: 1 }, (error) => {
|
|
76
|
+
if (error) {
|
|
77
|
+
fail(new Error(`Failed to subscribe to ${config.baseTopic}/#: ${error.message}`));
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
// Give retained bridge topics a moment to land before the first read.
|
|
81
|
+
this.waitForBridgeData()
|
|
82
|
+
.then(() => {
|
|
83
|
+
if (settled)
|
|
84
|
+
return;
|
|
85
|
+
settled = true;
|
|
86
|
+
clearTimeout(timer);
|
|
87
|
+
resolve();
|
|
88
|
+
})
|
|
89
|
+
.catch(fail);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
async waitForBridgeData(timeoutMs = 5_000) {
|
|
95
|
+
const deadline = Date.now() + timeoutMs;
|
|
96
|
+
while (Date.now() < deadline && !(this.bridge.has("devices") && this.bridge.has("info"))) {
|
|
97
|
+
await sleep(25);
|
|
98
|
+
}
|
|
99
|
+
if (!this.bridge.has("devices")) {
|
|
100
|
+
throw new Error(`Connected to the broker but received no retained '${this.config.baseTopic}/bridge/devices' ` +
|
|
101
|
+
`message within ${timeoutMs}ms. Check that Zigbee2MQTT is running and that Z2M_BASE_TOPIC ` +
|
|
102
|
+
`(currently '${this.config.baseTopic}') matches its mqtt.base_topic setting.`);
|
|
103
|
+
}
|
|
104
|
+
// Retained per-device availability topics arrive in a burst just after the
|
|
105
|
+
// bridge topics. Resolving too early loses them, so wait for a quiet period.
|
|
106
|
+
await this.settle(250, 2_000);
|
|
107
|
+
}
|
|
108
|
+
/** Wait until no message has arrived for `quietMs`, capped at `maxMs`. */
|
|
109
|
+
async settle(quietMs, maxMs) {
|
|
110
|
+
const deadline = Date.now() + maxMs;
|
|
111
|
+
while (Date.now() < deadline && Date.now() - this.lastMessageAt < quietMs) {
|
|
112
|
+
await sleep(25);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
async disconnect() {
|
|
116
|
+
const client = this.client;
|
|
117
|
+
this.client = null;
|
|
118
|
+
if (!client)
|
|
119
|
+
return;
|
|
120
|
+
// Drop the error handler first: a reconnect attempt racing the close would
|
|
121
|
+
// otherwise surface a spurious 'write after end'.
|
|
122
|
+
client.removeAllListeners("error");
|
|
123
|
+
client.on("error", () => undefined);
|
|
124
|
+
await new Promise((resolve) => client.end(false, {}, () => resolve()));
|
|
125
|
+
}
|
|
126
|
+
// ----------------------------------------------------------------- messages
|
|
127
|
+
handleMessage(topic, payload) {
|
|
128
|
+
const prefix = `${this.config.baseTopic}/`;
|
|
129
|
+
if (!topic.startsWith(prefix))
|
|
130
|
+
return;
|
|
131
|
+
this.lastMessageAt = Date.now();
|
|
132
|
+
const rest = topic.slice(prefix.length);
|
|
133
|
+
const raw = payload.toString();
|
|
134
|
+
const parsed = safeParse(raw);
|
|
135
|
+
if (rest.startsWith("bridge/response/")) {
|
|
136
|
+
this.resolveWaiter(rest.slice("bridge/response/".length), parsed);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (rest === "bridge/logging") {
|
|
140
|
+
const entry = parsed;
|
|
141
|
+
if (entry && typeof entry === "object") {
|
|
142
|
+
push(this.logs, LOG_BUFFER, {
|
|
143
|
+
received_at: new Date().toISOString(),
|
|
144
|
+
level: String(entry.level ?? "info"),
|
|
145
|
+
message: String(entry.message ?? raw),
|
|
146
|
+
namespace: entry.namespace,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (rest === "bridge/event") {
|
|
152
|
+
const event = parsed;
|
|
153
|
+
if (event && typeof event === "object") {
|
|
154
|
+
push(this.events, EVENT_BUFFER, {
|
|
155
|
+
received_at: new Date().toISOString(),
|
|
156
|
+
type: String(event.type ?? "unknown"),
|
|
157
|
+
data: event.data ?? {},
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (rest.startsWith("bridge/")) {
|
|
163
|
+
this.bridge.set(rest.slice("bridge/".length), parsed ?? raw);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// Friendly names may contain '/', so match on the suffix rather than splitting.
|
|
167
|
+
if (rest.endsWith("/availability")) {
|
|
168
|
+
const name = rest.slice(0, -"/availability".length);
|
|
169
|
+
const state = typeof parsed === "object" && parsed !== null
|
|
170
|
+
? String(parsed.state ?? raw)
|
|
171
|
+
: raw;
|
|
172
|
+
this.availability.set(name, state);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (/\/(set|get)(\/|$)/.test(rest))
|
|
176
|
+
return; // commands, not state
|
|
177
|
+
if (parsed && typeof parsed === "object") {
|
|
178
|
+
this.deviceState.set(rest, parsed);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
resolveWaiter(subTopic, parsed) {
|
|
182
|
+
if (!parsed || typeof parsed !== "object")
|
|
183
|
+
return;
|
|
184
|
+
const response = parsed;
|
|
185
|
+
const key = `${subTopic}|${response.transaction ?? ""}`;
|
|
186
|
+
const waiter = this.waiters.get(key);
|
|
187
|
+
if (waiter)
|
|
188
|
+
waiter(response);
|
|
189
|
+
}
|
|
190
|
+
// ----------------------------------------------------------------- requests
|
|
191
|
+
/**
|
|
192
|
+
* Publish to bridge/request/<subTopic> and await the matching
|
|
193
|
+
* bridge/response/<subTopic>, correlated via the `transaction` property.
|
|
194
|
+
*/
|
|
195
|
+
async request(subTopic, payload = {}, timeoutMs) {
|
|
196
|
+
await this.connect();
|
|
197
|
+
const client = this.client;
|
|
198
|
+
if (!client)
|
|
199
|
+
throw new Error("MQTT client is not connected");
|
|
200
|
+
const timeout = timeoutMs ?? this.config.requestTimeoutMs;
|
|
201
|
+
const transaction = `mcp-${++this.transactionCounter}`;
|
|
202
|
+
const key = `${subTopic}|${transaction}`;
|
|
203
|
+
return new Promise((resolve, reject) => {
|
|
204
|
+
const timer = setTimeout(() => {
|
|
205
|
+
this.waiters.delete(key);
|
|
206
|
+
reject(new Error(`Timed out after ${timeout}ms waiting for ${this.config.baseTopic}/bridge/response/${subTopic}. ` +
|
|
207
|
+
`The request may still be running on the bridge.`));
|
|
208
|
+
}, timeout);
|
|
209
|
+
this.waiters.set(key, (response) => {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
this.waiters.delete(key);
|
|
212
|
+
if (response.status === "error") {
|
|
213
|
+
reject(new Error(response.error ?? `Zigbee2MQTT returned an error for ${subTopic}`));
|
|
214
|
+
}
|
|
215
|
+
else {
|
|
216
|
+
resolve(response.data);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
const topic = `${this.config.baseTopic}/bridge/request/${subTopic}`;
|
|
220
|
+
this.log.debug(`-> ${topic}`, JSON.stringify(payload));
|
|
221
|
+
client.publish(topic, JSON.stringify({ ...payload, transaction }), { qos: 1 }, (error) => {
|
|
222
|
+
if (error) {
|
|
223
|
+
clearTimeout(timer);
|
|
224
|
+
this.waiters.delete(key);
|
|
225
|
+
reject(new Error(`Failed to publish to ${topic}: ${error.message}`));
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** Fire-and-forget publish, used for device `set` and `get` commands. */
|
|
231
|
+
async publish(topic, payload) {
|
|
232
|
+
await this.connect();
|
|
233
|
+
const client = this.client;
|
|
234
|
+
if (!client)
|
|
235
|
+
throw new Error("MQTT client is not connected");
|
|
236
|
+
const body = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
237
|
+
return new Promise((resolve, reject) => {
|
|
238
|
+
client.publish(topic, body, { qos: 1 }, (error) => error ? reject(new Error(`Failed to publish to ${topic}: ${error.message}`)) : resolve());
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
// ----------------------------------------------------------------- accessors
|
|
242
|
+
async bridgeTopic(name) {
|
|
243
|
+
await this.connect();
|
|
244
|
+
return this.bridge.get(name);
|
|
245
|
+
}
|
|
246
|
+
async snapshot() {
|
|
247
|
+
await this.connect();
|
|
248
|
+
return {
|
|
249
|
+
info: this.bridge.get("info"),
|
|
250
|
+
state: this.bridge.get("state"),
|
|
251
|
+
health: this.bridge.get("health"),
|
|
252
|
+
devices: this.bridge.get("devices") ?? [],
|
|
253
|
+
groups: this.bridge.get("groups") ?? [],
|
|
254
|
+
deviceState: this.deviceState,
|
|
255
|
+
availability: this.availability,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
recentLogs() {
|
|
259
|
+
return this.logs;
|
|
260
|
+
}
|
|
261
|
+
recentEvents() {
|
|
262
|
+
return this.events;
|
|
263
|
+
}
|
|
264
|
+
/** Collect log lines produced from now until the window elapses. */
|
|
265
|
+
async collectLogs(windowMs) {
|
|
266
|
+
await this.connect();
|
|
267
|
+
const from = this.logs.length;
|
|
268
|
+
await sleep(windowMs);
|
|
269
|
+
return this.logs.slice(from);
|
|
270
|
+
}
|
|
271
|
+
/** Listen for live device traffic, which is how linkquality and battery arrive. */
|
|
272
|
+
async collectState(windowMs) {
|
|
273
|
+
await this.connect();
|
|
274
|
+
await sleep(windowMs);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function sleep(ms) {
|
|
278
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
279
|
+
}
|
|
280
|
+
function safeParse(raw) {
|
|
281
|
+
try {
|
|
282
|
+
return JSON.parse(raw);
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
function push(buffer, max, item) {
|
|
289
|
+
buffer.push(item);
|
|
290
|
+
if (buffer.length > max)
|
|
291
|
+
buffer.splice(0, buffer.length - max);
|
|
292
|
+
}
|
|
293
|
+
//# sourceMappingURL=client.js.map
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
function int(name, fallback) {
|
|
3
|
+
const raw = process.env[name];
|
|
4
|
+
if (raw === undefined || raw === "")
|
|
5
|
+
return fallback;
|
|
6
|
+
const parsed = Number.parseInt(raw, 10);
|
|
7
|
+
if (Number.isNaN(parsed)) {
|
|
8
|
+
throw new Error(`${name} must be an integer, got ${JSON.stringify(raw)}`);
|
|
9
|
+
}
|
|
10
|
+
return parsed;
|
|
11
|
+
}
|
|
12
|
+
function bool(name, fallback) {
|
|
13
|
+
const raw = process.env[name];
|
|
14
|
+
if (raw === undefined || raw === "")
|
|
15
|
+
return fallback;
|
|
16
|
+
return !["0", "false", "no", "off"].includes(raw.toLowerCase());
|
|
17
|
+
}
|
|
18
|
+
function file(name) {
|
|
19
|
+
const path = process.env[name];
|
|
20
|
+
if (!path)
|
|
21
|
+
return undefined;
|
|
22
|
+
try {
|
|
23
|
+
return readFileSync(path);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
throw new Error(`${name}: cannot read ${path}: ${error.message}`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function oneOf(name, allowed, fallback) {
|
|
30
|
+
const raw = process.env[name];
|
|
31
|
+
if (raw === undefined || raw === "")
|
|
32
|
+
return fallback;
|
|
33
|
+
const value = raw.toLowerCase();
|
|
34
|
+
if (!allowed.includes(value)) {
|
|
35
|
+
throw new Error(`${name} must be one of ${allowed.join(", ")}, got ${JSON.stringify(raw)}`);
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
export function loadConfig() {
|
|
40
|
+
const mqttUrl = process.env.Z2M_MQTT_URL;
|
|
41
|
+
if (!mqttUrl) {
|
|
42
|
+
throw new Error("Z2M_MQTT_URL is required, e.g. mqtt://192.168.1.10:1883 " +
|
|
43
|
+
"(mqtt://, mqtts://, ws:// and wss:// are supported).");
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
mqttUrl,
|
|
47
|
+
username: process.env.Z2M_MQTT_USERNAME || undefined,
|
|
48
|
+
password: process.env.Z2M_MQTT_PASSWORD || undefined,
|
|
49
|
+
baseTopic: (process.env.Z2M_BASE_TOPIC || "zigbee2mqtt").replace(/\/+$/, ""),
|
|
50
|
+
clientId: process.env.Z2M_MQTT_CLIENT_ID || `zigbee2mqtt-mcp-${process.pid}`,
|
|
51
|
+
rejectUnauthorized: bool("Z2M_MQTT_REJECT_UNAUTHORIZED", true),
|
|
52
|
+
ca: file("Z2M_MQTT_CA"),
|
|
53
|
+
cert: file("Z2M_MQTT_CERT"),
|
|
54
|
+
key: file("Z2M_MQTT_KEY"),
|
|
55
|
+
connectTimeoutMs: int("Z2M_CONNECT_TIMEOUT_MS", 10_000),
|
|
56
|
+
requestTimeoutMs: int("Z2M_REQUEST_TIMEOUT_MS", 15_000),
|
|
57
|
+
writeMode: oneOf("Z2M_WRITE_MODE", ["off", "safe", "full"], "full"),
|
|
58
|
+
logLevel: oneOf("Z2M_LOG_LEVEL", ["silent", "error", "warn", "info", "debug"], "error"),
|
|
59
|
+
weakLinkThreshold: int("Z2M_WEAK_LINK_THRESHOLD", 30),
|
|
60
|
+
lowBatteryThreshold: int("Z2M_LOW_BATTERY_THRESHOLD", 20),
|
|
61
|
+
staleHours: int("Z2M_STALE_HOURS", 24),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const LEVELS = { silent: 0, error: 1, warn: 2, info: 3, debug: 4 };
|
|
65
|
+
/**
|
|
66
|
+
* stdio transport owns stdout, so every diagnostic must go to stderr.
|
|
67
|
+
*/
|
|
68
|
+
export function createLogger(level) {
|
|
69
|
+
const emit = (at, args) => {
|
|
70
|
+
if (LEVELS[level] >= LEVELS[at]) {
|
|
71
|
+
console.error(`[zigbee2mqtt-mcp] [${at}]`, ...args);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
error: (...args) => emit("error", args),
|
|
76
|
+
warn: (...args) => emit("warn", args),
|
|
77
|
+
info: (...args) => emit("info", args),
|
|
78
|
+
debug: (...args) => emit("debug", args),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=config.js.map
|