From 5d30b60eda8b691b1c339cb6d8bfe688cc25c2d5 Mon Sep 17 00:00:00 2001 From: An-J Date: Tue, 5 May 2026 19:56:10 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20z2m=20Extension=20=D0=B4=D0=BB=D1=8F=20Last=5FSeen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- z2m-Extension-%D0%B4%D0%BB%D1%8F-Last_Seen.md | 583 ++++++++++++++++++ 1 file changed, 583 insertions(+) create mode 100644 z2m-Extension-%D0%B4%D0%BB%D1%8F-Last_Seen.md diff --git a/z2m-Extension-%D0%B4%D0%BB%D1%8F-Last_Seen.md b/z2m-Extension-%D0%B4%D0%BB%D1%8F-Last_Seen.md new file mode 100644 index 0000000..05dafd4 --- /dev/null +++ b/z2m-Extension-%D0%B4%D0%BB%D1%8F-Last_Seen.md @@ -0,0 +1,583 @@ +# 📘 Wiki: Zigbee2MQTT Devices Meta Extension + +## 🎯 Назначение + +Extension агрегирует **все данные устройств Zigbee** в единый MQTT-топик: + +``` +/bridge/devices_meta +``` + +Цель: + +* убрать разрозненные топики устройств +* получить **единый JSON по всем устройствам** +* упростить интеграцию (Dashboard, Edge, AI) + +--- + +## 🧠 Логика работы + +**Pipeline:** + +1. Загружается `state.json` (bootstrap) +2. Подписка на: + + * `bridge/devices` → маппинг `friendly_name ↔ ieee` + * live-топики устройств → реальные данные +3. Формируется структура: + + ``` + ieee → payload + ``` +4. Данные обновляются: + + * сразу при изменении + * не реже 1 раза в 30 сек + +📌 Итог: всегда актуальный snapshot всех устройств + +--- + +## 🏗 Архитектура + +### Основные структуры + +```js +devicesMeta // ieee -> данные устройства +topicToIeee // friendly_name -> ieee +ieeeToTopic // ieee -> friendly_name +pendingByTopic // буфер до получения bridge/devices +``` + +--- + +## ⚙️ Обработка событий + +### 1. `bridge/devices` + +* строит mapping +* добавляет meta (model, vendor, type) +* применяет pending данные + +--- + +### 2. Live данные устройств + +* приходят в: + +``` +/ +``` + +* мержатся в `devicesMeta` + +--- + +### 3. Availability + +``` +...//availability +``` + +→ записывается в: + +```json +availability: "online/offline" +``` + +--- + +## 🔄 Публикация + +### Условия: + +* данные изменились → publish сразу +* нет изменений → publish каждые 30 сек + +### Механизм: + +* сортировка JSON +* hash (md5) +* сравнение с предыдущим + +--- + +## 📡 Итоговый MQTT топик + +``` +g-box-XXXX/z2m/bridge/devices_meta +``` + +--- + +## 📦 Формат данных + +```json +{ + "0x00124b0012345678": { + "temperature": 25.7, + "soil_moisture": 83.9, + "battery": 89, + "linkquality": 70, + "last_seen": 1774247222154, + "friendly_name": "Sensor_1" + } +} +``` + +### Возможные поля: + +* telemetry: `temperature`, `humidity`, `soil_moisture` +* energy: `power`, `voltage`, `current` +* system: `battery`, `linkquality`, `last_seen` +* meta: `model`, `vendor`, `type` +* OTA: `update` + +--- + +## 🚀 Установка + +### 1. Создать папку + +```bash +mkdir -p /opt/zigbee2mqtt/data/external_extensions +``` + +### 2. Создать файл + +```bash +nano /opt/zigbee2mqtt/data/external_extensions/devices_meta.js +``` + +(вставить код extension) + +--- + +### 3. Права + +```bash +chown -R zigbee2mqtt:zigbee2mqtt /opt/zigbee2mqtt/data/external_extensions && chmod 755 /opt/zigbee2mqtt/data/external_extensions && chmod 644 /opt/zigbee2mqtt/data/external_extensions/devices_meta.js +``` + +--- + +### 4. Конфигурация Zigbee2MQTT + +```yaml +advanced: + last_seen: epoch + cache_state: true +``` + +--- + +### 5. Перезапуск + +```bash +systemctl restart zigbee2mqtt +``` + +--- + +## ⚡ Поведение после запуска + +* первая публикация → сразу после старта +* изменение устройства → мгновенный publish +* idle → publish раз в ~30 сек + +--- + +## 💡 Ключевая ценность + +### Было: + +* N устройств → N топиков +* сложная агрегация + +### Стало: + +* 1 топик → весь Zigbee слой +* готовый Digital State Layer + +--- + +## 🔗 Использование в архитектуре + +Идеально ложится в: + +### Edge + +* единый ingestion слой + +### Digital DNA + +* source of truth для STATE + +### Dashboard + +* один подписчик → все устройства + +### AI Layer + +* полный snapshot системы для анализа + +--- + +## ⚠️ Ограничения + +* зависит от `bridge/devices` (mapping обязателен) +* payload не фильтруется (все поля проходят) +* нет schema validation + +--- + +## 📌 Рекомендации + +* добавить whitelist/blacklist полей +* ограничить payload size +* добавить version/schema +* сделать diff publish (опционально) + +--- + +## 🧩 Вывод + +Extension превращает Zigbee2MQTT из набора топиков в: + +> **единый state-stream устройств** + +Это критический слой для: + +* Edge runtime +* Digital Twin +* AI обработки +* масштабируемой автоматизации + +Да, код нужно вынести отдельным разделом: + +## 📜 Полный код extension + +Файл: + +```bash +nano /opt/zigbee2mqtt/data/external_extensions/devices_meta.js +``` + +Код для вставки: + +```js +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +module.exports = class DevicesMeta { + constructor(zigbee, mqtt, state, publishEntityState, eventBus, settings, logger) { + this.mqtt = mqtt; + this.state = state; + this.eventBus = eventBus; + this.settings = settings || {}; + this.logger = logger || console; + + const config = this.settings || {}; + const mqttConfig = config.mqtt || {}; + + this.baseTopic = mqttConfig.base_topic || 'zigbee2mqtt'; + this.stateFile = path.join(config.data || '/opt/zigbee2mqtt/data', 'state.json'); + this.publishTopic = 'bridge/devices_meta'; + + this.devicesMeta = {}; + this.topicToIeee = {}; + this.ieeeToTopic = {}; + this.pendingByTopic = {}; + + this.lastPublishedHash = null; + this.lastPublishTs = 0; + this.pollTimer = null; + } + + start() { + this.loadInitialState(); + + this.eventBus.onMQTTMessage(this, (data) => { + this.handleMQTTMessage(data); + }); + + this.pollTimer = setInterval(() => { + this.publishIfNeeded(false); + }, 5000); + + this.publishIfNeeded(true); + + this.logger.info?.('[devices_meta] started'); + } + + stop() { + if (this.pollTimer) { + clearInterval(this.pollTimer); + this.pollTimer = null; + } + + if (this.eventBus?.removeListeners) { + this.eventBus.removeListeners(this); + } + + this.logger.info?.('[devices_meta] stopped'); + } + + loadInitialState() { + try { + if (!fs.existsSync(this.stateFile)) { + this.logger.warn?.(`[devices_meta] state file not found: ${this.stateFile}`); + return; + } + + const raw = fs.readFileSync(this.stateFile, 'utf8'); + if (!raw || raw.trim().length < 2) { + return; + } + + const json = JSON.parse(raw); + if (!this.isPlainObject(json) || Object.keys(json).length === 0) { + return; + } + + for (const [key, value] of Object.entries(json)) { + if (!this.isPlainObject(value)) { + continue; + } + + this.devicesMeta[key] = { ...value }; + } + + this.logger.info?.(`[devices_meta] bootstrap loaded: ${Object.keys(this.devicesMeta).length} devices`); + } catch (e) { + this.logger.error?.(`[devices_meta] failed to load state.json: ${e.message}`); + } + } + + handleMQTTMessage(data) { + try { + if (!data || typeof data.topic !== 'string') { + return; + } + + const topic = data.topic; + const payload = this.parseMessage(data.message); + + if (topic === `${this.baseTopic}/bridge/devices`) { + this.handleBridgeDevices(payload); + return; + } + + if (!topic.startsWith(`${this.baseTopic}/`)) { + return; + } + + const relativeTopic = topic.slice(this.baseTopic.length + 1); + + if ( + relativeTopic.startsWith('bridge/') || + relativeTopic.endsWith('/set') || + relativeTopic.includes('/set/') || + relativeTopic.endsWith('/get') || + relativeTopic.includes('/get/') + ) { + return; + } + + if (relativeTopic.endsWith('/availability')) { + this.handleAvailability(relativeTopic, payload); + return; + } + + this.handleDeviceTopic(relativeTopic, payload); + } catch (e) { + this.logger.error?.(`[devices_meta] handleMQTTMessage error: ${e.message}`); + } + } + + handleBridgeDevices(payload) { + if (!Array.isArray(payload)) { + return; + } + + let mapped = 0; + + for (const item of payload) { + if (!this.isPlainObject(item)) { + continue; + } + + const ieee = item.ieee_address; + const friendlyName = item.friendly_name; + + if (!ieee || !friendlyName) { + continue; + } + + this.topicToIeee[friendlyName] = ieee; + this.ieeeToTopic[ieee] = friendlyName; + + if (!this.devicesMeta[ieee]) { + this.devicesMeta[ieee] = {}; + } + + if (item.definition?.model) { + this.devicesMeta[ieee].model = item.definition.model; + } + + if (item.definition?.vendor) { + this.devicesMeta[ieee].vendor = item.definition.vendor; + } + + if (item.type) { + this.devicesMeta[ieee].type = item.type; + } + + this.devicesMeta[ieee].friendly_name = friendlyName; + + mapped++; + + if (this.pendingByTopic[friendlyName]) { + this.mergeDevicePayload(ieee, this.pendingByTopic[friendlyName]); + delete this.pendingByTopic[friendlyName]; + } + } + + this.logger.info?.(`[devices_meta] bridge/devices mapped: ${mapped}`); + this.publishIfNeeded(true); + } + + handleAvailability(relativeTopic, payload) { + if (!this.isPlainObject(payload)) { + return; + } + + const friendlyName = relativeTopic.replace(/\/availability$/, ''); + const ieee = this.topicToIeee[friendlyName]; + + if (!ieee) { + return; + } + + if (!this.devicesMeta[ieee]) { + this.devicesMeta[ieee] = {}; + } + + if (typeof payload.state === 'string') { + this.devicesMeta[ieee].availability = payload.state; + } + + this.publishIfNeeded(true); + } + + handleDeviceTopic(relativeTopic, payload) { + if (!this.isPlainObject(payload)) { + return; + } + + const friendlyName = relativeTopic; + const ieee = this.topicToIeee[friendlyName]; + + if (!ieee) { + this.pendingByTopic[friendlyName] = payload; + return; + } + + this.mergeDevicePayload(ieee, payload); + this.publishIfNeeded(true); + } + + mergeDevicePayload(ieee, payload) { + if (!this.devicesMeta[ieee]) { + this.devicesMeta[ieee] = {}; + } + + const current = this.devicesMeta[ieee]; + + for (const [key, value] of Object.entries(payload)) { + current[key] = value; + } + + if (this.ieeeToTopic[ieee]) { + current.friendly_name = this.ieeeToTopic[ieee]; + } + } + + publishIfNeeded(forcePeriodicCheck) { + try { + if (!this.isPlainObject(this.devicesMeta) || Object.keys(this.devicesMeta).length === 0) { + return; + } + + const normalized = JSON.stringify(this.sortedObject(this.devicesMeta)); + const hash = crypto.createHash('md5').update(normalized).digest('hex'); + const now = Date.now(); + + const changed = hash !== this.lastPublishedHash; + const periodicDue = (now - this.lastPublishTs) >= 30000; + + if (changed || (forcePeriodicCheck && periodicDue) || (!changed && periodicDue)) { + this.mqtt.publish(this.publishTopic, normalized, { retain: true }); + + this.lastPublishedHash = hash; + this.lastPublishTs = now; + + this.logger.info?.( + `[devices_meta] published: changed=${changed} periodic=${periodicDue} count=${Object.keys(this.devicesMeta).length}`, + ); + } + } catch (e) { + this.logger.error?.(`[devices_meta] publishIfNeeded error: ${e.message}`); + } + } + + parseMessage(message) { + if (message == null) { + return null; + } + + if (typeof message === 'string') { + try { + return JSON.parse(message); + } catch { + return message; + } + } + + if (Buffer.isBuffer(message)) { + const text = message.toString('utf8'); + try { + return JSON.parse(text); + } catch { + return text; + } + } + + return message; + } + + isPlainObject(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); + } + + sortedObject(value) { + if (Array.isArray(value)) { + return value.map((item) => this.sortedObject(item)); + } + + if (!this.isPlainObject(value)) { + return value; + } + + const result = {}; + + for (const key of Object.keys(value).sort()) { + result[key] = this.sortedObject(value[key]); + } + + return result; + } +}; +```