From 2ef23ce8b576afef94d1349aa6c62450cf66d044 Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Tue, 5 May 2026 20:57:35 +0400 Subject: [PATCH] z2m_extension_added_for_last_seen_option --- stage_z2m/remove_iomatex_z2m.sh | 71 +++++++ stage_z2m/stage_z2m_04_config.sh | 3 + stage_z2m/stage_z2m_lib.sh | 321 +++++++++++++++++++++++++++++++ 3 files changed, 395 insertions(+) create mode 100644 stage_z2m/remove_iomatex_z2m.sh diff --git a/stage_z2m/remove_iomatex_z2m.sh b/stage_z2m/remove_iomatex_z2m.sh new file mode 100644 index 0000000..a534794 --- /dev/null +++ b/stage_z2m/remove_iomatex_z2m.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +log() { + printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*" +} + +STATE_FILE="/opt/iomatex/Iomatex_OS/local_installer.state" + +log "Stop and disable z2m services" +systemctl stop zigbee2mqtt.service iomatex-z2m-web.service iomatex-z2m-healthcheck.timer iomatex-z2m-healthcheck.service 2>/dev/null || true +systemctl disable zigbee2mqtt.service iomatex-z2m-web.service iomatex-z2m-healthcheck.timer 2>/dev/null || true + +log "Remove systemd unit files" +rm -f /etc/systemd/system/zigbee2mqtt.service +rm -f /etc/systemd/system/iomatex-z2m-web.service +rm -f /etc/systemd/system/iomatex-z2m-healthcheck.service +rm -f /etc/systemd/system/iomatex-z2m-healthcheck.timer +systemctl daemon-reload + +log "Remove helper scripts and commands" +rm -f /usr/local/sbin/iomatex-z2m-wrapper.sh +rm -f /usr/local/sbin/iomatex-z2m-healthcheck.sh +rm -f /usr/local/lib/iomatex-z2m-web.js +rm -f /usr/local/bin/iomatex-help-z2m +rm -f /usr/local/bin/iomatex-z2m + +log "Remove Zigbee2MQTT directories" +rm -rf /opt/zigbee2mqtt +rm -rf /var/log/zigbee2mqtt +rm -rf /var/lib/zigbee2mqtt + +log "Remove z2m logs" +rm -f /var/log/iomatex-z2m-healthcheck.log +rm -f /var/log/iomatex-z2m-pnpm-install.log +rm -f /var/log/iomatex-z2m-tsc.log +rm -f /var/log/iomatex-z2m-writehash.log +rm -f /var/log/iomatex-stage-z2m-master.log +rm -f /var/log/iomatex-stage-z2m-04-config.log +rm -f /var/log/iomatex-stage-z2m-05-deps.log +rm -f /var/log/iomatex-stage-z2m-06-build.log +rm -f /var/log/iomatex-stage-z2m-07-runtime.log +rm -f /var/log/iomatex-stage-z2m-08-enable.log +rm -f /var/log/iomatex-z2m-installer.log + +log "Remove zigbee2mqtt user" +userdel -r zigbee2mqtt 2>/dev/null || true + +log "Clear only stage_z2m state" +if [ -f "$STATE_FILE" ]; then + tmp="$(mktemp)" + awk ' + $0 !~ /^STATUS_stage_z2m=/ && + $0 !~ /^LAST_STAGE=stage_z2m$/ && + $0 !~ /^LAST_INSTALLER=stage_z2m_install$/ && + $0 !~ /^LAST_INSTALLER=stage_z2m.sh$/ && + $0 !~ /^LAST_RESULT=/ + ' "$STATE_FILE" > "$tmp" + cat "$tmp" > "$STATE_FILE" + rm -f "$tmp" +fi + +log "Verification" +log "--- systemd units ---" +systemctl list-unit-files | grep -E 'zigbee2mqtt|iomatex-z2m' || true +log "--- paths ---" +ls -ld /opt/zigbee2mqtt /var/log/zigbee2mqtt /var/lib/zigbee2mqtt 2>/dev/null || true +log "--- user ---" +id zigbee2mqtt 2>/dev/null || true + +log "Done" diff --git a/stage_z2m/stage_z2m_04_config.sh b/stage_z2m/stage_z2m_04_config.sh index 6310c8b..9595ec0 100755 --- a/stage_z2m/stage_z2m_04_config.sh +++ b/stage_z2m/stage_z2m_04_config.sh @@ -18,6 +18,9 @@ main() { step "Patch configuration.yaml safely" ensure_default_config "$detected_serial" + + step "Install external extensions" + install_external_extensions } main "$@" diff --git a/stage_z2m/stage_z2m_lib.sh b/stage_z2m/stage_z2m_lib.sh index 4b88025..34ca96d 100755 --- a/stage_z2m/stage_z2m_lib.sh +++ b/stage_z2m/stage_z2m_lib.sh @@ -681,6 +681,327 @@ advanced: EOF } +install_external_extensions() { + local ext_dir="${Z2M_DATA_DIR}/external_extensions" + local ext_file="${ext_dir}/devices_meta.js" + + mkdir -p "$ext_dir" + write_if_changed "$ext_file" 0644 "$Z2M_USER" "$Z2M_GROUP" <<'EOF' +//************************************************************** +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; + } + if (friendlyName) { + 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; + } +}; +//************************************************************** +EOF + chown -R "$Z2M_USER:$Z2M_GROUP" "$ext_dir" || true + chmod 0755 "$ext_dir" + chmod 0644 "$ext_file" +} + install_base_packages() { export DEBIAN_FRONTEND=noninteractive log "RUN: dpkg --configure -a || true"