Refactor Z2M stage: move Stage_2_zigbee3mqtt to stage_z2m
This commit is contained in:
parent
3ae0472417
commit
789ebdfba2
|
|
@ -1,4 +0,0 @@
|
|||
{"id":1,"type":"Coordinator","ieeeAddr":"0xb83dfb6082900000","nwkAddr":0,"manufId":65535,"epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":80,"inClusterList":[0,25],"outClusterList":[0,1,3,4,5,6,8,768,1280,2821,64599],"clusters":{},"binds":[],"configuredReportings":[],"meta":{}}},"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{}}
|
||||
{"id":2,"type":"Router","ieeeAddr":"0x0c4314fffe52ae25","nwkAddr":47345,"manufId":4660,"manufName":"_TZ3000_okaz9tjs","powerSource":"Mains (single phase)","modelId":"TS011F","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":81,"inClusterList":[0,6,3,4,5,57345,2820,1794,64529],"outClusterList":[25],"clusters":{"genBasic":{"attributes":{"modelId":"TS011F","manufacturerName":"_TZ3000_okaz9tjs","powerSource":1,"zclVersion":2,"appVersion":100,"stackVersion":1,"hwVersion":2,"dateCode":"20210625","swBuildId":"500+TZSKT31BS103"}},"haElectricalMeasurement":{"attributes":{"acCurrentDivisor":1000,"acCurrentMultiplier":1,"rmsVoltage":231,"rmsCurrent":0,"activePower":0}},"seMetering":{"attributes":{"divisor":100,"multiplier":1,"currentSummDelivered":0}},"genOnOff":{"attributes":{"onOff":1}},"manuSpecificTuya3":{"attributes":{"powerOnBehavior":2,"switchType":2}}},"binds":[],"configuredReportings":[],"meta":{}}},"appVersion":100,"stackVersion":1,"hwVersion":2,"dateCode":"20210625","swBuildId":"500+TZSKT31BS103","zclVersion":2,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907208362}
|
||||
{"id":3,"type":"EndDevice","ieeeAddr":"0xffffb40e0606b15b","nwkAddr":18225,"manufId":5127,"manufName":"Third Reality, Inc","powerSource":"Battery","modelId":"3RSM0147Z","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":770,"inClusterList":[0,65281,1,1026,1029,1032],"outClusterList":[25],"clusters":{"genBasic":{"attributes":{"modelId":"3RSM0147Z","manufacturerName":"Third Reality, Inc","powerSource":3,"zclVersion":3,"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46"}},"msTemperatureMeasurement":{"attributes":{"measuredValue":2725}},"msRelativeHumidity":{"attributes":{"measuredValue":0}},"msSoilMoisture":{"attributes":{"measuredValue":0}},"genPowerCfg":{"attributes":{"batteryVoltage":15,"batteryPercentageRemaining":189}}},"binds":[{"cluster":1026,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1032,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1}],"configuredReportings":[{"cluster":1026,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1032,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1,"attrId":33,"minRepIntval":3600,"maxRepIntval":65000,"repChange":10}],"meta":{}}},"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46","zclVersion":3,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907081855}
|
||||
{"id":4,"type":"EndDevice","ieeeAddr":"0xffffb40e0606b17f","nwkAddr":41920,"manufId":5127,"manufName":"Third Reality, Inc","powerSource":"Battery","modelId":"3RSM0147Z","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":770,"inClusterList":[0,65281,1,1026,1029,1032],"outClusterList":[25],"clusters":{"msTemperatureMeasurement":{"attributes":{"measuredValue":2734}},"msRelativeHumidity":{"attributes":{"measuredValue":0}},"msSoilMoisture":{"attributes":{"measuredValue":0}},"genBasic":{"attributes":{"modelId":"3RSM0147Z","manufacturerName":"Third Reality, Inc","powerSource":3,"zclVersion":3,"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46"}},"genPowerCfg":{"attributes":{"batteryVoltage":15,"batteryPercentageRemaining":193}}},"binds":[{"cluster":1026,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1032,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1},{"cluster":1,"type":"endpoint","deviceIeeeAddress":"0xb83dfb6082900000","endpointID":1}],"configuredReportings":[{"cluster":1026,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1032,"attrId":0,"minRepIntval":10,"maxRepIntval":3600,"repChange":100},{"cluster":1,"attrId":33,"minRepIntval":3600,"maxRepIntval":65000,"repChange":10}],"meta":{}}},"appVersion":46,"stackVersion":2,"hwVersion":0,"swBuildId":"v1.00.46","zclVersion":3,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{"configured":332242049},"lastSeen":1771907094193}
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
# Zigbee2MQTT Installer — What This Script Does
|
||||
|
||||
## Общая задача
|
||||
Автоматически устанавливает и настраивает **Zigbee2MQTT** на edge-устройстве IOMATEX в полностью **non-interactive** режиме, готовом для работы инженерами «из коробки».
|
||||
|
||||
---
|
||||
|
||||
## Последовательность действий скрипта
|
||||
|
||||
1. **Проверяет запуск от root**
|
||||
- Завершает работу с ошибкой, если запущен не через `sudo`.
|
||||
|
||||
2. **Инициализирует логирование**
|
||||
- Создаёт файл лога установки.
|
||||
- Перенаправляет `stdout` и `stderr` в лог и консоль.
|
||||
|
||||
3. **Выводит информацию о версии установки**
|
||||
- Версия installer’а.
|
||||
- Текущее UTC-время.
|
||||
|
||||
4. **Объявляет вспомогательные функции**
|
||||
- `spinner()` — визуальный индикатор выполнения долгих операций.
|
||||
- `run_bg()` — запуск команд в фоне со spinner’ом и корректной обработкой ошибок.
|
||||
|
||||
5. **Устанавливает системные зависимости**
|
||||
- Базовые пакеты (curl, git, build-tools, udev, usbutils и т.д.).
|
||||
|
||||
6. **Устанавливает Node.js**
|
||||
- Устанавливает Node.js заданной major-версии (через NodeSource).
|
||||
- Проверяет версии `node` и `npm`.
|
||||
|
||||
7. **Включает Corepack**
|
||||
- Активирует Corepack.
|
||||
- Обеспечивает полностью non-interactive загрузку `pnpm`.
|
||||
|
||||
8. **Создаёт системного пользователя Zigbee2MQTT**
|
||||
- Пользователь `zigbee2mqtt` без shell.
|
||||
- Добавляет пользователя в группу `dialout` для доступа к USB-устройствам.
|
||||
|
||||
9. **Клонирует репозиторий Zigbee2MQTT**
|
||||
- Загружает официальный репозиторий в `/opt/zigbee2mqtt`.
|
||||
|
||||
10. **Готовит директорию данных**
|
||||
- Создаёт `/opt/zigbee2mqtt/data`.
|
||||
- Назначает владельца и права доступа.
|
||||
- (Опционально) разрешает чтение конфигурации инженеру.
|
||||
|
||||
11. **Обнаруживает Zigbee USB-dongle**
|
||||
- Ожидает появления устройства через udev.
|
||||
- Ищет dongle в следующем порядке:
|
||||
- фиксированный путь `/dev/serial/by-id/...`
|
||||
- любой `/dev/serial/by-id/*`
|
||||
- fallback: `/dev/ttyUSB*` или `/dev/ttyACM*`
|
||||
- Если dongle не найден — установка продолжается с предупреждением.
|
||||
|
||||
12. **Генерирует `configuration.yaml`**
|
||||
- MQTT-настройки.
|
||||
- Serial-порт и тип адаптера.
|
||||
- Включает Web UI на `0.0.0.0:8081` (HTTP).
|
||||
- Генерирует `network_key`.
|
||||
|
||||
13. **Устанавливает и собирает Zigbee2MQTT**
|
||||
- Выполняет `pnpm install`.
|
||||
- Выполняет `pnpm run build`.
|
||||
- Все операции выполняются non-interactive со spinner’ом.
|
||||
|
||||
14. **Создаёт systemd-сервис**
|
||||
- Конфигурирует сервис `zigbee2mqtt`.
|
||||
- Прямой запуск через `node index.js`.
|
||||
- Включает автозапуск при старте системы.
|
||||
|
||||
15. **Устанавливает helper-команду**
|
||||
- Команда `iomatex-z2m` для инженеров.
|
||||
- Показывает:
|
||||
- IP устройства.
|
||||
- ссылку на Web UI.
|
||||
- статус сервиса.
|
||||
- состояние USB и serial-портов.
|
||||
- последние ошибки.
|
||||
|
||||
16. **(Опционально) Подготавливает Warning для Cockpit**
|
||||
- Генерирует файл в `/etc/motd.d/` с предупреждением о состоянии dongle.
|
||||
- По умолчанию отключено флагом.
|
||||
|
||||
17. **Запускает сервис и выполняет быстрый self-check**
|
||||
- Проверяет, активен ли сервис.
|
||||
- Проверяет, слушается ли Web-порт.
|
||||
|
||||
18. **Выводит финальное резюме установки**
|
||||
- Web UI URL.
|
||||
- MQTT-сервер и topic.
|
||||
- Serial-порт.
|
||||
- Тип адаптера.
|
||||
- Команды для диагностики.
|
||||
|
||||
---
|
||||
|
||||
## Результат
|
||||
После выполнения скрипта:
|
||||
- Zigbee2MQTT установлен и готов к работе.
|
||||
- Web UI доступен по HTTP на порту 8081.
|
||||
- Установка не требует ручных подтверждений.
|
||||
- Инженер получает понятную диагностику и инструменты поддержки.
|
||||
|
|
@ -1,464 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
LOG="/var/log/iomatex-stage2-z2m.log"
|
||||
mkdir -p "$(dirname "$LOG")" >/dev/null 2>&1 || true
|
||||
exec > >(tee -a "$LOG") 2>&1
|
||||
|
||||
# Must run as root
|
||||
if [ "${EUID:-$(id -u)}" -ne 0 ]; then
|
||||
echo "Run as root: sudo $0"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== IOMATEX stage2.sh :: Zigbee2MQTT install/upgrade (NO DATA WIPE) v3 (hostname topic) ==="
|
||||
date -u +"UTC: %Y-%m-%d %H:%M:%S"
|
||||
|
||||
# ---------------- SETTINGS ----------------
|
||||
Z2M_USER="zigbee2mqtt"
|
||||
Z2M_DIR="/opt/zigbee2mqtt"
|
||||
Z2M_DATA_DIR="/opt/zigbee2mqtt/data"
|
||||
CFG="${Z2M_DATA_DIR}/configuration.yaml"
|
||||
|
||||
NODE_MAJOR="20"
|
||||
|
||||
# Policy: LOCAL MQTT ONLY
|
||||
MQTT_SERVER="mqtt://127.0.0.1:1883"
|
||||
HOSTNAME_SHORT="$(hostname -s)"
|
||||
MQTT_BASE_TOPIC="${HOSTNAME_SHORT}/z2m"
|
||||
|
||||
WEB_PORT_DEFAULT="8081"
|
||||
|
||||
# Preferred stable path (if present)
|
||||
SERIAL_BY_ID="/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0"
|
||||
Z2M_ADAPTER="zigate"
|
||||
|
||||
DONGLE_WAIT_SECONDS=20
|
||||
ALLOW_READ_USER="iomatex" # "" to skip
|
||||
|
||||
# Wrapper behavior (no-dongle polling)
|
||||
NO_DONGLE_SLEEP=300 # seconds (5 minutes)
|
||||
CRASH_SLEEP_MIN=10
|
||||
CRASH_SLEEP_MAX=120
|
||||
# -----------------------------------------
|
||||
|
||||
spinner() {
|
||||
local pid="$1"
|
||||
local msg="${2:-Working}"
|
||||
local spin='|/-\\'
|
||||
local i=0
|
||||
command -v tput >/dev/null 2>&1 && tput civis || true
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
i=$(( (i+1) % 4 ))
|
||||
printf "\r%s %s" "${spin:$i:1}" "$msg"
|
||||
sleep 0.15
|
||||
done
|
||||
printf "\r✓ %s\n" "$msg"
|
||||
command -v tput >/dev/null 2>&1 && tput cnorm || true
|
||||
}
|
||||
|
||||
run_bg() {
|
||||
local msg="$1"; shift
|
||||
set +e
|
||||
("$@") &
|
||||
local pid=$!
|
||||
spinner "$pid" "$msg"
|
||||
wait "$pid"
|
||||
local rc=$?
|
||||
set -e
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
echo "=== APT baseline ==="
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl gnupg git jq sudo nano \
|
||||
build-essential python3 make g++ \
|
||||
usbutils udev dos2unix
|
||||
|
||||
echo "=== Install Node.js ${NODE_MAJOR}.x (NodeSource) if needed ==="
|
||||
if ! command -v node >/dev/null 2>&1 || ! node -v | grep -qE "^v${NODE_MAJOR}\."; then
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
|
||||
| gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
|
||||
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_${NODE_MAJOR}.x nodistro main" \
|
||||
> /etc/apt/sources.list.d/nodesource.list
|
||||
apt-get update
|
||||
apt-get install -y nodejs
|
||||
fi
|
||||
node -v
|
||||
npm -v
|
||||
|
||||
echo "=== Enable pnpm via corepack (non-interactive) ==="
|
||||
export COREPACK_ENABLE_DOWNLOAD_PROMPT=0
|
||||
corepack enable || true
|
||||
pnpm -v || true
|
||||
|
||||
echo "=== Ensure user ${Z2M_USER} ==="
|
||||
if ! id -u "$Z2M_USER" >/dev/null 2>&1; then
|
||||
useradd -r -m -d "/home/${Z2M_USER}" -s /usr/sbin/nologin "$Z2M_USER"
|
||||
fi
|
||||
usermod -aG dialout "$Z2M_USER" || true
|
||||
|
||||
echo "=== Ensure data dir exists (DO NOT WIPE) ==="
|
||||
mkdir -p "$Z2M_DATA_DIR"
|
||||
chown -R "$Z2M_USER:$Z2M_USER" "$Z2M_DATA_DIR"
|
||||
chmod 750 "$Z2M_DATA_DIR"
|
||||
|
||||
if [ -n "$ALLOW_READ_USER" ] && id -u "$ALLOW_READ_USER" >/dev/null 2>&1; then
|
||||
chgrp -R "$ALLOW_READ_USER" "$Z2M_DATA_DIR" || true
|
||||
chmod -R g+rX "$Z2M_DATA_DIR" || true
|
||||
fi
|
||||
|
||||
echo "=== Install/Update Zigbee2MQTT code (keep data) ==="
|
||||
if [ -d "${Z2M_DIR}/.git" ]; then
|
||||
cd "$Z2M_DIR"
|
||||
git remote set-url origin https://github.com/Koenkk/zigbee2mqtt.git
|
||||
git fetch --depth 1 origin
|
||||
git reset --hard origin/master
|
||||
else
|
||||
rm -rf "$Z2M_DIR"
|
||||
git clone --depth 1 https://github.com/Koenkk/zigbee2mqtt.git "$Z2M_DIR"
|
||||
fi
|
||||
chown -R "$Z2M_USER:$Z2M_USER" "$Z2M_DIR"
|
||||
|
||||
echo "=== Detect serial dongle (best effort) ==="
|
||||
detect_serial() {
|
||||
local found=""
|
||||
if [ -e "$SERIAL_BY_ID" ]; then
|
||||
echo "$SERIAL_BY_ID"; return 0
|
||||
fi
|
||||
if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then
|
||||
found="$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "$found" ] && echo "$found" && return 0
|
||||
fi
|
||||
found="$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "$found" ] && echo "$found" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
DETECTED_SERIAL=""
|
||||
for _i in $(seq 1 "$DONGLE_WAIT_SECONDS"); do
|
||||
if DETECTED_SERIAL="$(detect_serial 2>/dev/null)"; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
DETECTED_SERIAL="${DETECTED_SERIAL:-$SERIAL_BY_ID}"
|
||||
echo "Serial candidate: ${DETECTED_SERIAL}"
|
||||
echo "MQTT base_topic: ${MQTT_BASE_TOPIC}"
|
||||
|
||||
echo "=== configuration.yaml handling ==="
|
||||
if [ ! -f "$CFG" ]; then
|
||||
echo "No config found -> creating new config at: $CFG"
|
||||
cat > "$CFG" <<__Z2M_CFG_NEW__
|
||||
homeassistant:
|
||||
enabled: false
|
||||
|
||||
mqtt:
|
||||
server: ${MQTT_SERVER}
|
||||
base_topic: ${MQTT_BASE_TOPIC}
|
||||
|
||||
serial:
|
||||
port: ${DETECTED_SERIAL}
|
||||
adapter: ${Z2M_ADAPTER}
|
||||
|
||||
frontend:
|
||||
enabled: true
|
||||
port: ${WEB_PORT_DEFAULT}
|
||||
host: 0.0.0.0
|
||||
|
||||
advanced:
|
||||
log_level: info
|
||||
__Z2M_CFG_NEW__
|
||||
chown "$Z2M_USER:$Z2M_USER" "$CFG"
|
||||
chmod 640 "$CFG"
|
||||
else
|
||||
echo "Config exists -> will NOT overwrite. Will patch mqtt.server/base_topic and remove mqtt auth if present."
|
||||
|
||||
# Remove mqtt auth lines if exist (user/password/username)
|
||||
sed -i -E '/^[[:space:]]*(user|username|password)[[:space:]]*:/d' "$CFG"
|
||||
|
||||
# Ensure mqtt section exists; if not, append minimal mqtt block.
|
||||
if ! grep -qE '^[[:space:]]*mqtt:[[:space:]]*$' "$CFG"; then
|
||||
cat >> "$CFG" <<__Z2M_MQTT_BLOCK__
|
||||
|
||||
mqtt:
|
||||
server: ${MQTT_SERVER}
|
||||
base_topic: ${MQTT_BASE_TOPIC}
|
||||
__Z2M_MQTT_BLOCK__
|
||||
fi
|
||||
|
||||
# Patch mqtt.server
|
||||
if grep -qE '^[[:space:]]*server:[[:space:]]*' "$CFG"; then
|
||||
awk -v new=" server: ${MQTT_SERVER}" '
|
||||
BEGIN{in=0;done=0}
|
||||
/^[[:space:]]*mqtt:[[:space:]]*$/ {in=1}
|
||||
in && !done && /^[[:space:]]*server:[[:space:]]*/ {print new; done=1; next}
|
||||
/^[[:alpha:]_]+:/ && $0 !~ /^mqtt:/ {in=0}
|
||||
{print}
|
||||
' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG"
|
||||
else
|
||||
awk -v s=" server: ${MQTT_SERVER}" '
|
||||
BEGIN{in=0;ins=0}
|
||||
/^[[:space:]]*mqtt:[[:space:]]*$/ {in=1; print; next}
|
||||
in && !ins && /^[[:space:]]*[a-zA-Z_]+:/ {print s; ins=1; in=0}
|
||||
{print}
|
||||
END{ if(in && !ins){print s} }
|
||||
' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG"
|
||||
fi
|
||||
|
||||
# Patch mqtt.base_topic
|
||||
if grep -qE '^[[:space:]]*base_topic:[[:space:]]*' "$CFG"; then
|
||||
awk -v new=" base_topic: ${MQTT_BASE_TOPIC}" '
|
||||
BEGIN{in=0;done=0}
|
||||
/^[[:space:]]*mqtt:[[:space:]]*$/ {in=1}
|
||||
in && !done && /^[[:space:]]*base_topic:[[:space:]]*/ {print new; done=1; next}
|
||||
/^[[:alpha:]_]+:/ && $0 !~ /^mqtt:/ {in=0}
|
||||
{print}
|
||||
' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG"
|
||||
else
|
||||
awk -v b=" base_topic: ${MQTT_BASE_TOPIC}" '
|
||||
BEGIN{in=0;ins=0}
|
||||
/^[[:space:]]*mqtt:[[:space:]]*$/ {in=1; print; next}
|
||||
in && !ins && /^[[:space:]]*[a-zA-Z_]+:/ {print b; ins=1; in=0}
|
||||
{print}
|
||||
END{ if(in && !ins){print b} }
|
||||
' "$CFG" > "${CFG}.tmp" && mv "${CFG}.tmp" "$CFG"
|
||||
fi
|
||||
|
||||
chown "$Z2M_USER:$Z2M_USER" "$CFG" || true
|
||||
chmod 640 "$CFG" || true
|
||||
fi
|
||||
|
||||
echo "=== pnpm install + build (non-interactive) ==="
|
||||
cd "$Z2M_DIR"
|
||||
sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-timeout 600000 >/dev/null
|
||||
sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-retries 10 >/dev/null
|
||||
run_bg "pnpm install" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm install
|
||||
run_bg "pnpm build" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm run build
|
||||
|
||||
echo "=== Dongle-aware wrapper (prevents restart storm when stick is missing) ==="
|
||||
cat > /usr/local/sbin/iomatex-z2m-wrapper.sh <<__Z2M_WRAPPER__
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
Z2M_DIR="${Z2M_DIR}"
|
||||
CFG="${CFG}"
|
||||
SERIAL_BY_ID="${SERIAL_BY_ID}"
|
||||
|
||||
NO_DONGLE_SLEEP=${NO_DONGLE_SLEEP}
|
||||
CRASH_SLEEP_MIN=${CRASH_SLEEP_MIN}
|
||||
CRASH_SLEEP_MAX=${CRASH_SLEEP_MAX}
|
||||
|
||||
log(){ echo "[\$(date -u +'%F %T UTC')] \$*"; }
|
||||
|
||||
detect_serial() {
|
||||
local found=""
|
||||
if [ -e "\$SERIAL_BY_ID" ]; then
|
||||
echo "\$SERIAL_BY_ID"; return 0
|
||||
fi
|
||||
if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then
|
||||
found="\$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "\$found" ] && echo "\$found" && return 0
|
||||
fi
|
||||
found="\$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "\$found" ] && echo "\$found" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
patch_cfg_port_if_needed() {
|
||||
local port="\$1"
|
||||
[ -f "\$CFG" ] || return 0
|
||||
awk -v new=" port: \${port}" '
|
||||
BEGIN{in=0;done=0}
|
||||
/^[[:space:]]*serial:[[:space:]]*$/ {in=1}
|
||||
in && !done && /^[[:space:]]*port:[[:space:]]*/ {print new; done=1; next}
|
||||
/^[[:alpha:]_]+:/ && \$0 !~ /^serial:/ {in=0}
|
||||
{print}
|
||||
' "\$CFG" > "\${CFG}.tmp" && mv "\${CFG}.tmp" "\$CFG"
|
||||
}
|
||||
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
log "IOMATEX Zigbee2MQTT wrapper started"
|
||||
|
||||
while true; do
|
||||
if serial="\$(detect_serial 2>/dev/null)"; then
|
||||
log "Dongle detected: \${serial}"
|
||||
patch_cfg_port_if_needed "\$serial" || true
|
||||
|
||||
log "Starting Zigbee2MQTT..."
|
||||
set +e
|
||||
/usr/bin/node "\${Z2M_DIR}/index.js"
|
||||
rc=\$?
|
||||
set -e
|
||||
log "Zigbee2MQTT exited with rc=\${rc}"
|
||||
|
||||
if ! detect_serial >/dev/null 2>&1; then
|
||||
log "Dongle not present after exit -> sleeping \${NO_DONGLE_SLEEP}s"
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
sleep "\$NO_DONGLE_SLEEP"
|
||||
else
|
||||
log "Dongle still present -> crash backoff \${crash_sleep}s"
|
||||
sleep "\$crash_sleep"
|
||||
crash_sleep=\$(( crash_sleep * 2 ))
|
||||
[ "\$crash_sleep" -gt "\$CRASH_SLEEP_MAX" ] && crash_sleep="\$CRASH_SLEEP_MAX"
|
||||
fi
|
||||
else
|
||||
log "No dongle detected -> sleeping \${NO_DONGLE_SLEEP}s"
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
sleep "\$NO_DONGLE_SLEEP"
|
||||
fi
|
||||
done
|
||||
__Z2M_WRAPPER__
|
||||
chmod 0755 /usr/local/sbin/iomatex-z2m-wrapper.sh
|
||||
chown root:root /usr/local/sbin/iomatex-z2m-wrapper.sh
|
||||
|
||||
echo "=== systemd service (wrapper-based, no restart storm) ==="
|
||||
cat > /etc/systemd/system/zigbee2mqtt.service <<__Z2M_SVC__
|
||||
[Unit]
|
||||
Description=Zigbee2MQTT (local MQTT only) with dongle-aware wrapper
|
||||
After=network-online.target mosquitto.service
|
||||
Wants=network-online.target mosquitto.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=${Z2M_USER}
|
||||
WorkingDirectory=${Z2M_DIR}
|
||||
Environment=NODE_ENV=production
|
||||
Environment=ZIGBEE2MQTT_DATA=${Z2M_DATA_DIR}
|
||||
Environment=PATH=/usr/bin:/bin
|
||||
ExecStart=/usr/local/sbin/iomatex-z2m-wrapper.sh
|
||||
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
StartLimitIntervalSec=0
|
||||
LimitNOFILE=65536
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
__Z2M_SVC__
|
||||
|
||||
echo "=== Healthcheck timer (skip when no dongle, run every 5 min) ==="
|
||||
cat > /usr/local/sbin/iomatex-z2m-healthcheck.sh <<__Z2M_HC_SH__
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
SVC="zigbee2mqtt"
|
||||
STAMP="/var/log/iomatex-z2m-healthcheck.log"
|
||||
SERIAL_BY_ID="${SERIAL_BY_ID}"
|
||||
|
||||
log(){ echo "[\$(date -u +'%F %T UTC')] \$*" >> "\$STAMP"; }
|
||||
|
||||
have_dongle() {
|
||||
[ -e "\$SERIAL_BY_ID" ] && return 0
|
||||
ls -1 /dev/serial/by-id/* >/dev/null 2>&1 && return 0
|
||||
ls -1 /dev/ttyUSB* /dev/ttyACM* >/dev/null 2>&1 && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
if ! have_dongle; then
|
||||
log "No dongle -> skip"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if systemctl is-active --quiet "\$SVC"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "Service NOT active (dongle present) -> restart"
|
||||
systemctl restart "\$SVC" || true
|
||||
sleep 2
|
||||
|
||||
if systemctl is-active --quiet "\$SVC"; then
|
||||
log "Restart OK"
|
||||
else
|
||||
log "Restart FAILED"
|
||||
fi
|
||||
__Z2M_HC_SH__
|
||||
chmod 0755 /usr/local/sbin/iomatex-z2m-healthcheck.sh
|
||||
|
||||
cat > /etc/systemd/system/iomatex-z2m-healthcheck.service <<'__Z2M_HC_SVC__'
|
||||
[Unit]
|
||||
Description=IOMATEX Zigbee2MQTT healthcheck (restart if down and dongle present)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/iomatex-z2m-healthcheck.sh
|
||||
__Z2M_HC_SVC__
|
||||
|
||||
cat > /etc/systemd/system/iomatex-z2m-healthcheck.timer <<'__Z2M_HC_TIMER__'
|
||||
[Unit]
|
||||
Description=Run IOMATEX Zigbee2MQTT healthcheck every 5 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=90
|
||||
OnUnitActiveSec=300
|
||||
AccuracySec=30
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
__Z2M_HC_TIMER__
|
||||
|
||||
echo "=== Help command: iomatex-help-z2m ==="
|
||||
cat > /usr/local/bin/iomatex-help-z2m <<'__Z2M_HELP__'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
SERVICE="zigbee2mqtt"
|
||||
CFG="/opt/zigbee2mqtt/data/configuration.yaml"
|
||||
WRAP="/usr/local/sbin/iomatex-z2m-wrapper.sh"
|
||||
|
||||
hr(){ echo "------------------------------------------------------------"; }
|
||||
h(){ echo -e "\n\033[1m$1\033[0m"; }
|
||||
|
||||
IP="$(hostname -I | awk '{print $1}')"
|
||||
HN="$(hostname -s)"
|
||||
WEB_PORT="$(awk '/^frontend:/{f=1} f&&/port:/{print $2; exit}' "$CFG" 2>/dev/null || echo "8081")"
|
||||
MQTT_SERVER="$(awk '/^mqtt:/{f=1} f&&/server:/{print $2; exit}' "$CFG" 2>/dev/null || echo "mqtt://127.0.0.1:1883")"
|
||||
BASE_TOPIC="$(awk '/^mqtt:/{f=1} f&&/base_topic:/{print $2; exit}' "$CFG" 2>/dev/null || echo "${HN}/z2m")"
|
||||
SERIAL_PORT="$(awk '/^serial:/{f=1} f&&/port:/{print $2; exit}' "$CFG" 2>/dev/null || echo "<unknown>")"
|
||||
ADAPTER="$(awk '/^serial:/{f=1} f&&/adapter:/{print $2; exit}' "$CFG" 2>/dev/null || echo "<unknown>")"
|
||||
|
||||
h "IOMATEX Zigbee2MQTT help/status"
|
||||
hr
|
||||
echo "Host : $(hostname)"
|
||||
echo "IP : ${IP}"
|
||||
echo "Config : ${CFG}"
|
||||
echo "Wrapper : ${WRAP}"
|
||||
echo "Web UI : http://${IP}:${WEB_PORT}"
|
||||
echo "MQTT : ${MQTT_SERVER}"
|
||||
echo "Base topic: ${BASE_TOPIC}"
|
||||
echo "Serial : ${SERIAL_PORT}"
|
||||
echo "Adapter : ${ADAPTER}"
|
||||
hr
|
||||
|
||||
h "Service status"
|
||||
systemctl status "${SERVICE}" --no-pager -l || true
|
||||
|
||||
h "Healthcheck timer"
|
||||
systemctl status iomatex-z2m-healthcheck.timer --no-pager -l || true
|
||||
tail -n 60 /var/log/iomatex-z2m-healthcheck.log 2>/dev/null || true
|
||||
|
||||
h "Recent errors/warnings"
|
||||
journalctl -u "${SERVICE}" -n 200 --no-pager | grep -i -E "error|fail|fatal|adapter|usb|mqtt|zigate|serial" || echo "No recent errors/warnings"
|
||||
|
||||
h "USB/Serial"
|
||||
lsusb || true
|
||||
ls -l /dev/serial/by-id/ 2>/dev/null || echo "No /dev/serial/by-id"
|
||||
ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true
|
||||
__Z2M_HELP__
|
||||
chmod +x /usr/local/bin/iomatex-help-z2m
|
||||
ln -sf /usr/local/bin/iomatex-help-z2m /usr/local/bin/iomatex-z2m
|
||||
|
||||
echo "=== Enable & start services ==="
|
||||
systemctl daemon-reload
|
||||
systemctl enable zigbee2mqtt >/dev/null 2>&1 || true
|
||||
systemctl enable iomatex-z2m-healthcheck.timer >/dev/null 2>&1 || true
|
||||
systemctl restart zigbee2mqtt || systemctl start zigbee2mqtt
|
||||
systemctl start iomatex-z2m-healthcheck.timer || true
|
||||
|
||||
echo "=== Done ==="
|
||||
echo "Data kept : ${Z2M_DATA_DIR}"
|
||||
echo "Config kept : ${CFG}"
|
||||
echo "MQTT base_topic: ${MQTT_BASE_TOPIC}"
|
||||
echo "Help : iomatex-help-z2m (or iomatex-z2m)"
|
||||
echo "Logs : journalctl -u zigbee2mqtt -f"
|
||||
echo "NOTE: Without dongle, wrapper sleeps ${NO_DONGLE_SLEEP}s between checks."
|
||||
|
|
@ -0,0 +1,926 @@
|
|||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
LOG="/var/log/iomatex-stage2-z2m.log"
|
||||
mkdir -p "$(dirname "$LOG")" >/dev/null 2>&1 || true
|
||||
exec > >(tee -a "$LOG") 2>&1
|
||||
|
||||
Z2M_USER="zigbee2mqtt"
|
||||
Z2M_GROUP="${Z2M_USER}"
|
||||
Z2M_HOME="/home/${Z2M_USER}"
|
||||
Z2M_DIR="/opt/zigbee2mqtt"
|
||||
Z2M_DATA_DIR="${Z2M_DIR}/data"
|
||||
CFG="${Z2M_DATA_DIR}/configuration.yaml"
|
||||
|
||||
NODE_MAJOR="20"
|
||||
Z2M_REPO_URL="https://github.com/Koenkk/zigbee2mqtt.git"
|
||||
|
||||
MQTT_SERVER="mqtt://127.0.0.1:1883"
|
||||
HOSTNAME_SHORT="$(hostname -s)"
|
||||
MQTT_BASE_TOPIC="${HOSTNAME_SHORT}/z2m"
|
||||
|
||||
WEB_PORT_PUBLIC="8081"
|
||||
WEB_PORT_INTERNAL="8082"
|
||||
|
||||
SERIAL_BY_ID="/dev/serial/by-id/usb-1a86_USB_Serial-if00-port0"
|
||||
Z2M_ADAPTER="zigate"
|
||||
|
||||
DONGLE_WAIT_SECONDS=20
|
||||
ALLOW_READ_USER="iomatex"
|
||||
|
||||
NO_DONGLE_SLEEP=300
|
||||
CRASH_SLEEP_MIN=10
|
||||
CRASH_SLEEP_MAX=120
|
||||
|
||||
CURRENT_STEP="bootstrap"
|
||||
|
||||
log() {
|
||||
printf '[%s] %s\n' "$(date -u +'%F %T UTC')" "$*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
log "WARN: $*"
|
||||
}
|
||||
|
||||
die() {
|
||||
log "ERROR: $*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
on_error() {
|
||||
local line="$1"
|
||||
log "ERROR: step='${CURRENT_STEP}' failed at line ${line}"
|
||||
}
|
||||
trap 'on_error "${LINENO}"' ERR
|
||||
|
||||
step() {
|
||||
CURRENT_STEP="$1"
|
||||
log "=== ${CURRENT_STEP} ==="
|
||||
}
|
||||
|
||||
require_root() {
|
||||
if [ "${EUID:-$(id -u)}" -ne 0 ]; then
|
||||
die "Run as root: sudo bash $0"
|
||||
fi
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
local cmd
|
||||
for cmd in "$@"; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || die "Missing required command: ${cmd}"
|
||||
done
|
||||
}
|
||||
|
||||
spinner() {
|
||||
local pid="$1"
|
||||
local msg="${2:-Working}"
|
||||
local spin='|/-\'
|
||||
local i=0
|
||||
|
||||
command -v tput >/dev/null 2>&1 && tput civis || true
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
i=$(( (i + 1) % 4 ))
|
||||
printf '\r%s %s' "${spin:$i:1}" "$msg"
|
||||
sleep 0.15
|
||||
done
|
||||
printf '\r%s %s\n' "✓" "$msg"
|
||||
command -v tput >/dev/null 2>&1 && tput cnorm || true
|
||||
}
|
||||
|
||||
run_bg() {
|
||||
local msg="$1"
|
||||
shift
|
||||
set +e
|
||||
("$@") &
|
||||
local pid=$!
|
||||
spinner "$pid" "$msg"
|
||||
wait "$pid"
|
||||
local rc=$?
|
||||
set -e
|
||||
return "$rc"
|
||||
}
|
||||
|
||||
ensure_parent_dir() {
|
||||
mkdir -p "$(dirname "$1")"
|
||||
}
|
||||
|
||||
write_file_atomic() {
|
||||
local target="$1"
|
||||
local mode="$2"
|
||||
local owner="$3"
|
||||
local group="$4"
|
||||
local tmp
|
||||
|
||||
ensure_parent_dir "$target"
|
||||
tmp="$(mktemp "${target}.tmp.XXXXXX")"
|
||||
cat > "$tmp"
|
||||
chown "$owner:$group" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$target"
|
||||
}
|
||||
|
||||
write_if_changed() {
|
||||
local target="$1"
|
||||
local mode="$2"
|
||||
local owner="$3"
|
||||
local group="$4"
|
||||
local tmp
|
||||
|
||||
ensure_parent_dir "$target"
|
||||
tmp="$(mktemp "${target}.tmp.XXXXXX")"
|
||||
cat > "$tmp"
|
||||
|
||||
if [ -f "$target" ] && cmp -s "$tmp" "$target"; then
|
||||
rm -f "$tmp"
|
||||
chown "$owner:$group" "$target" || true
|
||||
chmod "$mode" "$target" || true
|
||||
return 0
|
||||
fi
|
||||
|
||||
chown "$owner:$group" "$tmp"
|
||||
chmod "$mode" "$tmp"
|
||||
mv -f "$tmp" "$target"
|
||||
}
|
||||
|
||||
safe_inplace_edit() {
|
||||
local target="$1"
|
||||
local tmp
|
||||
|
||||
[ -f "$target" ] || die "File not found for edit: ${target}"
|
||||
tmp="$(mktemp "${target}.tmp.XXXXXX")"
|
||||
cat > "$tmp"
|
||||
chown --reference="$target" "$tmp" 2>/dev/null || true
|
||||
chmod --reference="$target" "$tmp" 2>/dev/null || true
|
||||
mv -f "$tmp" "$target"
|
||||
}
|
||||
|
||||
detect_serial() {
|
||||
local found=""
|
||||
|
||||
if [ -e "$SERIAL_BY_ID" ]; then
|
||||
printf '%s\n' "$SERIAL_BY_ID"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then
|
||||
found="$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "$found" ] && printf '%s\n' "$found" && return 0
|
||||
fi
|
||||
|
||||
found="$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "$found" ] && printf '%s\n' "$found" && return 0
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_for_serial_candidate() {
|
||||
local serial=""
|
||||
local _i
|
||||
|
||||
for _i in $(seq 1 "$DONGLE_WAIT_SECONDS"); do
|
||||
if serial="$(detect_serial 2>/dev/null)"; then
|
||||
printf '%s\n' "$serial"
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf '%s\n' "$SERIAL_BY_ID"
|
||||
}
|
||||
|
||||
yaml_ensure_section() {
|
||||
local file="$1"
|
||||
local section="$2"
|
||||
|
||||
if grep -qE "^[[:space:]]*${section}:[[:space:]]*$" "$file"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
printf '\n%s:\n' "$section" >> "$file"
|
||||
}
|
||||
|
||||
yaml_remove_keys_in_section() {
|
||||
local file="$1"
|
||||
local section="$2"
|
||||
shift 2
|
||||
local regex
|
||||
|
||||
regex="$(printf '%s|' "$@" | sed 's/|$//')"
|
||||
awk -v section="$section" -v regex="$regex" '
|
||||
BEGIN { in_section=0 }
|
||||
{
|
||||
if ($0 ~ "^[[:space:]]*" section ":[[:space:]]*$") {
|
||||
in_section=1
|
||||
print
|
||||
next
|
||||
}
|
||||
|
||||
if (in_section && $0 ~ "^[^[:space:]][^:]*:[[:space:]]*$") {
|
||||
in_section=0
|
||||
}
|
||||
|
||||
if (in_section && $0 ~ "^[[:space:]]*(" regex ")[[:space:]]*:") {
|
||||
next
|
||||
}
|
||||
|
||||
print
|
||||
}
|
||||
' "$file" | safe_inplace_edit "$file"
|
||||
}
|
||||
|
||||
yaml_set_key() {
|
||||
local file="$1"
|
||||
local section="$2"
|
||||
local key="$3"
|
||||
local value="$4"
|
||||
|
||||
awk -v section="$section" -v key="$key" -v value="$value" '
|
||||
BEGIN { in_section=0; section_found=0; key_found=0 }
|
||||
{
|
||||
if ($0 ~ "^[[:space:]]*" section ":[[:space:]]*$") {
|
||||
section_found=1
|
||||
in_section=1
|
||||
print
|
||||
next
|
||||
}
|
||||
|
||||
if (in_section && $0 ~ "^[^[:space:]][^:]*:[[:space:]]*$") {
|
||||
if (!key_found) {
|
||||
print " " key ": " value
|
||||
key_found=1
|
||||
}
|
||||
in_section=0
|
||||
}
|
||||
|
||||
if (in_section && $0 ~ "^[[:space:]]*" key ":[[:space:]]*") {
|
||||
print " " key ": " value
|
||||
key_found=1
|
||||
next
|
||||
}
|
||||
|
||||
print
|
||||
}
|
||||
END {
|
||||
if (!section_found) {
|
||||
print ""
|
||||
print section ":"
|
||||
print " " key ": " value
|
||||
} else if (in_section && !key_found) {
|
||||
print " " key ": " value
|
||||
}
|
||||
}
|
||||
' "$file" | safe_inplace_edit "$file"
|
||||
}
|
||||
|
||||
ensure_default_config() {
|
||||
local serial_port="$1"
|
||||
|
||||
if [ -f "$CFG" ]; then
|
||||
log "Config exists -> preserving file and patching required keys only"
|
||||
yaml_remove_keys_in_section "$CFG" mqtt user username password
|
||||
yaml_set_key "$CFG" mqtt server "$MQTT_SERVER"
|
||||
yaml_set_key "$CFG" mqtt base_topic "$MQTT_BASE_TOPIC"
|
||||
yaml_set_key "$CFG" frontend enabled "true"
|
||||
yaml_set_key "$CFG" frontend port "$WEB_PORT_INTERNAL"
|
||||
yaml_set_key "$CFG" frontend host "127.0.0.1"
|
||||
chown "$Z2M_USER:$Z2M_GROUP" "$CFG" || true
|
||||
chmod 0640 "$CFG" || true
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "No configuration.yaml found -> creating initial config"
|
||||
write_file_atomic "$CFG" 0640 "$Z2M_USER" "$Z2M_GROUP" <<EOF
|
||||
homeassistant:
|
||||
enabled: false
|
||||
|
||||
mqtt:
|
||||
server: ${MQTT_SERVER}
|
||||
base_topic: ${MQTT_BASE_TOPIC}
|
||||
|
||||
serial:
|
||||
port: ${serial_port}
|
||||
adapter: ${Z2M_ADAPTER}
|
||||
|
||||
frontend:
|
||||
enabled: true
|
||||
port: ${WEB_PORT_INTERNAL}
|
||||
host: 127.0.0.1
|
||||
|
||||
advanced:
|
||||
log_level: info
|
||||
EOF
|
||||
}
|
||||
|
||||
install_base_packages() {
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates \
|
||||
curl \
|
||||
dos2unix \
|
||||
git \
|
||||
gnupg \
|
||||
jq \
|
||||
nano \
|
||||
python3 \
|
||||
build-essential \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
sudo \
|
||||
systemd \
|
||||
usbutils \
|
||||
udev
|
||||
}
|
||||
|
||||
install_node_if_needed() {
|
||||
if command -v node >/dev/null 2>&1 && node -v | grep -qE "^v${NODE_MAJOR}\."; then
|
||||
log "Node.js ${NODE_MAJOR}.x already present: $(node -v)"
|
||||
return 0
|
||||
fi
|
||||
|
||||
install -m 0755 -d /etc/apt/keyrings
|
||||
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
|
||||
| gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
|
||||
printf 'deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_%s.x nodistro main\n' "${NODE_MAJOR}" \
|
||||
> /etc/apt/sources.list.d/nodesource.list
|
||||
apt-get update
|
||||
apt-get install -y nodejs
|
||||
}
|
||||
|
||||
ensure_z2m_user() {
|
||||
if ! id -u "$Z2M_USER" >/dev/null 2>&1; then
|
||||
useradd -r -m -d "$Z2M_HOME" -s /usr/sbin/nologin "$Z2M_USER"
|
||||
fi
|
||||
|
||||
usermod -d "$Z2M_HOME" -s /usr/sbin/nologin "$Z2M_USER" || true
|
||||
usermod -aG dialout "$Z2M_USER" || true
|
||||
}
|
||||
|
||||
ensure_directories() {
|
||||
mkdir -p "$Z2M_DIR" "$Z2M_DATA_DIR"
|
||||
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DATA_DIR"
|
||||
chmod 0750 "$Z2M_DATA_DIR"
|
||||
|
||||
if [ -n "$ALLOW_READ_USER" ] && id -u "$ALLOW_READ_USER" >/dev/null 2>&1; then
|
||||
chgrp -R "$ALLOW_READ_USER" "$Z2M_DATA_DIR" || true
|
||||
chmod -R g+rX "$Z2M_DATA_DIR" || true
|
||||
fi
|
||||
}
|
||||
|
||||
update_z2m_code() {
|
||||
local tmpdir
|
||||
|
||||
if [ -d "${Z2M_DIR}/.git" ]; then
|
||||
log "Updating existing Zigbee2MQTT git checkout"
|
||||
git -C "$Z2M_DIR" remote set-url origin "$Z2M_REPO_URL"
|
||||
git -C "$Z2M_DIR" fetch --depth 1 origin master
|
||||
git -C "$Z2M_DIR" reset --hard FETCH_HEAD
|
||||
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ -d "${Z2M_DIR}/node_modules" ] || [ -f "${Z2M_DIR}/package.json" ] || [ -d "$Z2M_DATA_DIR" ]; then
|
||||
log "Existing non-git Zigbee2MQTT directory detected -> refreshing code without touching data/"
|
||||
tmpdir="$(mktemp -d /tmp/iomatex-z2m.XXXXXX)"
|
||||
trap 'rm -rf "$tmpdir"' RETURN
|
||||
git clone --depth 1 "$Z2M_REPO_URL" "$tmpdir"
|
||||
tar -C "$tmpdir" --exclude=.git --exclude=./data -cf - . | tar -C "$Z2M_DIR" -xf -
|
||||
rm -rf "$tmpdir"
|
||||
trap - RETURN
|
||||
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "Fresh Zigbee2MQTT clone"
|
||||
git clone --depth 1 "$Z2M_REPO_URL" "$Z2M_DIR"
|
||||
mkdir -p "$Z2M_DATA_DIR"
|
||||
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
|
||||
}
|
||||
|
||||
install_dependencies_and_build() {
|
||||
cd "$Z2M_DIR"
|
||||
sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-timeout 600000 >/dev/null
|
||||
sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm config set fetch-retries 10 >/dev/null
|
||||
run_bg "pnpm install" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm install
|
||||
run_bg "pnpm build" sudo -u "$Z2M_USER" env COREPACK_ENABLE_DOWNLOAD_PROMPT=0 pnpm run build
|
||||
}
|
||||
|
||||
install_wrapper() {
|
||||
write_if_changed /usr/local/sbin/iomatex-z2m-wrapper.sh 0755 root root <<EOF
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
Z2M_DIR="${Z2M_DIR}"
|
||||
CFG="${CFG}"
|
||||
SERIAL_BY_ID="${SERIAL_BY_ID}"
|
||||
|
||||
NO_DONGLE_SLEEP=${NO_DONGLE_SLEEP}
|
||||
CRASH_SLEEP_MIN=${CRASH_SLEEP_MIN}
|
||||
CRASH_SLEEP_MAX=${CRASH_SLEEP_MAX}
|
||||
|
||||
log() {
|
||||
echo "[\$(date -u +'%F %T UTC')] \$*"
|
||||
}
|
||||
|
||||
detect_serial() {
|
||||
local found=""
|
||||
|
||||
if [ -e "\$SERIAL_BY_ID" ]; then
|
||||
echo "\$SERIAL_BY_ID"
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ -d /dev/serial/by-id ] && ls -1 /dev/serial/by-id/* >/dev/null 2>&1; then
|
||||
found="\$(ls -1 /dev/serial/by-id/* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "\$found" ] && echo "\$found" && return 0
|
||||
fi
|
||||
|
||||
found="\$(ls -1 /dev/ttyUSB* /dev/ttyACM* 2>/dev/null | head -n1 || true)"
|
||||
[ -n "\$found" ] && echo "\$found" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
patch_cfg_port_if_needed() {
|
||||
local port="\$1"
|
||||
local tmp
|
||||
|
||||
[ -f "\$CFG" ] || return 0
|
||||
|
||||
tmp="\$(mktemp "\${CFG}.tmp.XXXXXX")"
|
||||
awk -v new=" port: \${port}" '
|
||||
BEGIN { in_section=0; done=0 }
|
||||
/^[[:space:]]*serial:[[:space:]]*$/ { in_section=1 }
|
||||
in_section && !done && /^[[:space:]]*port:[[:space:]]*/ { print new; done=1; next }
|
||||
/^[^[:space:]][^:]*:[[:space:]]*$/ && \$0 !~ /^serial:/ {
|
||||
if (in_section && !done) {
|
||||
print new
|
||||
done=1
|
||||
}
|
||||
in_section=0
|
||||
}
|
||||
{ print }
|
||||
END {
|
||||
if (!done && in_section) {
|
||||
print new
|
||||
}
|
||||
}
|
||||
' "\$CFG" > "\$tmp"
|
||||
chown --reference="\$CFG" "\$tmp" 2>/dev/null || true
|
||||
chmod --reference="\$CFG" "\$tmp" 2>/dev/null || true
|
||||
mv -f "\$tmp" "\$CFG"
|
||||
}
|
||||
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
log "IOMATEX Zigbee2MQTT wrapper started"
|
||||
|
||||
while true; do
|
||||
if serial="\$(detect_serial 2>/dev/null)"; then
|
||||
log "Dongle detected: \${serial}"
|
||||
patch_cfg_port_if_needed "\$serial" || true
|
||||
|
||||
log "Starting Zigbee2MQTT..."
|
||||
set +e
|
||||
/usr/bin/node "\${Z2M_DIR}/index.js"
|
||||
rc=\$?
|
||||
set -e
|
||||
log "Zigbee2MQTT exited with rc=\${rc}"
|
||||
|
||||
if ! detect_serial >/dev/null 2>&1; then
|
||||
log "Dongle not present after exit -> sleeping \${NO_DONGLE_SLEEP}s"
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
sleep "\$NO_DONGLE_SLEEP"
|
||||
else
|
||||
log "Dongle still present -> crash backoff \${crash_sleep}s"
|
||||
sleep "\$crash_sleep"
|
||||
crash_sleep=\$(( crash_sleep * 2 ))
|
||||
[ "\$crash_sleep" -gt "\$CRASH_SLEEP_MAX" ] && crash_sleep="\$CRASH_SLEEP_MAX"
|
||||
fi
|
||||
else
|
||||
log "No dongle detected -> sleeping \${NO_DONGLE_SLEEP}s"
|
||||
crash_sleep="\$CRASH_SLEEP_MIN"
|
||||
sleep "\$NO_DONGLE_SLEEP"
|
||||
fi
|
||||
done
|
||||
EOF
|
||||
}
|
||||
|
||||
install_systemd_units() {
|
||||
write_if_changed /etc/systemd/system/zigbee2mqtt.service 0644 root root <<EOF
|
||||
[Unit]
|
||||
Description=Zigbee2MQTT (local MQTT only) with dongle-aware wrapper
|
||||
After=network-online.target mosquitto.service
|
||||
Wants=network-online.target mosquitto.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=${Z2M_USER}
|
||||
WorkingDirectory=${Z2M_DIR}
|
||||
Environment=NODE_ENV=production
|
||||
Environment=ZIGBEE2MQTT_DATA=${Z2M_DATA_DIR}
|
||||
Environment=PATH=/usr/bin:/bin
|
||||
ExecStart=/usr/local/sbin/iomatex-z2m-wrapper.sh
|
||||
Restart=on-failure
|
||||
RestartSec=30
|
||||
StartLimitIntervalSec=0
|
||||
LimitNOFILE=65536
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
write_if_changed /usr/local/sbin/iomatex-z2m-healthcheck.sh 0755 root root <<EOF
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
SVC="zigbee2mqtt"
|
||||
STAMP="/var/log/iomatex-z2m-healthcheck.log"
|
||||
SERIAL_BY_ID="${SERIAL_BY_ID}"
|
||||
|
||||
log() {
|
||||
echo "[\$(date -u +'%F %T UTC')] \$*" >> "\$STAMP"
|
||||
}
|
||||
|
||||
have_dongle() {
|
||||
[ -e "\$SERIAL_BY_ID" ] && return 0
|
||||
ls -1 /dev/serial/by-id/* >/dev/null 2>&1 && return 0
|
||||
ls -1 /dev/ttyUSB* /dev/ttyACM* >/dev/null 2>&1 && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
if ! have_dongle; then
|
||||
log "No dongle -> skip"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if systemctl is-active --quiet "\$SVC"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
log "Service NOT active (dongle present) -> restart"
|
||||
systemctl restart "\$SVC" || true
|
||||
sleep 2
|
||||
|
||||
if systemctl is-active --quiet "\$SVC"; then
|
||||
log "Restart OK"
|
||||
else
|
||||
log "Restart FAILED"
|
||||
fi
|
||||
EOF
|
||||
|
||||
write_if_changed /etc/systemd/system/iomatex-z2m-healthcheck.service 0644 root root <<'EOF'
|
||||
[Unit]
|
||||
Description=IOMATEX Zigbee2MQTT healthcheck (restart if down and dongle present)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/iomatex-z2m-healthcheck.sh
|
||||
EOF
|
||||
|
||||
write_if_changed /etc/systemd/system/iomatex-z2m-healthcheck.timer 0644 root root <<'EOF'
|
||||
[Unit]
|
||||
Description=Run IOMATEX Zigbee2MQTT healthcheck every 5 minutes
|
||||
|
||||
[Timer]
|
||||
OnBootSec=90
|
||||
OnUnitActiveSec=300
|
||||
AccuracySec=30
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
}
|
||||
|
||||
install_web_status_proxy() {
|
||||
write_if_changed /usr/local/lib/iomatex-z2m-web.js 0755 root root <<EOF
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const net = require('net');
|
||||
|
||||
const LISTEN_HOST = '0.0.0.0';
|
||||
const LISTEN_PORT = ${WEB_PORT_PUBLIC};
|
||||
const UPSTREAM_HOST = '127.0.0.1';
|
||||
const UPSTREAM_PORT = ${WEB_PORT_INTERNAL};
|
||||
const SERIAL_BY_ID = '${SERIAL_BY_ID}';
|
||||
const Z2M_DIR = '${Z2M_DIR}';
|
||||
const CFG = '${CFG}';
|
||||
|
||||
function log(message) {
|
||||
process.stdout.write('[' + new Date().toISOString() + '] ' + message + '\n');
|
||||
}
|
||||
|
||||
function isInstalled() {
|
||||
return fs.existsSync(Z2M_DIR) && fs.existsSync(CFG) && fs.existsSync(Z2M_DIR + '/index.js');
|
||||
}
|
||||
|
||||
function hasDongle() {
|
||||
if (fs.existsSync(SERIAL_BY_ID)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const byId = fs.readdirSync('/dev/serial/by-id');
|
||||
if (byId.length > 0) {
|
||||
return true;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
try {
|
||||
const devs = fs.readdirSync('/dev');
|
||||
return devs.some((name) => name.startsWith('ttyUSB') || name.startsWith('ttyACM'));
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function buildStatus() {
|
||||
if (!isInstalled()) {
|
||||
return {
|
||||
code: 503,
|
||||
title: 'IOMATEX Edge',
|
||||
state: 'Service z2m not installed'
|
||||
};
|
||||
}
|
||||
|
||||
if (!hasDongle()) {
|
||||
return {
|
||||
code: 503,
|
||||
title: 'IOMATEX Edge',
|
||||
state: 'Service z2m not configured'
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
code: 503,
|
||||
title: 'IOMATEX Edge',
|
||||
state: 'Service z2m unavailable'
|
||||
};
|
||||
}
|
||||
|
||||
function statusHtml(status) {
|
||||
return '<!doctype html>' +
|
||||
'<html lang="en"><head><meta charset="utf-8">' +
|
||||
'<meta name="viewport" content="width=device-width, initial-scale=1">' +
|
||||
'<title>IOMATEX Edge</title>' +
|
||||
'<style>' +
|
||||
':root{color-scheme:light;--bg:#f6f8fb;--card:#ffffff;--text:#1f2937;--muted:#6b7280;--line:#d8dee8;}' +
|
||||
'*{box-sizing:border-box}body{margin:0;font-family:Segoe UI,Arial,sans-serif;background:linear-gradient(180deg,#f9fbfd 0%,#eef3f9 100%);color:var(--text);min-height:100vh;display:grid;place-items:center;padding:24px}' +
|
||||
'.card{width:min(520px,100%);background:var(--card);border:1px solid var(--line);border-radius:18px;padding:32px;box-shadow:0 16px 40px rgba(15,23,42,.08)}' +
|
||||
'.eyebrow{font-size:12px;letter-spacing:.18em;text-transform:uppercase;color:var(--muted);margin-bottom:12px}' +
|
||||
'h1{margin:0 0 12px;font-size:28px;font-weight:700}.status{font-size:18px;line-height:1.5;margin:0}.hint{margin-top:14px;font-size:14px;color:var(--muted)}' +
|
||||
'</style></head><body><main class="card"><div class="eyebrow">IOMATEX Edge</div>' +
|
||||
'<h1>Zigbee2MQTT</h1><p class="status">' + status.state + '</p>' +
|
||||
'<p class="hint">Port ${WEB_PORT_PUBLIC} is served by a local status gateway.</p>' +
|
||||
'</main></body></html>';
|
||||
}
|
||||
|
||||
function sendFallback(res) {
|
||||
const status = buildStatus();
|
||||
const body = statusHtml(status);
|
||||
res.writeHead(status.code, {
|
||||
'Content-Type': 'text/html; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body)
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
function proxyHttp(req, res) {
|
||||
const options = {
|
||||
hostname: UPSTREAM_HOST,
|
||||
port: UPSTREAM_PORT,
|
||||
path: req.url,
|
||||
method: req.method,
|
||||
headers: Object.assign({}, req.headers, {
|
||||
host: UPSTREAM_HOST + ':' + UPSTREAM_PORT
|
||||
}),
|
||||
timeout: 2000
|
||||
};
|
||||
|
||||
const upstream = http.request(options, (upstreamRes) => {
|
||||
res.writeHead(upstreamRes.statusCode || 502, upstreamRes.headers);
|
||||
upstreamRes.pipe(res);
|
||||
});
|
||||
|
||||
upstream.on('timeout', () => upstream.destroy(new Error('timeout')));
|
||||
upstream.on('error', () => {
|
||||
if (!res.headersSent) {
|
||||
sendFallback(res);
|
||||
} else {
|
||||
res.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
req.pipe(upstream);
|
||||
}
|
||||
|
||||
function buildUpgradeRequest(req) {
|
||||
const lines = [];
|
||||
lines.push(req.method + ' ' + req.url + ' HTTP/' + req.httpVersion);
|
||||
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
||||
const name = req.rawHeaders[i];
|
||||
const value = req.rawHeaders[i + 1];
|
||||
if (name.toLowerCase() === 'host') {
|
||||
lines.push('Host: ' + UPSTREAM_HOST + ':' + UPSTREAM_PORT);
|
||||
} else {
|
||||
lines.push(name + ': ' + value);
|
||||
}
|
||||
}
|
||||
lines.push('');
|
||||
lines.push('');
|
||||
return lines.join('\r\n');
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
proxyHttp(req, res);
|
||||
});
|
||||
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const upstream = net.connect(UPSTREAM_PORT, UPSTREAM_HOST, () => {
|
||||
upstream.write(buildUpgradeRequest(req));
|
||||
if (head && head.length) {
|
||||
upstream.write(head);
|
||||
}
|
||||
socket.pipe(upstream).pipe(socket);
|
||||
});
|
||||
|
||||
upstream.on('error', () => {
|
||||
socket.write('HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nService z2m unavailable\r\n');
|
||||
socket.destroy();
|
||||
});
|
||||
|
||||
socket.on('error', () => {
|
||||
upstream.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(LISTEN_PORT, LISTEN_HOST, () => {
|
||||
log('IOMATEX z2m web gateway listening on ' + LISTEN_HOST + ':' + LISTEN_PORT + ' -> ' + UPSTREAM_HOST + ':' + UPSTREAM_PORT);
|
||||
});
|
||||
EOF
|
||||
|
||||
write_if_changed /etc/systemd/system/iomatex-z2m-web.service 0644 root root <<EOF
|
||||
[Unit]
|
||||
Description=IOMATEX Zigbee2MQTT web status/proxy on port ${WEB_PORT_PUBLIC}
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/node /usr/local/lib/iomatex-z2m-web.js
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
User=root
|
||||
Group=root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
}
|
||||
|
||||
install_help_command() {
|
||||
write_if_changed /usr/local/bin/iomatex-help-z2m 0755 root root <<EOF
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
SERVICE="zigbee2mqtt"
|
||||
CFG="${CFG}"
|
||||
WRAP="/usr/local/sbin/iomatex-z2m-wrapper.sh"
|
||||
WEB_PROXY="iomatex-z2m-web.service"
|
||||
|
||||
hr() { echo "------------------------------------------------------------"; }
|
||||
h() { echo -e "\n\033[1m\$1\033[0m"; }
|
||||
|
||||
IP="\$(hostname -I | awk '{print \$1}')"
|
||||
HN="\$(hostname -s)"
|
||||
WEB_PORT_PUBLIC="${WEB_PORT_PUBLIC}"
|
||||
WEB_PORT_INTERNAL="\$(awk '/^frontend:/{f=1} f&&/port:/{print \$2; exit}' "\$CFG" 2>/dev/null || echo "${WEB_PORT_INTERNAL}")"
|
||||
MQTT_SERVER="\$(awk '/^mqtt:/{f=1} f&&/server:/{print \$2; exit}' "\$CFG" 2>/dev/null || echo "${MQTT_SERVER}")"
|
||||
BASE_TOPIC="\$(awk '/^mqtt:/{f=1} f&&/base_topic:/{print \$2; exit}' "\$CFG" 2>/dev/null || echo "\${HN}/z2m")"
|
||||
SERIAL_PORT="\$(awk '/^serial:/{f=1} f&&/port:/{print \$2; exit}' "\$CFG" 2>/dev/null || echo "<unknown>")"
|
||||
ADAPTER="\$(awk '/^serial:/{f=1} f&&/adapter:/{print \$2; exit}' "\$CFG" 2>/dev/null || echo "<unknown>")"
|
||||
|
||||
h "IOMATEX Zigbee2MQTT help/status"
|
||||
hr
|
||||
echo "Host : \$(hostname)"
|
||||
echo "IP : \${IP}"
|
||||
echo "Config : \${CFG}"
|
||||
echo "Wrapper : \${WRAP}"
|
||||
echo "Web UI : http://\${IP}:\${WEB_PORT_PUBLIC}"
|
||||
echo "Frontend inner: http://127.0.0.1:\${WEB_PORT_INTERNAL}"
|
||||
echo "MQTT : \${MQTT_SERVER}"
|
||||
echo "Base topic : \${BASE_TOPIC}"
|
||||
echo "Serial : \${SERIAL_PORT}"
|
||||
echo "Adapter : \${ADAPTER}"
|
||||
hr
|
||||
|
||||
h "Service status"
|
||||
systemctl status "\${SERVICE}" --no-pager -l || true
|
||||
|
||||
h "Web status/proxy"
|
||||
systemctl status "\${WEB_PROXY}" --no-pager -l || true
|
||||
|
||||
h "Healthcheck timer"
|
||||
systemctl status iomatex-z2m-healthcheck.timer --no-pager -l || true
|
||||
tail -n 60 /var/log/iomatex-z2m-healthcheck.log 2>/dev/null || true
|
||||
|
||||
h "Recent errors/warnings"
|
||||
journalctl -u "\${SERVICE}" -n 200 --no-pager | grep -i -E "error|fail|fatal|adapter|usb|mqtt|zigate|serial" || echo "No recent errors/warnings"
|
||||
|
||||
h "USB/Serial"
|
||||
lsusb || true
|
||||
ls -l /dev/serial/by-id/ 2>/dev/null || echo "No /dev/serial/by-id"
|
||||
ls -l /dev/ttyUSB* /dev/ttyACM* 2>/dev/null || true
|
||||
EOF
|
||||
|
||||
ln -sf /usr/local/bin/iomatex-help-z2m /usr/local/bin/iomatex-z2m
|
||||
}
|
||||
|
||||
enable_and_restart_services() {
|
||||
systemctl daemon-reload
|
||||
systemctl enable zigbee2mqtt >/dev/null 2>&1 || true
|
||||
systemctl enable iomatex-z2m-healthcheck.timer >/dev/null 2>&1 || true
|
||||
systemctl enable iomatex-z2m-web.service >/dev/null 2>&1 || true
|
||||
systemctl restart zigbee2mqtt || systemctl start zigbee2mqtt
|
||||
systemctl restart iomatex-z2m-web.service || systemctl start iomatex-z2m-web.service
|
||||
systemctl start iomatex-z2m-healthcheck.timer || true
|
||||
}
|
||||
|
||||
print_summary() {
|
||||
cat <<EOF
|
||||
=== Done ===
|
||||
Data kept : ${Z2M_DATA_DIR}
|
||||
Config kept : ${CFG}
|
||||
MQTT server : ${MQTT_SERVER}
|
||||
MQTT base_topic : ${MQTT_BASE_TOPIC}
|
||||
Public Web UI : http://<device-ip>:${WEB_PORT_PUBLIC}
|
||||
Internal frontend : http://127.0.0.1:${WEB_PORT_INTERNAL}
|
||||
Help : iomatex-help-z2m (or iomatex-z2m)
|
||||
Logs : journalctl -u zigbee2mqtt -f
|
||||
Web gateway logs : journalctl -u iomatex-z2m-web -f
|
||||
Critical state files : ${Z2M_DATA_DIR}/configuration.yaml, ${Z2M_DATA_DIR}/database.db, ${Z2M_DATA_DIR}/coordinator_backup.json, ${Z2M_DATA_DIR}/state.json
|
||||
NOTE : Without dongle, wrapper sleeps ${NO_DONGLE_SLEEP}s between checks.
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
require_root
|
||||
require_cmd apt-get awk cmp hostname id install mktemp mv sed systemctl tar tee
|
||||
|
||||
log "=== IOMATEX stage2.sh :: Zigbee2MQTT install/upgrade (NO DATA WIPE) v4 (idempotent + web fallback) ==="
|
||||
date -u +"UTC: %Y-%m-%d %H:%M:%S"
|
||||
|
||||
step "Preflight"
|
||||
install_base_packages
|
||||
require_cmd curl git gpg jq python3
|
||||
|
||||
step "Install Node.js ${NODE_MAJOR}.x if needed"
|
||||
install_node_if_needed
|
||||
require_cmd node npm
|
||||
node -v
|
||||
npm -v
|
||||
|
||||
step "Enable pnpm via corepack"
|
||||
export COREPACK_ENABLE_DOWNLOAD_PROMPT=0
|
||||
corepack enable || true
|
||||
pnpm -v || true
|
||||
|
||||
step "Ensure system user and directories"
|
||||
ensure_z2m_user
|
||||
ensure_directories
|
||||
|
||||
step "Install or update Zigbee2MQTT code"
|
||||
update_z2m_code
|
||||
|
||||
step "Detect serial dongle"
|
||||
DETECTED_SERIAL="$(wait_for_serial_candidate)"
|
||||
log "Serial candidate: ${DETECTED_SERIAL}"
|
||||
log "MQTT base_topic: ${MQTT_BASE_TOPIC}"
|
||||
|
||||
step "Patch configuration.yaml safely"
|
||||
ensure_default_config "$DETECTED_SERIAL"
|
||||
|
||||
step "Install dependencies and build Zigbee2MQTT"
|
||||
install_dependencies_and_build
|
||||
|
||||
step "Install wrapper and systemd units"
|
||||
install_wrapper
|
||||
install_systemd_units
|
||||
|
||||
step "Install web fallback/proxy on port ${WEB_PORT_PUBLIC}"
|
||||
install_web_status_proxy
|
||||
|
||||
step "Install help command"
|
||||
install_help_command
|
||||
|
||||
step "Enable and restart services"
|
||||
enable_and_restart_services
|
||||
|
||||
print_summary
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Loading…
Reference in New Issue