Merge branch 'refactor-stage-reverse-tunnels'
This commit is contained in:
commit
b4a99df5ef
|
|
@ -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."
|
|
||||||
|
|
@ -1,217 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# =============================================================
|
|
||||||
# IOMATEX Stage4 — Reverse SSH Tunnels (production)
|
|
||||||
# - 3 independent tunnels: Cockpit / Zigbee2MQTT / WebUI
|
|
||||||
# - services ENABLED but NOT started (start after reboot)
|
|
||||||
# - autossh + systemd restart for resilience
|
|
||||||
# - ServerAlive keepalive for network/IP changes
|
|
||||||
# - prints one-line VPS command (user + key + fail2ban allow)
|
|
||||||
# =============================================================
|
|
||||||
|
|
||||||
set -euo pipefail
|
|
||||||
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
|
||||||
|
|
||||||
LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log"
|
|
||||||
mkdir -p /var/log >/dev/null 2>&1 || true
|
|
||||||
touch "$LOG" >/dev/null 2>&1 || true
|
|
||||||
exec > >(tee -a "$LOG") 2>&1
|
|
||||||
|
|
||||||
log(){ echo "[$(date -u +'%F %T UTC')] $*"; }
|
|
||||||
|
|
||||||
need_root(){
|
|
||||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
|
||||||
echo "Run as root: sudo bash $0"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
EDGE_USER="${EDGE_USER:-iomatex}"
|
|
||||||
|
|
||||||
VPS_HOST="${VPS_HOST:-65.109.116.180}"
|
|
||||||
VPS_PORT="${VPS_PORT:-22}"
|
|
||||||
|
|
||||||
COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}"
|
|
||||||
Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}"
|
|
||||||
WEBUI_LOCAL_PORT="${WEBUI_LOCAL_PORT:-8099}"
|
|
||||||
|
|
||||||
PORT_BASE="${PORT_BASE:-20000}"
|
|
||||||
PORT_SLOTS="${PORT_SLOTS:-4000}"
|
|
||||||
|
|
||||||
ensure_autossh(){
|
|
||||||
if ! command -v autossh >/dev/null 2>&1; then
|
|
||||||
log "Installing autossh..."
|
|
||||||
apt-get update -y
|
|
||||||
apt-get install -y autossh
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
compute_ports(){
|
|
||||||
local hn="$1"
|
|
||||||
local crc slot cockpit z2m webui
|
|
||||||
crc="$(cksum <<<"$hn" | awk '{print $1}')"
|
|
||||||
slot="$(( crc % PORT_SLOTS ))"
|
|
||||||
cockpit="$(( PORT_BASE + slot*3 + 0 ))"
|
|
||||||
z2m="$(( PORT_BASE + slot*3 + 1 ))"
|
|
||||||
webui="$(( PORT_BASE + slot*3 + 2 ))"
|
|
||||||
echo "$cockpit $z2m $webui"
|
|
||||||
}
|
|
||||||
|
|
||||||
ensure_key(){
|
|
||||||
# IMPORTANT:
|
|
||||||
# - stdout: ONLY "edge_home|key|keypub"
|
|
||||||
# - any info/errors: stderr
|
|
||||||
|
|
||||||
local hn="$1"
|
|
||||||
local edge_home ssh_dir key keypub
|
|
||||||
|
|
||||||
if ! id -u "$EDGE_USER" >/dev/null 2>&1; then
|
|
||||||
echo "ERROR: EDGE user '$EDGE_USER' not found." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
edge_home="$(getent passwd "$EDGE_USER" | cut -d: -f6)"
|
|
||||||
if [[ -z "${edge_home:-}" ]]; then
|
|
||||||
echo "ERROR: cannot resolve home for user '$EDGE_USER'." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
ssh_dir="${edge_home}/.ssh"
|
|
||||||
key="${ssh_dir}/iomatex-${hn}"
|
|
||||||
keypub="${key}.pub"
|
|
||||||
|
|
||||||
install -d -m 700 -o "$EDGE_USER" -g "$EDGE_USER" "$ssh_dir"
|
|
||||||
|
|
||||||
if [[ ! -f "$key" || ! -f "$keypub" ]]; then
|
|
||||||
echo "Generating SSH key for ${EDGE_USER}..." >&2
|
|
||||||
runuser -u "$EDGE_USER" -- ssh-keygen -t ed25519 -N "" -f "$key" -C "$hn" >/dev/null
|
|
||||||
else
|
|
||||||
echo "SSH key already exists: $key" >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
chmod 600 "$key" 2>/dev/null || true
|
|
||||||
chmod 644 "$keypub" 2>/dev/null || true
|
|
||||||
chown "$EDGE_USER:$EDGE_USER" "$key" "$keypub" 2>/dev/null || true
|
|
||||||
|
|
||||||
runuser -u "$EDGE_USER" -- bash -lc "touch '$ssh_dir/known_hosts' && chmod 600 '$ssh_dir/known_hosts'" >/dev/null 2>&1 || true
|
|
||||||
|
|
||||||
echo "$edge_home|$key|$keypub"
|
|
||||||
}
|
|
||||||
|
|
||||||
write_wrapper(){
|
|
||||||
local name="$1"
|
|
||||||
local local_port="$2"
|
|
||||||
local remote_port="$3"
|
|
||||||
local vps_user="$4"
|
|
||||||
local key="$5"
|
|
||||||
local edge_home="$6"
|
|
||||||
local wrapper="/usr/local/sbin/iomatex-rt-${name}.sh"
|
|
||||||
|
|
||||||
cat > "$wrapper" <<SCRIPT
|
|
||||||
#!/usr/bin/env bash
|
|
||||||
exec autossh -M 0 -N \\
|
|
||||||
-o ServerAliveInterval=30 \\
|
|
||||||
-o ServerAliveCountMax=3 \\
|
|
||||||
-o ExitOnForwardFailure=yes \\
|
|
||||||
-o StrictHostKeyChecking=accept-new \\
|
|
||||||
-o UserKnownHostsFile=${edge_home}/.ssh/known_hosts \\
|
|
||||||
-i ${key} \\
|
|
||||||
-p ${VPS_PORT} \\
|
|
||||||
-R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\
|
|
||||||
${vps_user}@${VPS_HOST}
|
|
||||||
SCRIPT
|
|
||||||
|
|
||||||
chmod +x "$wrapper"
|
|
||||||
}
|
|
||||||
|
|
||||||
write_unit(){
|
|
||||||
local name="$1"
|
|
||||||
cat > "/etc/systemd/system/iomatex-rt-${name}.service" <<UNIT
|
|
||||||
[Unit]
|
|
||||||
Description=IOMATEX Reverse Tunnel (${name}) %H
|
|
||||||
After=network-online.target
|
|
||||||
Wants=network-online.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
User=${EDGE_USER}
|
|
||||||
Environment=AUTOSSH_GATETIME=0
|
|
||||||
Environment=AUTOSSH_POLL=30
|
|
||||||
ExecStart=/usr/local/sbin/iomatex-rt-${name}.sh
|
|
||||||
Restart=always
|
|
||||||
RestartSec=15
|
|
||||||
StartLimitIntervalSec=0
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
UNIT
|
|
||||||
}
|
|
||||||
|
|
||||||
main(){
|
|
||||||
need_root
|
|
||||||
ensure_autossh
|
|
||||||
|
|
||||||
local hn vps_user cockpit_r z2m_r webui_r
|
|
||||||
local edge_home key keypub publine
|
|
||||||
|
|
||||||
hn="$(hostname)"
|
|
||||||
vps_user="tunnel_${hn}"
|
|
||||||
|
|
||||||
read cockpit_r z2m_r webui_r <<< "$(compute_ports "$hn")"
|
|
||||||
|
|
||||||
IFS='|' read -r edge_home key keypub < <(ensure_key "$hn" | tail -n 1)
|
|
||||||
|
|
||||||
if [[ -z "${keypub:-}" || ! -f "$keypub" ]]; then
|
|
||||||
log "ERROR: keypub not found: '${keypub:-}'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
publine="$(cat "$keypub")"
|
|
||||||
|
|
||||||
write_wrapper cockpit "$COCKPIT_LOCAL_PORT" "$cockpit_r" "$vps_user" "$key" "$edge_home"
|
|
||||||
write_wrapper z2m "$Z2M_LOCAL_PORT" "$z2m_r" "$vps_user" "$key" "$edge_home"
|
|
||||||
write_wrapper webui "$WEBUI_LOCAL_PORT" "$webui_r" "$vps_user" "$key" "$edge_home"
|
|
||||||
|
|
||||||
write_unit cockpit
|
|
||||||
write_unit z2m
|
|
||||||
write_unit webui
|
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
|
|
||||||
# enable but DO NOT start (start after reboot)
|
|
||||||
systemctl enable iomatex-rt-cockpit.service
|
|
||||||
systemctl enable iomatex-rt-z2m.service
|
|
||||||
systemctl enable iomatex-rt-webui.service
|
|
||||||
|
|
||||||
local EDGE_IP
|
|
||||||
EDGE_IP="$(curl -s https://api.ipify.org || true)"
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "============================================================"
|
|
||||||
echo "EDGE READY (TUNNELS START AFTER REBOOT)"
|
|
||||||
echo
|
|
||||||
echo "HOSTNAME: ${hn}"
|
|
||||||
echo "EDGE IP: ${EDGE_IP}"
|
|
||||||
echo
|
|
||||||
echo "VPS HOST: ${VPS_HOST}:${VPS_PORT}"
|
|
||||||
echo "VPS USER: ${vps_user}"
|
|
||||||
echo
|
|
||||||
echo "VPS PORTS:"
|
|
||||||
echo "Cockpit=${cockpit_r}"
|
|
||||||
echo "Z2M=${z2m_r}"
|
|
||||||
echo "WebUI=${webui_r}"
|
|
||||||
echo
|
|
||||||
echo "SSH PUBLIC KEY:"
|
|
||||||
echo "$publine"
|
|
||||||
echo
|
|
||||||
echo "RUN THIS ON VPS:"
|
|
||||||
echo
|
|
||||||
echo "EDGE_HOSTNAME='${hn}'; EDGE_IP='${EDGE_IP}'; EDGE_PUBKEY_LINE='${publine}'; COCKPIT_REMOTE_PORT='${cockpit_r}'; Z2M_REMOTE_PORT='${z2m_r}'; WEBUI_REMOTE_PORT='${webui_r}'; VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
|
|
||||||
echo
|
|
||||||
echo "IMPORTANT:"
|
|
||||||
echo "1. Run the VPS command above"
|
|
||||||
echo "2. Reboot EDGE"
|
|
||||||
echo "3. Reverse tunnels will start automatically"
|
|
||||||
echo "============================================================"
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
|
|
@ -0,0 +1,286 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# =============================================================
|
||||||
|
# IOMATEX Stage4 Reverse SSH Tunnels (production)
|
||||||
|
# - 3 independent tunnels: Cockpit / Zigbee2MQTT / WebUI
|
||||||
|
# - services are ENABLED but NOT started
|
||||||
|
# - autossh + systemd restart for resilience
|
||||||
|
# - ServerAlive keepalive for network/IP changes
|
||||||
|
# - prints one-line VPS bootstrap command
|
||||||
|
# =============================================================
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log"
|
||||||
|
|
||||||
|
EDGE_USER="${EDGE_USER:-iomatex}"
|
||||||
|
|
||||||
|
VPS_HOST="${VPS_HOST:-65.109.116.180}"
|
||||||
|
VPS_PORT="${VPS_PORT:-22}"
|
||||||
|
|
||||||
|
COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}"
|
||||||
|
Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}"
|
||||||
|
WEBUI_LOCAL_PORT="${WEBUI_LOCAL_PORT:-8099}"
|
||||||
|
|
||||||
|
PORT_BASE="${PORT_BASE:-20000}"
|
||||||
|
PORT_SLOTS="${PORT_SLOTS:-4000}"
|
||||||
|
|
||||||
|
WRAPPER_DIR="/usr/local/sbin"
|
||||||
|
SYSTEMD_DIR="/etc/systemd/system"
|
||||||
|
|
||||||
|
mkdir -p /var/log >/dev/null 2>&1 || true
|
||||||
|
touch "$LOG" >/dev/null 2>&1 || true
|
||||||
|
exec > >(tee -a "$LOG") 2>&1
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "[$(date -u +'%F %T UTC')] $*"
|
||||||
|
}
|
||||||
|
|
||||||
|
die() {
|
||||||
|
log "ERROR: $*"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
require_root() {
|
||||||
|
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||||
|
echo "Run as root: sudo bash $0" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
require_cmd() {
|
||||||
|
local cmd="$1"
|
||||||
|
command -v "$cmd" >/dev/null 2>&1 || die "Required command not found: $cmd"
|
||||||
|
}
|
||||||
|
|
||||||
|
preflight_checks() {
|
||||||
|
require_cmd id
|
||||||
|
require_cmd cksum
|
||||||
|
require_cmd awk
|
||||||
|
require_cmd getent
|
||||||
|
require_cmd runuser
|
||||||
|
require_cmd ssh-keygen
|
||||||
|
require_cmd systemctl
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_autossh_installed() {
|
||||||
|
if command -v autossh >/dev/null 2>&1; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
require_cmd apt-get
|
||||||
|
log "Installing autossh..."
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y autossh
|
||||||
|
}
|
||||||
|
|
||||||
|
compute_ports() {
|
||||||
|
local hostname_value="$1"
|
||||||
|
local crc slot cockpit_port z2m_port webui_port
|
||||||
|
|
||||||
|
crc="$(cksum <<<"$hostname_value" | awk '{print $1}')"
|
||||||
|
slot="$(( crc % PORT_SLOTS ))"
|
||||||
|
cockpit_port="$(( PORT_BASE + slot * 3 + 0 ))"
|
||||||
|
z2m_port="$(( PORT_BASE + slot * 3 + 1 ))"
|
||||||
|
webui_port="$(( PORT_BASE + slot * 3 + 2 ))"
|
||||||
|
|
||||||
|
echo "$cockpit_port $z2m_port $webui_port"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_key() {
|
||||||
|
# IMPORTANT:
|
||||||
|
# - stdout: ONLY "edge_home|key|keypub"
|
||||||
|
# - informational messages: stderr only
|
||||||
|
local hostname_value="$1"
|
||||||
|
local edge_home ssh_dir key keypub
|
||||||
|
|
||||||
|
if ! id -u "$EDGE_USER" >/dev/null 2>&1; then
|
||||||
|
echo "ERROR: EDGE user '$EDGE_USER' not found." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
edge_home="$(getent passwd "$EDGE_USER" | cut -d: -f6)"
|
||||||
|
if [[ -z "${edge_home:-}" ]]; then
|
||||||
|
echo "ERROR: cannot resolve home for user '$EDGE_USER'." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
ssh_dir="${edge_home}/.ssh"
|
||||||
|
key="${ssh_dir}/iomatex-${hostname_value}"
|
||||||
|
keypub="${key}.pub"
|
||||||
|
|
||||||
|
install -d -m 700 -o "$EDGE_USER" -g "$EDGE_USER" "$ssh_dir"
|
||||||
|
|
||||||
|
if [[ ! -f "$key" || ! -f "$keypub" ]]; then
|
||||||
|
echo "Generating SSH key for ${EDGE_USER}..." >&2
|
||||||
|
runuser -u "$EDGE_USER" -- ssh-keygen -t ed25519 -N "" -f "$key" -C "$hostname_value" >/dev/null
|
||||||
|
else
|
||||||
|
echo "SSH key already exists: $key" >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
chmod 600 "$key" 2>/dev/null || true
|
||||||
|
chmod 644 "$keypub" 2>/dev/null || true
|
||||||
|
chown "$EDGE_USER:$EDGE_USER" "$key" "$keypub" 2>/dev/null || true
|
||||||
|
runuser -u "$EDGE_USER" -- bash -lc "touch '$ssh_dir/known_hosts' && chmod 600 '$ssh_dir/known_hosts'" >/dev/null 2>&1 || true
|
||||||
|
|
||||||
|
echo "$edge_home|$key|$keypub"
|
||||||
|
}
|
||||||
|
|
||||||
|
write_wrapper() {
|
||||||
|
local name="$1"
|
||||||
|
local local_port="$2"
|
||||||
|
local remote_port="$3"
|
||||||
|
local vps_user="$4"
|
||||||
|
local key="$5"
|
||||||
|
local edge_home="$6"
|
||||||
|
local wrapper_path="${WRAPPER_DIR}/iomatex-rt-${name}.sh"
|
||||||
|
|
||||||
|
cat >"$wrapper_path" <<EOF
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
exec autossh -M 0 -N \\
|
||||||
|
-o ServerAliveInterval=30 \\
|
||||||
|
-o ServerAliveCountMax=3 \\
|
||||||
|
-o ExitOnForwardFailure=yes \\
|
||||||
|
-o StrictHostKeyChecking=accept-new \\
|
||||||
|
-o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\
|
||||||
|
-i "${key}" \\
|
||||||
|
-p "${VPS_PORT}" \\
|
||||||
|
-R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\
|
||||||
|
"${vps_user}@${VPS_HOST}"
|
||||||
|
EOF
|
||||||
|
|
||||||
|
chmod 0755 "$wrapper_path"
|
||||||
|
}
|
||||||
|
|
||||||
|
write_unit() {
|
||||||
|
local name="$1"
|
||||||
|
local unit_path="${SYSTEMD_DIR}/iomatex-rt-${name}.service"
|
||||||
|
|
||||||
|
cat >"$unit_path" <<EOF
|
||||||
|
[Unit]
|
||||||
|
Description=IOMATEX Reverse Tunnel (${name}) %H
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=${EDGE_USER}
|
||||||
|
Environment=AUTOSSH_GATETIME=0
|
||||||
|
Environment=AUTOSSH_POLL=30
|
||||||
|
ExecStart=${WRAPPER_DIR}/iomatex-rt-${name}.sh
|
||||||
|
Restart=always
|
||||||
|
RestartSec=15
|
||||||
|
StartLimitIntervalSec=0
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
chmod 0644 "$unit_path"
|
||||||
|
}
|
||||||
|
|
||||||
|
enable_units_only() {
|
||||||
|
systemctl enable iomatex-rt-cockpit.service
|
||||||
|
systemctl enable iomatex-rt-z2m.service
|
||||||
|
systemctl enable iomatex-rt-webui.service
|
||||||
|
}
|
||||||
|
|
||||||
|
fetch_public_ip() {
|
||||||
|
if ! command -v curl >/dev/null 2>&1; then
|
||||||
|
echo ""
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
curl -fsS --max-time 5 https://api.ipify.org 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
print_summary() {
|
||||||
|
local hostname_value="$1"
|
||||||
|
local edge_ip="$2"
|
||||||
|
local vps_user="$3"
|
||||||
|
local cockpit_remote_port="$4"
|
||||||
|
local z2m_remote_port="$5"
|
||||||
|
local webui_remote_port="$6"
|
||||||
|
local public_key_line="$7"
|
||||||
|
local vps_bootstrap_cmd="$8"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "============================================================"
|
||||||
|
echo "EDGE READY (TUNNELS START AFTER REBOOT)"
|
||||||
|
echo
|
||||||
|
echo "HOSTNAME: ${hostname_value}"
|
||||||
|
echo "EDGE IP: ${edge_ip}"
|
||||||
|
echo
|
||||||
|
echo "VPS HOST: ${VPS_HOST}:${VPS_PORT}"
|
||||||
|
echo "VPS USER: ${vps_user}"
|
||||||
|
echo
|
||||||
|
echo "VPS PORTS:"
|
||||||
|
echo "Cockpit=${cockpit_remote_port}"
|
||||||
|
echo "Z2M=${z2m_remote_port}"
|
||||||
|
echo "WebUI=${webui_remote_port}"
|
||||||
|
echo
|
||||||
|
echo "SSH PUBLIC KEY:"
|
||||||
|
echo "$public_key_line"
|
||||||
|
echo
|
||||||
|
echo "RUN THIS ON VPS:"
|
||||||
|
echo
|
||||||
|
echo "$vps_bootstrap_cmd"
|
||||||
|
echo
|
||||||
|
echo "IMPORTANT:"
|
||||||
|
echo "1. Run the VPS command above"
|
||||||
|
echo "2. Reboot EDGE"
|
||||||
|
echo "3. Reverse tunnels will start automatically"
|
||||||
|
echo "============================================================"
|
||||||
|
}
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local hostname_value vps_user
|
||||||
|
local cockpit_remote_port z2m_remote_port webui_remote_port
|
||||||
|
local edge_home key keypub public_key_line edge_ip
|
||||||
|
local vps_bootstrap_cmd
|
||||||
|
|
||||||
|
require_root
|
||||||
|
preflight_checks
|
||||||
|
ensure_autossh_installed
|
||||||
|
|
||||||
|
hostname_value="$(hostname)"
|
||||||
|
vps_user="tunnel_${hostname_value}"
|
||||||
|
|
||||||
|
read -r cockpit_remote_port z2m_remote_port webui_remote_port <<<"$(compute_ports "$hostname_value")"
|
||||||
|
IFS='|' read -r edge_home key keypub < <(ensure_key "$hostname_value" | tail -n 1)
|
||||||
|
|
||||||
|
[[ -n "${edge_home:-}" ]] || die "edge home is empty"
|
||||||
|
[[ -n "${key:-}" ]] || die "key path is empty"
|
||||||
|
[[ -n "${keypub:-}" ]] || die "keypub path is empty"
|
||||||
|
[[ -f "$key" ]] || die "private key not found: $key"
|
||||||
|
[[ -f "$keypub" ]] || die "keypub not found: $keypub"
|
||||||
|
|
||||||
|
public_key_line="$(<"$keypub")"
|
||||||
|
|
||||||
|
write_wrapper cockpit "$COCKPIT_LOCAL_PORT" "$cockpit_remote_port" "$vps_user" "$key" "$edge_home"
|
||||||
|
write_wrapper z2m "$Z2M_LOCAL_PORT" "$z2m_remote_port" "$vps_user" "$key" "$edge_home"
|
||||||
|
write_wrapper webui "$WEBUI_LOCAL_PORT" "$webui_remote_port" "$vps_user" "$key" "$edge_home"
|
||||||
|
|
||||||
|
write_unit cockpit
|
||||||
|
write_unit z2m
|
||||||
|
write_unit webui
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
|
|
||||||
|
# Enable but DO NOT start. Services should come up after reboot.
|
||||||
|
enable_units_only
|
||||||
|
|
||||||
|
edge_ip="$(fetch_public_ip)"
|
||||||
|
|
||||||
|
vps_bootstrap_cmd="EDGE_HOSTNAME='${hostname_value}'; EDGE_IP='${edge_ip}'; EDGE_PUBKEY_LINE='${public_key_line}'; COCKPIT_REMOTE_PORT='${cockpit_remote_port}'; Z2M_REMOTE_PORT='${z2m_remote_port}'; WEBUI_REMOTE_PORT='${webui_remote_port}'; VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\""
|
||||||
|
|
||||||
|
print_summary \
|
||||||
|
"$hostname_value" \
|
||||||
|
"$edge_ip" \
|
||||||
|
"$vps_user" \
|
||||||
|
"$cockpit_remote_port" \
|
||||||
|
"$z2m_remote_port" \
|
||||||
|
"$webui_remote_port" \
|
||||||
|
"$public_key_line" \
|
||||||
|
"$vps_bootstrap_cmd"
|
||||||
|
}
|
||||||
|
|
||||||
|
main "$@"
|
||||||
|
|
@ -0,0 +1,17 @@
|
||||||
|
# IOMATEX Console Architecture
|
||||||
|
|
||||||
|
## Core responsibilities
|
||||||
|
- Serve one fast local diagnostics UI.
|
||||||
|
- Expose one normalized status endpoint: `/api/status`.
|
||||||
|
- Load provider modules from `providers.d`.
|
||||||
|
- Cache recent status briefly to avoid repeated shell work on every page render.
|
||||||
|
|
||||||
|
## Addon responsibilities
|
||||||
|
- Add new service cards without changing core frontend or server flow.
|
||||||
|
- Read only the service-specific files and units they need.
|
||||||
|
- Return normalized card objects using the shared card contract.
|
||||||
|
|
||||||
|
## Future `ui_backend` role
|
||||||
|
- Keep this Console focused on lightweight diagnostics.
|
||||||
|
- Future `ui_backend` can own richer workflows: actions, forms, provisioning, and service-specific control paths.
|
||||||
|
- The normalized card contract can remain stable while richer backend features evolve separately.
|
||||||
Binary file not shown.
|
|
@ -0,0 +1,273 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
import glob
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
APP_DIR = "/opt/iomatex-console"
|
||||||
|
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||||
|
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||||
|
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||||
|
|
||||||
|
DEFAULT_CONFIG = {
|
||||||
|
"bind": "0.0.0.0",
|
||||||
|
"port": 8099,
|
||||||
|
"cache_ttl_sec": 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
_CACHE = {"expires_at": 0.0, "payload": None}
|
||||||
|
|
||||||
|
|
||||||
|
def load_config():
|
||||||
|
data = dict(DEFAULT_CONFIG)
|
||||||
|
try:
|
||||||
|
with open(CONFIG_PATH, "r", encoding="utf-8") as fh:
|
||||||
|
loaded = json.load(fh)
|
||||||
|
if isinstance(loaded, dict):
|
||||||
|
data.update(loaded)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd, timeout=4):
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
timeout=timeout,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip()
|
||||||
|
except Exception as exc:
|
||||||
|
return 1, "", str(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def file_exists(path):
|
||||||
|
return os.path.exists(path)
|
||||||
|
|
||||||
|
|
||||||
|
def any_exists(paths):
|
||||||
|
return any(os.path.exists(path) for path in paths)
|
||||||
|
|
||||||
|
|
||||||
|
def read_text(path):
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
|
||||||
|
return fh.read()
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def read_env_file(path):
|
||||||
|
data = {}
|
||||||
|
try:
|
||||||
|
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
|
||||||
|
for raw in fh:
|
||||||
|
line = raw.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
value = value.strip().strip('"').strip("'")
|
||||||
|
data[key.strip()] = value
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def systemd_unit(unit_name):
|
||||||
|
properties = [
|
||||||
|
"LoadState",
|
||||||
|
"ActiveState",
|
||||||
|
"SubState",
|
||||||
|
"UnitFileState",
|
||||||
|
"Result",
|
||||||
|
"ExecMainStatus",
|
||||||
|
"FragmentPath",
|
||||||
|
]
|
||||||
|
cmd = ["systemctl", "show", unit_name, "--no-page"]
|
||||||
|
for prop in properties:
|
||||||
|
cmd.extend(["-p", prop])
|
||||||
|
rc, stdout, stderr = run(cmd)
|
||||||
|
data = {
|
||||||
|
"unit": unit_name,
|
||||||
|
"load_state": "not-found",
|
||||||
|
"active_state": "inactive",
|
||||||
|
"sub_state": "dead",
|
||||||
|
"unit_file_state": "unknown",
|
||||||
|
"result": "",
|
||||||
|
"exec_main_status": "",
|
||||||
|
"fragment_path": "",
|
||||||
|
"installed": False,
|
||||||
|
"active": False,
|
||||||
|
"raw_error": stderr if rc != 0 else "",
|
||||||
|
}
|
||||||
|
if stdout:
|
||||||
|
for line in stdout.splitlines():
|
||||||
|
if "=" not in line:
|
||||||
|
continue
|
||||||
|
key, value = line.split("=", 1)
|
||||||
|
key = key.strip()
|
||||||
|
value = value.strip()
|
||||||
|
if key == "LoadState":
|
||||||
|
data["load_state"] = value or "not-found"
|
||||||
|
elif key == "ActiveState":
|
||||||
|
data["active_state"] = value or "inactive"
|
||||||
|
elif key == "SubState":
|
||||||
|
data["sub_state"] = value or "dead"
|
||||||
|
elif key == "UnitFileState":
|
||||||
|
data["unit_file_state"] = value or "unknown"
|
||||||
|
elif key == "Result":
|
||||||
|
data["result"] = value
|
||||||
|
elif key == "ExecMainStatus":
|
||||||
|
data["exec_main_status"] = value
|
||||||
|
elif key == "FragmentPath":
|
||||||
|
data["fragment_path"] = value
|
||||||
|
data["installed"] = data["load_state"] != "not-found" or bool(data["fragment_path"])
|
||||||
|
data["active"] = data["active_state"] == "active"
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_card(card):
|
||||||
|
item = dict(card)
|
||||||
|
item.setdefault("id", "unknown")
|
||||||
|
item.setdefault("title", item["id"])
|
||||||
|
item["installed"] = bool(item.get("installed", False))
|
||||||
|
item["configured"] = bool(item.get("configured", False))
|
||||||
|
item["active"] = bool(item.get("active", False))
|
||||||
|
item["state"] = str(item.get("state", "unknown"))
|
||||||
|
item["status_text"] = str(item.get("status_text", item["state"]))
|
||||||
|
item["errors"] = [str(x) for x in item.get("errors", []) if str(x).strip()]
|
||||||
|
item["warnings"] = [str(x) for x in item.get("warnings", []) if str(x).strip()]
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def load_providers():
|
||||||
|
providers = []
|
||||||
|
for path in sorted(glob.glob(os.path.join(PROVIDERS_DIR, "*.py"))):
|
||||||
|
name = "provider_" + os.path.basename(path).replace(".", "_")
|
||||||
|
spec = importlib.util.spec_from_file_location(name, path)
|
||||||
|
if not spec or not spec.loader:
|
||||||
|
continue
|
||||||
|
module = importlib.util.module_from_spec(spec)
|
||||||
|
try:
|
||||||
|
spec.loader.exec_module(module)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
if hasattr(module, "get_cards"):
|
||||||
|
providers.append((path, module.get_cards))
|
||||||
|
return providers
|
||||||
|
|
||||||
|
|
||||||
|
def build_status_payload():
|
||||||
|
now = time.time()
|
||||||
|
cfg = load_config()
|
||||||
|
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||||
|
return _CACHE["payload"]
|
||||||
|
|
||||||
|
context = {
|
||||||
|
"file_exists": file_exists,
|
||||||
|
"any_exists": any_exists,
|
||||||
|
"read_text": read_text,
|
||||||
|
"read_env_file": read_env_file,
|
||||||
|
"systemd_unit": systemd_unit,
|
||||||
|
}
|
||||||
|
cards = []
|
||||||
|
provider_names = []
|
||||||
|
for path, provider in load_providers():
|
||||||
|
provider_names.append(os.path.basename(path))
|
||||||
|
try:
|
||||||
|
result = provider(context)
|
||||||
|
except Exception as exc:
|
||||||
|
result = [{
|
||||||
|
"id": os.path.splitext(os.path.basename(path))[0],
|
||||||
|
"title": os.path.basename(path),
|
||||||
|
"installed": False,
|
||||||
|
"configured": False,
|
||||||
|
"active": False,
|
||||||
|
"state": "error",
|
||||||
|
"status_text": "Provider error",
|
||||||
|
"errors": [str(exc)],
|
||||||
|
"warnings": [],
|
||||||
|
}]
|
||||||
|
if isinstance(result, dict):
|
||||||
|
result = [result]
|
||||||
|
for card in result or []:
|
||||||
|
cards.append(normalize_card(card))
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
|
"services": cards,
|
||||||
|
"providers": provider_names,
|
||||||
|
}
|
||||||
|
_CACHE["payload"] = payload
|
||||||
|
_CACHE["expires_at"] = now + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, fmt, *args):
|
||||||
|
return
|
||||||
|
|
||||||
|
def send_json(self, payload, code=200):
|
||||||
|
body = json.dumps(payload, indent=2).encode("utf-8")
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def send_file(self, path, content_type):
|
||||||
|
try:
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
data = fh.read()
|
||||||
|
except FileNotFoundError:
|
||||||
|
self.send_error(404)
|
||||||
|
return
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", content_type)
|
||||||
|
self.send_header("Content-Length", str(len(data)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(data)
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
if parsed.path == "/api/status":
|
||||||
|
self.send_json(build_status_payload())
|
||||||
|
return
|
||||||
|
if parsed.path in ("/", "/index.html"):
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/console.css":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/console.js":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8")
|
||||||
|
return
|
||||||
|
if parsed.path == "/logo.png":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png")
|
||||||
|
return
|
||||||
|
if parsed.path == "/favicon.png":
|
||||||
|
self.send_file(os.path.join(PUBLIC_DIR, "favicon.png"), "image/png")
|
||||||
|
return
|
||||||
|
self.send_error(404)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
cfg = load_config()
|
||||||
|
bind = str(cfg.get("bind", DEFAULT_CONFIG["bind"]))
|
||||||
|
port = int(cfg.get("port", DEFAULT_CONFIG["port"]))
|
||||||
|
server = ThreadingHTTPServer((bind, port), Handler)
|
||||||
|
print(f"[console] http://{bind}:{port}", file=sys.stderr)
|
||||||
|
server.serve_forever()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|
@ -0,0 +1,78 @@
|
||||||
|
:root{
|
||||||
|
--bg:#eef2f0;
|
||||||
|
--panel:#ffffff;
|
||||||
|
--ink:#16211d;
|
||||||
|
--muted:#66736d;
|
||||||
|
--line:#d7e0db;
|
||||||
|
--accent:#0e7a53;
|
||||||
|
--warn:#9a6a00;
|
||||||
|
--error:#b93434;
|
||||||
|
--shadow:0 12px 32px rgba(16,24,20,.08);
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{
|
||||||
|
margin:0;
|
||||||
|
font-family:system-ui,-apple-system,"Segoe UI",sans-serif;
|
||||||
|
background:
|
||||||
|
radial-gradient(circle at top left, rgba(14,122,83,.10), transparent 32%),
|
||||||
|
linear-gradient(180deg, #f7faf8 0%, var(--bg) 100%);
|
||||||
|
color:var(--ink);
|
||||||
|
}
|
||||||
|
.shell{max-width:1100px;margin:0 auto;padding:28px 18px 40px}
|
||||||
|
.hero{
|
||||||
|
display:flex;justify-content:space-between;gap:16px;align-items:center;flex-wrap:wrap;
|
||||||
|
margin-bottom:18px;
|
||||||
|
}
|
||||||
|
.brand{display:flex;align-items:center;gap:14px;min-width:0}
|
||||||
|
.brandLogo{
|
||||||
|
width:40px;height:40px;object-fit:contain;display:block;flex:0 0 auto;
|
||||||
|
border-radius:10px;background:#fff;border:1px solid var(--line);padding:4px;
|
||||||
|
}
|
||||||
|
.eyebrow{font-size:12px;letter-spacing:.16em;text-transform:uppercase;color:var(--accent);font-weight:700}
|
||||||
|
h1{margin:4px 0 4px;font-size:34px;line-height:1}
|
||||||
|
.sub{margin:0;color:var(--muted)}
|
||||||
|
.actions button{
|
||||||
|
border:0;border-radius:999px;background:var(--ink);color:#fff;padding:12px 18px;font-weight:700;cursor:pointer;
|
||||||
|
box-shadow:var(--shadow);
|
||||||
|
}
|
||||||
|
.panel{
|
||||||
|
background:var(--panel);border:1px solid var(--line);border-radius:18px;box-shadow:var(--shadow);
|
||||||
|
}
|
||||||
|
.summary{
|
||||||
|
display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;padding:16px 18px;margin-bottom:18px;
|
||||||
|
}
|
||||||
|
.summaryItem{display:flex;flex-direction:column;gap:4px}
|
||||||
|
.label{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}
|
||||||
|
.cards{
|
||||||
|
display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px;
|
||||||
|
}
|
||||||
|
.card{padding:18px}
|
||||||
|
.cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
|
||||||
|
.card h2{margin:0;font-size:19px}
|
||||||
|
.badge{
|
||||||
|
display:inline-flex;align-items:center;gap:8px;border-radius:999px;padding:7px 10px;font-size:12px;font-weight:700;
|
||||||
|
background:#edf4f0;color:var(--ink);
|
||||||
|
}
|
||||||
|
.dot{width:9px;height:9px;border-radius:50%}
|
||||||
|
.dot.ok{background:var(--accent)}
|
||||||
|
.dot.warn{background:var(--warn)}
|
||||||
|
.dot.error{background:var(--error)}
|
||||||
|
.meta{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;margin-top:16px;font-size:13px}
|
||||||
|
.meta .key{color:var(--muted)}
|
||||||
|
.list{margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}
|
||||||
|
.listTitle{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px}
|
||||||
|
.pillRow{display:flex;gap:8px;flex-wrap:wrap}
|
||||||
|
.pill{
|
||||||
|
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:#f5f7f6;color:var(--ink);
|
||||||
|
}
|
||||||
|
.pill.good{background:rgba(14,122,83,.10);color:var(--accent)}
|
||||||
|
.pill.bad{background:rgba(185,52,52,.10);color:var(--error)}
|
||||||
|
.msgList{margin:8px 0 0;padding-left:18px;color:var(--muted)}
|
||||||
|
.empty{
|
||||||
|
padding:32px;border:1px dashed var(--line);border-radius:18px;background:rgba(255,255,255,.6);color:var(--muted);text-align:center;
|
||||||
|
}
|
||||||
|
@media (max-width:720px){
|
||||||
|
.summary{grid-template-columns:1fr}
|
||||||
|
.meta{grid-template-columns:1fr 1fr}
|
||||||
|
.brand{align-items:flex-start}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const nodes = {
|
||||||
|
refreshBtn: document.getElementById("refreshBtn"),
|
||||||
|
cards: document.getElementById("cards"),
|
||||||
|
lastUpdate: document.getElementById("lastUpdate"),
|
||||||
|
providerCount: document.getElementById("providerCount"),
|
||||||
|
serviceCount: document.getElementById("serviceCount")
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(value) {
|
||||||
|
return (value ?? "").toString().replace(/[&<>"']/g, (m) => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
"\"": """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function boolPill(label, value) {
|
||||||
|
return `<span class="pill ${value ? "good" : "bad"}">${esc(label)}: ${value ? "yes" : "no"}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusTone(card) {
|
||||||
|
if (card.errors && card.errors.length) return "error";
|
||||||
|
if (card.active) return "ok";
|
||||||
|
return "warn";
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCard(card) {
|
||||||
|
const tone = statusTone(card);
|
||||||
|
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
|
||||||
|
const errors = Array.isArray(card.errors) ? card.errors : [];
|
||||||
|
|
||||||
|
return `
|
||||||
|
<article class="panel card">
|
||||||
|
<div class="cardTop">
|
||||||
|
<div>
|
||||||
|
<h2>${esc(card.title)}</h2>
|
||||||
|
<div class="badge"><span class="dot ${tone}"></span>${esc(card.status_text || card.state || "Unknown")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="meta">
|
||||||
|
<div class="key">ID</div><div>${esc(card.id)}</div>
|
||||||
|
<div class="key">State</div><div>${esc(card.state || "-")}</div>
|
||||||
|
<div class="key">Status</div><div>${esc(card.status_text || "-")}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="list">
|
||||||
|
<div class="listTitle">Flags</div>
|
||||||
|
<div class="pillRow">
|
||||||
|
${boolPill("Installed", !!card.installed)}
|
||||||
|
${boolPill("Configured", !!card.configured)}
|
||||||
|
${boolPill("Active", !!card.active)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
${warnings.length ? `
|
||||||
|
<div class="list">
|
||||||
|
<div class="listTitle">Warnings</div>
|
||||||
|
<ul class="msgList">${warnings.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>
|
||||||
|
</div>
|
||||||
|
` : ""}
|
||||||
|
|
||||||
|
${errors.length ? `
|
||||||
|
<div class="list">
|
||||||
|
<div class="listTitle">Errors</div>
|
||||||
|
<ul class="msgList">${errors.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>
|
||||||
|
</div>
|
||||||
|
` : ""}
|
||||||
|
</article>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(payload) {
|
||||||
|
const services = Array.isArray(payload.services) ? payload.services : [];
|
||||||
|
const providers = Array.isArray(payload.providers) ? payload.providers : [];
|
||||||
|
|
||||||
|
nodes.lastUpdate.textContent = payload.generated_at || "-";
|
||||||
|
nodes.providerCount.textContent = String(providers.length);
|
||||||
|
nodes.serviceCount.textContent = String(services.length);
|
||||||
|
|
||||||
|
if (!services.length) {
|
||||||
|
nodes.cards.innerHTML = `<div class="empty">No service cards returned by providers.</div>`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.cards.innerHTML = services.map(renderCard).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
nodes.refreshBtn.disabled = true;
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/status", { cache: "no-store" });
|
||||||
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||||
|
const payload = await response.json();
|
||||||
|
render(payload);
|
||||||
|
} catch (error) {
|
||||||
|
nodes.cards.innerHTML = `<div class="empty">Failed to load status: ${esc(error.message || String(error))}</div>`;
|
||||||
|
} finally {
|
||||||
|
nodes.refreshBtn.disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nodes.refreshBtn.addEventListener("click", load);
|
||||||
|
load();
|
||||||
|
})();
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>IOMATEX Console</title>
|
||||||
|
<link rel="icon" type="image/png" href="/favicon.png">
|
||||||
|
<link rel="stylesheet" href="/console.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="shell">
|
||||||
|
<header class="hero">
|
||||||
|
<div class="brand">
|
||||||
|
<img class="brandLogo" src="/logo.png" alt="IOMATEX logo">
|
||||||
|
<div>
|
||||||
|
<div class="eyebrow">IOMATEX</div>
|
||||||
|
<h1>Console</h1>
|
||||||
|
<p class="sub">Lightweight diagnostics for installed services.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button id="refreshBtn" type="button">Refresh</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="panel summary">
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Last update</span>
|
||||||
|
<strong id="lastUpdate">-</strong>
|
||||||
|
</div>
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Providers</span>
|
||||||
|
<strong id="providerCount">-</strong>
|
||||||
|
</div>
|
||||||
|
<div class="summaryItem">
|
||||||
|
<span class="label">Cards</span>
|
||||||
|
<strong id="serviceCount">-</strong>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section id="cards" class="cards" aria-live="polite"></section>
|
||||||
|
</main>
|
||||||
|
<script src="/console.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
@ -0,0 +1,192 @@
|
||||||
|
def _service_card(service_id, title, unit_name, installed, configured, active, state, status_text, errors=None, warnings=None):
|
||||||
|
return {
|
||||||
|
"id": service_id,
|
||||||
|
"title": title,
|
||||||
|
"installed": installed,
|
||||||
|
"configured": configured,
|
||||||
|
"active": active,
|
||||||
|
"state": state,
|
||||||
|
"status_text": status_text,
|
||||||
|
"errors": errors or [],
|
||||||
|
"warnings": warnings or [],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _short_unit_errors(unit):
|
||||||
|
errors = []
|
||||||
|
if unit["active_state"] == "failed":
|
||||||
|
errors.append("Service failed")
|
||||||
|
if unit["result"] and unit["result"] not in ("success", "done"):
|
||||||
|
errors.append(f"Result: {unit['result']}")
|
||||||
|
if unit["exec_main_status"] and unit["exec_main_status"] not in ("0", ""):
|
||||||
|
errors.append(f"Exit status: {unit['exec_main_status']}")
|
||||||
|
if unit["raw_error"]:
|
||||||
|
errors.append(unit["raw_error"])
|
||||||
|
return errors[:2]
|
||||||
|
|
||||||
|
|
||||||
|
def _lifecycle(installed, configured, active, *, failed=False):
|
||||||
|
if not installed:
|
||||||
|
return "not installed", "Not installed"
|
||||||
|
if active:
|
||||||
|
return "active", "Active"
|
||||||
|
if not configured:
|
||||||
|
return "installed_not_configured", "Not configured"
|
||||||
|
if failed:
|
||||||
|
return "failed", "Failed"
|
||||||
|
return "inactive", "Inactive"
|
||||||
|
|
||||||
|
|
||||||
|
def _strict_active(installed, configured, unit):
|
||||||
|
return bool(installed and configured and unit["active"])
|
||||||
|
|
||||||
|
|
||||||
|
def itscreen_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("itscreen-x11.service")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/opt/itscreen/bin/itscreen",
|
||||||
|
"/etc/systemd/system/itscreen-x11.service",
|
||||||
|
"/lib/systemd/system/itscreen-x11.service",
|
||||||
|
])
|
||||||
|
configured = ctx["any_exists"]([
|
||||||
|
"/etc/systemd/system/itscreen-x11.service",
|
||||||
|
"/lib/systemd/system/itscreen-x11.service",
|
||||||
|
])
|
||||||
|
warnings = []
|
||||||
|
if installed and not configured:
|
||||||
|
warnings.append("Service unit not found")
|
||||||
|
active = _strict_active(installed, configured, unit)
|
||||||
|
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
|
||||||
|
return _service_card(
|
||||||
|
"itscreen",
|
||||||
|
"IT-Screen App",
|
||||||
|
"itscreen-x11.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
_short_unit_errors(unit),
|
||||||
|
warnings,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def mosquitto_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("mosquitto.service")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/etc/mosquitto/mosquitto.conf",
|
||||||
|
"/lib/systemd/system/mosquitto.service",
|
||||||
|
"/etc/systemd/system/mosquitto.service",
|
||||||
|
])
|
||||||
|
configured = ctx["file_exists"]("/etc/mosquitto/mosquitto.conf")
|
||||||
|
warnings = []
|
||||||
|
if installed and not configured:
|
||||||
|
warnings.append("Main config missing")
|
||||||
|
active = _strict_active(installed, configured, unit)
|
||||||
|
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
|
||||||
|
return _service_card(
|
||||||
|
"mosquitto",
|
||||||
|
"Mosquitto MQTT",
|
||||||
|
"mosquitto.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
_short_unit_errors(unit),
|
||||||
|
warnings,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def mqtt_bridge_card(ctx):
|
||||||
|
env = ctx["read_env_file"]("/etc/iomatex/mqtt_bridge.env")
|
||||||
|
installed = ctx["any_exists"]([
|
||||||
|
"/etc/iomatex/mqtt_bridge.env",
|
||||||
|
"/usr/local/sbin/iomatex-mqtt-apply",
|
||||||
|
"/etc/systemd/system/iomatex-mqtt-bridge.service",
|
||||||
|
])
|
||||||
|
enabled = str(env.get("ENABLE_BRIDGE", "0")).strip() == "1"
|
||||||
|
configured = bool(env.get("REMOTE_HOST", "").strip())
|
||||||
|
bridge_service = ctx["systemd_unit"]("iomatex-mqtt-bridge.service")
|
||||||
|
bridge_path = ctx["systemd_unit"]("iomatex-mqtt-bridge.path")
|
||||||
|
active = bool(bridge_service["active"] or bridge_path["active"])
|
||||||
|
warnings = []
|
||||||
|
errors = []
|
||||||
|
if installed and not enabled:
|
||||||
|
warnings.append("Bridge disabled")
|
||||||
|
if installed and enabled and not configured:
|
||||||
|
errors.append("REMOTE_HOST is empty")
|
||||||
|
state, status_text = _lifecycle(installed, configured, active)
|
||||||
|
if installed and configured and not active and not enabled:
|
||||||
|
status_text = "Disabled"
|
||||||
|
return _service_card(
|
||||||
|
"mqtt_bridge",
|
||||||
|
"MQTT Bridge",
|
||||||
|
"iomatex-mqtt-bridge.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
errors[:2],
|
||||||
|
warnings[:2],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def zigbee_card(ctx):
|
||||||
|
unit = ctx["systemd_unit"]("zigbee2mqtt.service")
|
||||||
|
app_footprint = ctx["any_exists"]([
|
||||||
|
"/opt/zigbee2mqtt/package.json",
|
||||||
|
"/opt/zigbee2mqtt/index.js",
|
||||||
|
])
|
||||||
|
unit_footprint = ctx["any_exists"]([
|
||||||
|
"/etc/systemd/system/zigbee2mqtt.service",
|
||||||
|
"/lib/systemd/system/zigbee2mqtt.service",
|
||||||
|
])
|
||||||
|
installed = bool(app_footprint or unit_footprint or unit["installed"])
|
||||||
|
configured = installed and ctx["file_exists"]("/opt/zigbee2mqtt/data/configuration.yaml")
|
||||||
|
active = _strict_active(installed, configured, unit)
|
||||||
|
warnings = []
|
||||||
|
if installed and not configured:
|
||||||
|
warnings.append("configuration.yaml missing")
|
||||||
|
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
|
||||||
|
return _service_card(
|
||||||
|
"zigbee2mqtt",
|
||||||
|
"Zigbee2MQTT",
|
||||||
|
"zigbee2mqtt.service",
|
||||||
|
installed,
|
||||||
|
configured,
|
||||||
|
active,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
_short_unit_errors(unit),
|
||||||
|
warnings,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def placeholder_card(service_id, title):
|
||||||
|
state, status_text = _lifecycle(False, False, False)
|
||||||
|
return _service_card(
|
||||||
|
service_id,
|
||||||
|
title,
|
||||||
|
"",
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
state,
|
||||||
|
status_text,
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_cards(ctx):
|
||||||
|
return [
|
||||||
|
itscreen_card(ctx),
|
||||||
|
mosquitto_card(ctx),
|
||||||
|
mqtt_bridge_card(ctx),
|
||||||
|
zigbee_card(ctx),
|
||||||
|
placeholder_card("reverse_tunnel", "Reverse Tunnel"),
|
||||||
|
placeholder_card("display", "Display"),
|
||||||
|
placeholder_card("edge_api", "Edge API"),
|
||||||
|
]
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 355 KiB After Width: | Height: | Size: 355 KiB |
|
|
@ -0,0 +1,9 @@
|
||||||
|
# Legacy UI Reference
|
||||||
|
|
||||||
|
These files preserve the previous WebIPC-based UI implementation as reference only:
|
||||||
|
|
||||||
|
- `ui_installer.sh`
|
||||||
|
- `ui_addon_itscreen.sh`
|
||||||
|
- `ui_addon_display.sh`
|
||||||
|
|
||||||
|
The new `stage_ui/ui_installer.sh` installs the lightweight Console core instead of the legacy Node/Express UI.
|
||||||
|
|
@ -0,0 +1,207 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP="/opt/iomatex-process1-webipc"
|
||||||
|
ADDON_FRONT="$APP/public/addons"
|
||||||
|
SERVICE="iomatex-webipc.service"
|
||||||
|
|
||||||
|
echo "[1/4] prepare dirs"
|
||||||
|
mkdir -p "$ADDON_FRONT"
|
||||||
|
|
||||||
|
echo "[2/4] write x11 addon"
|
||||||
|
cat > "$ADDON_FRONT/x11.js" <<'JS'
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
if (window.__iomatexX11AddonLoaded) return;
|
||||||
|
window.__iomatexX11AddonLoaded = true;
|
||||||
|
|
||||||
|
const ui = window.IOMATEX_UI;
|
||||||
|
if (!ui) return;
|
||||||
|
|
||||||
|
const state = ui.state;
|
||||||
|
|
||||||
|
state.x11Addon = state.x11Addon || {
|
||||||
|
data: null,
|
||||||
|
busy: { refresh: false },
|
||||||
|
message: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return (s ?? "").toString().replace(/[&<>"']/g, m => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
'"': """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBusy(key, v) {
|
||||||
|
state.x11Addon.busy[key] = !!v;
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMsg(msg) {
|
||||||
|
state.x11Addon.message = (msg || "").toString();
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function btn(label, kind, fnName, busyKey, busyLabel) {
|
||||||
|
const busy = !!state.x11Addon.busy[busyKey];
|
||||||
|
return `<button class="${kind || ""}" ${busy ? "disabled" : ""} onclick="${busy ? "return false" : fnName}">${esc(busy ? busyLabel : label)}</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDisplay() {
|
||||||
|
const j = await ui.call("/api/display/hdmi");
|
||||||
|
state.x11Addon.data = j;
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshDisplay() {
|
||||||
|
setBusy("refresh", true);
|
||||||
|
setMsg("Refreshing display information...");
|
||||||
|
try {
|
||||||
|
await ui.loadDetail("x11").catch(() => {});
|
||||||
|
await loadDisplay();
|
||||||
|
setMsg("Display information updated.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("refresh", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderConnector(c) {
|
||||||
|
return `
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">${esc(c.edid?.monitor_name || c.connector || "Connector")}</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Connector</div><b class="mono">${esc(c.connector || "-")}</b>
|
||||||
|
<div>Type</div><b class="mono">${esc(c.kind || "-")}</b>
|
||||||
|
<div>Status</div><b class="mono">${esc(c.status || "-")}</b>
|
||||||
|
<div>Connected</div><b class="mono">${esc(c.connected ? "yes" : "no")}</b>
|
||||||
|
<div>Enabled</div><b class="mono">${esc(c.enabled || "-")}</b>
|
||||||
|
<div>DPMS</div><b class="mono">${esc(c.dpms || "-")}</b>
|
||||||
|
<div>Preferred mode</div><b class="mono">${esc(c.preferred_mode || "-")}</b>
|
||||||
|
<div>Modes</div><b class="mono">${esc((c.modes || []).join(", ") || "-")}</b>
|
||||||
|
<div>Monitor</div><b class="mono">${esc(c.edid?.monitor_name || "-")}</b>
|
||||||
|
<div>Vendor</div><b class="mono">${esc(c.edid?.manufacturer_id || "-")}</b>
|
||||||
|
<div>Product code</div><b class="mono">${esc(c.edid?.product_code || "-")}</b>
|
||||||
|
<div>Serial</div><b class="mono">${esc(c.edid?.serial_text || "-")}</b>
|
||||||
|
<div>Size</div><b class="mono">${esc(c.edid?.size_cm || "-")}</b>
|
||||||
|
<div>Diagonal</div><b class="mono">${esc(c.edid?.size_inch || "-")}</b>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderX11Detail(service) {
|
||||||
|
const d = state.x11Addon.data || {};
|
||||||
|
const sum = d.summary || {};
|
||||||
|
const first = sum.first_connected_hdmi || null;
|
||||||
|
const connectors = Array.isArray(d.connectors) ? d.connectors : [];
|
||||||
|
const connected = connectors.filter(x => x.connected);
|
||||||
|
const hdmi = Array.isArray(d.hdmi) ? d.hdmi : [];
|
||||||
|
const status = service.status || {};
|
||||||
|
|
||||||
|
document.getElementById("viewTitle").textContent = service.title || "Display";
|
||||||
|
document.getElementById("viewSub").textContent = service.desc || "";
|
||||||
|
document.getElementById("viewActions").innerHTML =
|
||||||
|
`<button class="primary" onclick="window.__x11Refresh()">Refresh</button>`;
|
||||||
|
|
||||||
|
document.getElementById("view").innerHTML = `
|
||||||
|
<div class="stack">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Display summary</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Active</div><b class="mono">${esc(status.active || "-")}</b>
|
||||||
|
<div>Started</div><b class="mono">${esc(status.started_at || "-")}</b>
|
||||||
|
<div>State</div><b class="mono">${esc(status.summary || "-")}</b>
|
||||||
|
<div>Running</div><b class="mono">${esc(status.running_for_text || "-")}</b>
|
||||||
|
<div>HDMI connected</div><b class="mono">${esc(sum.hdmi_connected ? "yes" : "no")}</b>
|
||||||
|
<div>Connected displays</div><b class="mono">${esc(String(sum.connected_count ?? 0))}</b>
|
||||||
|
<div>Connected HDMI</div><b class="mono">${esc(String(sum.connected_hdmi_count ?? 0))}</b>
|
||||||
|
<div>Connector</div><b class="mono">${esc(first?.connector || "-")}</b>
|
||||||
|
<div>Monitor</div><b class="mono">${esc(first?.edid?.monitor_name || "-")}</b>
|
||||||
|
<div>Preferred mode</div><b class="mono">${esc(first?.preferred_mode || "-")}</b>
|
||||||
|
<div>Vendor</div><b class="mono">${esc(first?.edid?.manufacturer_id || "-")}</b>
|
||||||
|
</div>
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Refresh", "primary", "window.__x11Refresh()", "refresh", "Refreshing...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Connected connectors</div>
|
||||||
|
${connected.length ? connected.map(renderConnector).join("") : `<div class="small">No connected connectors detected.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">HDMI connectors</div>
|
||||||
|
${hdmi.length ? hdmi.map(renderConnector).join("") : `<div class="small">No HDMI connectors found.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">All DRM connectors</div>
|
||||||
|
${connectors.length ? connectors.map(renderConnector).join("") : `<div class="small">No DRM connectors found.</div>`}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Message</div>
|
||||||
|
<div class="small mono">${esc(state.x11Addon.message || "Ready")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevLoadTabData = ui.loadTabData.bind(ui);
|
||||||
|
const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){};
|
||||||
|
const prevRender = ui.render.bind(ui);
|
||||||
|
|
||||||
|
ui.loadTabData = async function () {
|
||||||
|
if (state.tab === "x11") {
|
||||||
|
await ui.loadDetail("x11");
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevLoadTabData();
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.refreshDetail = async function () {
|
||||||
|
if (state.tab === "x11") {
|
||||||
|
await ui.loadDetail("x11");
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
ui.render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRefreshDetail();
|
||||||
|
};
|
||||||
|
window.refreshDetail = ui.refreshDetail;
|
||||||
|
|
||||||
|
ui.render = function () {
|
||||||
|
if (state.tab === "x11" && state.detail?.service?.key === "x11") {
|
||||||
|
renderX11Detail(state.detail.service);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRender();
|
||||||
|
};
|
||||||
|
window.render = ui.render;
|
||||||
|
|
||||||
|
window.__x11Refresh = refreshDisplay;
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await loadDisplay().catch(() => {});
|
||||||
|
if (state.tab === "x11") ui.render();
|
||||||
|
} catch (_) {}
|
||||||
|
}, 0);
|
||||||
|
})();
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[3/4] restart"
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
|
||||||
|
echo "[4/4] done"
|
||||||
|
echo "Installed frontend: $ADDON_FRONT/x11.js"
|
||||||
|
echo "Restarted: $SERVICE"
|
||||||
|
|
@ -0,0 +1,765 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
APP="/opt/iomatex-process1-webipc"
|
||||||
|
ADDON_BACK="$APP/addons/backend"
|
||||||
|
ADDON_FRONT="$APP/public/addons"
|
||||||
|
CFG="/etc/iomatex/webipc-itscreen.json"
|
||||||
|
SERVICE="iomatex-webipc.service"
|
||||||
|
|
||||||
|
echo "[1/6] prepare dirs"
|
||||||
|
mkdir -p "$ADDON_BACK" "$ADDON_FRONT" /etc/iomatex
|
||||||
|
|
||||||
|
echo "[2/6] config"
|
||||||
|
if [ ! -f "$CFG" ]; then
|
||||||
|
cat > "$CFG" <<'EOF'
|
||||||
|
{
|
||||||
|
"server": "",
|
||||||
|
"deviceId": "",
|
||||||
|
"token": "",
|
||||||
|
"username": "",
|
||||||
|
"password": "",
|
||||||
|
"topicNamespace": ""
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[3/6] backend addon"
|
||||||
|
cat > "$ADDON_BACK/itscreen.js" <<'JS'
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
const fs = require("fs");
|
||||||
|
const os = require("os");
|
||||||
|
const mqtt = require("mqtt");
|
||||||
|
|
||||||
|
const CFG = "/etc/iomatex/webipc-itscreen.json";
|
||||||
|
const MQTT = "mqtt://127.0.0.1:1883";
|
||||||
|
const LOGIN_PASSWORD = "eXXI0wkHBmNBnVbE";
|
||||||
|
const TOPIC_NAMESPACES = ["it-screen", "iomatex"];
|
||||||
|
const ITSERVICE = "itscreen-x11.service";
|
||||||
|
|
||||||
|
function readCfg() {
|
||||||
|
try {
|
||||||
|
const j = JSON.parse(fs.readFileSync(CFG, "utf8"));
|
||||||
|
return {
|
||||||
|
server: (j.server || "").toString(),
|
||||||
|
deviceId: (j.deviceId || "").toString(),
|
||||||
|
token: (j.token || "").toString(),
|
||||||
|
username: (j.username || "").toString(),
|
||||||
|
password: (j.password || "").toString(),
|
||||||
|
topicNamespace: (j.topicNamespace || "").toString()
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
server: "",
|
||||||
|
deviceId: "",
|
||||||
|
token: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
topicNamespace: ""
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeCfg(o) {
|
||||||
|
const safe = {
|
||||||
|
server: (o.server || "").toString().trim(),
|
||||||
|
deviceId: (o.deviceId || "").toString().trim(),
|
||||||
|
token: (o.token || "").toString().trim(),
|
||||||
|
username: (o.username || "").toString().trim(),
|
||||||
|
password: (o.password || "").toString().trim(),
|
||||||
|
topicNamespace: (o.topicNamespace || "").toString().trim()
|
||||||
|
};
|
||||||
|
fs.writeFileSync(CFG, JSON.stringify(safe, null, 2) + "\n", "utf8");
|
||||||
|
return safe;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeNamespace(ns) {
|
||||||
|
ns = (ns || "").toString().trim();
|
||||||
|
return TOPIC_NAMESPACES.includes(ns) ? ns : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function getDeviceId(cfg) {
|
||||||
|
return (cfg.deviceId || os.hostname()).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
function topicPair(cfg, namespace) {
|
||||||
|
const id = getDeviceId(cfg);
|
||||||
|
const ns = normalizeNamespace(namespace) || "it-screen";
|
||||||
|
const base = `${ns}/$devices/settings/${id}`;
|
||||||
|
return {
|
||||||
|
namespace: ns,
|
||||||
|
deviceId: id,
|
||||||
|
sub: `${base}/sub`,
|
||||||
|
pub: `${base}/pub`
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNamespaceOrder(cfg) {
|
||||||
|
const preferred = normalizeNamespace(cfg.topicNamespace);
|
||||||
|
if (preferred) return [preferred].concat(TOPIC_NAMESPACES.filter(x => x !== preferred));
|
||||||
|
return TOPIC_NAMESPACES.slice();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasRegistrationData(obj) {
|
||||||
|
if (!obj || typeof obj !== "object") return false;
|
||||||
|
const server = (obj.server || obj.host || "").toString().trim();
|
||||||
|
const username = (obj.username || "").toString().trim();
|
||||||
|
const password = (obj.password || "").toString().trim();
|
||||||
|
return !!(server && username && password);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = function(app, ctx) {
|
||||||
|
const mqttc = mqtt.connect(MQTT, {
|
||||||
|
reconnectPeriod: 1000,
|
||||||
|
connectTimeout: 4000,
|
||||||
|
keepalive: 30,
|
||||||
|
clean: true
|
||||||
|
});
|
||||||
|
|
||||||
|
let loginState = {
|
||||||
|
ok: false,
|
||||||
|
lastTs: null,
|
||||||
|
lastError: null,
|
||||||
|
lastNamespace: null
|
||||||
|
};
|
||||||
|
|
||||||
|
let sendQueue = Promise.resolve();
|
||||||
|
|
||||||
|
function saveNamespaceIfChanged(namespace) {
|
||||||
|
const ns = normalizeNamespace(namespace);
|
||||||
|
if (!ns) return readCfg();
|
||||||
|
const cur = readCfg();
|
||||||
|
if (cur.topicNamespace === ns) return cur;
|
||||||
|
return writeCfg({
|
||||||
|
server: cur.server,
|
||||||
|
deviceId: cur.deviceId || getDeviceId(cur),
|
||||||
|
token: cur.token,
|
||||||
|
username: cur.username,
|
||||||
|
password: cur.password,
|
||||||
|
topicNamespace: ns
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendOne(cfg, namespace, payload, timeout = 3000) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const tp = topicPair(cfg, namespace);
|
||||||
|
let done = false;
|
||||||
|
|
||||||
|
const finish = (obj) => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
mqttc.removeListener("message", onMsg);
|
||||||
|
try { mqttc.unsubscribe(tp.pub); } catch {}
|
||||||
|
resolve(obj);
|
||||||
|
};
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "timeout",
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
}, timeout);
|
||||||
|
|
||||||
|
function onMsg(t, b) {
|
||||||
|
if (t !== tp.pub) return;
|
||||||
|
const raw = b ? b.toString() : "";
|
||||||
|
let parsed = null;
|
||||||
|
try { parsed = JSON.parse(raw); } catch { parsed = { raw }; }
|
||||||
|
finish(Object.assign({
|
||||||
|
ok: true,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
}, parsed));
|
||||||
|
}
|
||||||
|
|
||||||
|
mqttc.subscribe(tp.pub, (subErr) => {
|
||||||
|
if (subErr) {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "subscribe_failed",
|
||||||
|
error: subErr.message,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mqttc.on("message", onMsg);
|
||||||
|
|
||||||
|
mqttc.publish(tp.sub, JSON.stringify(payload), (pubErr) => {
|
||||||
|
if (pubErr) {
|
||||||
|
finish({
|
||||||
|
ok: false,
|
||||||
|
note: "publish_failed",
|
||||||
|
error: pubErr.message,
|
||||||
|
namespace: tp.namespace,
|
||||||
|
topic_sub: tp.sub,
|
||||||
|
topic_pub: tp.pub
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function send(cfg, payload, timeout = 3000) {
|
||||||
|
const namespaces = getNamespaceOrder(cfg);
|
||||||
|
|
||||||
|
const runOne = async () => {
|
||||||
|
let last = null;
|
||||||
|
for (const ns of namespaces) {
|
||||||
|
const r = await sendOne(cfg, ns, payload, timeout);
|
||||||
|
last = r;
|
||||||
|
if (r && (r.result === true || r.category || r.action || (r.ok && !r.note))) {
|
||||||
|
saveNamespaceIfChanged(ns);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return last || { ok: false, note: "no_namespace_tried" };
|
||||||
|
};
|
||||||
|
|
||||||
|
sendQueue = sendQueue.then(runOne, runOne);
|
||||||
|
return sendQueue;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin(cfg) {
|
||||||
|
const r = await send(cfg, {
|
||||||
|
action: "login",
|
||||||
|
password: LOGIN_PASSWORD
|
||||||
|
}, 4000);
|
||||||
|
|
||||||
|
loginState.lastTs = Date.now();
|
||||||
|
loginState.lastNamespace = (r && r.namespace) || null;
|
||||||
|
|
||||||
|
if (r && r.action === "login" && r.result === true) {
|
||||||
|
loginState.ok = true;
|
||||||
|
loginState.lastError = null;
|
||||||
|
} else {
|
||||||
|
loginState.ok = false;
|
||||||
|
loginState.lastError = (r && (r.note || r.error || r.raw)) || "login_failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureLogin(cfg) {
|
||||||
|
return doLogin(cfg);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.get("/api/addon/itscreen/config", (req, res) => {
|
||||||
|
const cfg = readCfg();
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: cfg,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(cfg) },
|
||||||
|
topics: getNamespaceOrder(cfg).map(ns => topicPair(cfg, ns))
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/config/clear", (req, res) => {
|
||||||
|
const cleared = writeCfg({
|
||||||
|
server: "",
|
||||||
|
deviceId: "",
|
||||||
|
token: "",
|
||||||
|
username: "",
|
||||||
|
password: "",
|
||||||
|
topicNamespace: ""
|
||||||
|
});
|
||||||
|
|
||||||
|
loginState = {
|
||||||
|
ok: false,
|
||||||
|
lastTs: Date.now(),
|
||||||
|
lastError: "config_cleared",
|
||||||
|
lastNamespace: null
|
||||||
|
};
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: cleared,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: false }
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/login", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const cfg = readCfg();
|
||||||
|
const r = await doLogin(cfg);
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: readCfg(),
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(readCfg()) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get("/api/addon/itscreen/get_server", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const cfg = readCfg();
|
||||||
|
const loginR = await ensureLogin(cfg);
|
||||||
|
|
||||||
|
if (!(loginR && loginR.result === true)) {
|
||||||
|
const current = readCfg();
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: { ok: false, note: "login_failed_before_get", login_result: loginR }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cfg2 = readCfg();
|
||||||
|
const r = await send(cfg2, {
|
||||||
|
action: "get",
|
||||||
|
category: "server"
|
||||||
|
}, 4000);
|
||||||
|
|
||||||
|
const currentCfg = readCfg();
|
||||||
|
|
||||||
|
if (r && r.category === "server") {
|
||||||
|
const merged = writeCfg({
|
||||||
|
server: (r.host || currentCfg.server || "").toString(),
|
||||||
|
deviceId: currentCfg.deviceId || getDeviceId(cfg2),
|
||||||
|
token: currentCfg.token,
|
||||||
|
username: (r.username || currentCfg.username || "").toString(),
|
||||||
|
password: (r.password || currentCfg.password || "").toString(),
|
||||||
|
topicNamespace: (r.namespace || currentCfg.topicNamespace || "").toString()
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: merged,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(merged) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: currentCfg,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(currentCfg) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/register", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const body = req.body || {};
|
||||||
|
const cfg = readCfg();
|
||||||
|
|
||||||
|
const server = (body.server || "").toString().trim();
|
||||||
|
const username = (body.username || "").toString().trim();
|
||||||
|
const password = (body.password || "").toString().trim();
|
||||||
|
const token = (body.token || "").toString().trim();
|
||||||
|
|
||||||
|
if (!server) return res.status(400).json({ ok: false, error: "server is required" });
|
||||||
|
if (!username) return res.status(400).json({ ok: false, error: "username is required" });
|
||||||
|
if (!password) return res.status(400).json({ ok: false, error: "password is required" });
|
||||||
|
|
||||||
|
const loginR = await ensureLogin(cfg);
|
||||||
|
|
||||||
|
if (!(loginR && loginR.result === true)) {
|
||||||
|
const current = readCfg();
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: { ok: false, note: "login_failed_before_set", login_result: loginR }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const cfg2 = readCfg();
|
||||||
|
const payload = {
|
||||||
|
action: "set",
|
||||||
|
category: "server",
|
||||||
|
host: server,
|
||||||
|
username,
|
||||||
|
password
|
||||||
|
};
|
||||||
|
|
||||||
|
const r = await send(cfg2, payload, 5000);
|
||||||
|
|
||||||
|
if (r && r.result === true) {
|
||||||
|
const saved = writeCfg({
|
||||||
|
server,
|
||||||
|
deviceId: cfg2.deviceId || getDeviceId(cfg2),
|
||||||
|
token,
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
topicNamespace: r.namespace || cfg2.topicNamespace || ""
|
||||||
|
});
|
||||||
|
return res.json({
|
||||||
|
ok: true,
|
||||||
|
config: saved,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(saved) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = readCfg();
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
config: current,
|
||||||
|
login: loginState,
|
||||||
|
registration: { configured: hasRegistrationData(current) },
|
||||||
|
result: r
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message, login: loginState });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/addon/itscreen/service/:action", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const action = (req.params.action || "").toLowerCase();
|
||||||
|
if (!["restart", "stop", "start"].includes(action)) {
|
||||||
|
return res.status(400).json({ ok: false, error: "bad action" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = await ctx.run("/bin/systemctl", [action, ITSERVICE], 12000);
|
||||||
|
if (!r.ok) {
|
||||||
|
return res.status(502).json({ ok: false, error: r.err || r.out || "systemctl failed" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = await ctx.run("/bin/systemctl", ["is-active", ITSERVICE], 6000);
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
action,
|
||||||
|
unit: ITSERVICE,
|
||||||
|
active: (status.out || status.err || "").trim() || "unknown"
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
res.status(502).json({ ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[4/6] frontend addon"
|
||||||
|
cat > "$ADDON_FRONT/itscreen.js" <<'JS'
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
if (window.__iomatexItscreenAddonLoaded) return;
|
||||||
|
window.__iomatexItscreenAddonLoaded = true;
|
||||||
|
|
||||||
|
const ui = window.IOMATEX_UI;
|
||||||
|
if (!ui) return;
|
||||||
|
|
||||||
|
const state = ui.state;
|
||||||
|
|
||||||
|
state.itscreenAddon = state.itscreenAddon || {
|
||||||
|
cfg: {},
|
||||||
|
result: {},
|
||||||
|
login: {},
|
||||||
|
registration: { configured: false },
|
||||||
|
busy: {
|
||||||
|
refresh: false,
|
||||||
|
login: false,
|
||||||
|
register: false,
|
||||||
|
clear: false,
|
||||||
|
restart: false,
|
||||||
|
stop: false,
|
||||||
|
start: false
|
||||||
|
},
|
||||||
|
message: ""
|
||||||
|
};
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return (s ?? "").toString().replace(/[&<>"']/g, m => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
'"': """,
|
||||||
|
"'": "'"
|
||||||
|
}[m]));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMsg(msg) {
|
||||||
|
state.itscreenAddon.message = (msg || "").toString();
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setBusy(key, v) {
|
||||||
|
state.itscreenAddon.busy[key] = !!v;
|
||||||
|
ui.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function inputValue(id) {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
return el ? el.value.trim() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function btn(label, kind, fnName, busyKey, busyLabel) {
|
||||||
|
const busy = !!state.itscreenAddon.busy[busyKey];
|
||||||
|
return `<button class="${kind || ""}" ${busy ? "disabled" : ""} onclick="${busy ? "return false" : fnName}">${esc(busy ? busyLabel : label)}</button>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConfigOnly() {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/config");
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshRemote() {
|
||||||
|
setBusy("refresh", true);
|
||||||
|
setMsg("Refreshing registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/get_server");
|
||||||
|
state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
setMsg("Registration data refreshed.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("refresh", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doLogin() {
|
||||||
|
setBusy("login", true);
|
||||||
|
setMsg("Login in progress...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/login", { method: "POST", body: "{}" });
|
||||||
|
state.itscreenAddon.cfg = j.config || state.itscreenAddon.cfg || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
setMsg(j.login?.ok ? "Login OK." : "Login failed.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("login", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doRegister() {
|
||||||
|
const server = inputValue("its_server");
|
||||||
|
const username = inputValue("its_user");
|
||||||
|
const password = inputValue("its_pass");
|
||||||
|
const token = inputValue("its_token");
|
||||||
|
|
||||||
|
if (!server) return setMsg("Server is required.");
|
||||||
|
if (!username) return setMsg("Username is required.");
|
||||||
|
if (!password) return setMsg("Password is required.");
|
||||||
|
|
||||||
|
setBusy("register", true);
|
||||||
|
setMsg("Saving registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/register", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ server, username, password, token })
|
||||||
|
});
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = j.result || {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg(j.result?.result === true ? "Registration saved." : "Registration request sent.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("register", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doClear() {
|
||||||
|
setBusy("clear", true);
|
||||||
|
setMsg("Clearing registration...");
|
||||||
|
try {
|
||||||
|
const j = await ui.call("/api/addon/itscreen/config/clear", { method: "POST", body: "{}" });
|
||||||
|
state.itscreenAddon.cfg = j.config || {};
|
||||||
|
state.itscreenAddon.login = j.login || {};
|
||||||
|
state.itscreenAddon.registration = j.registration || { configured: false };
|
||||||
|
state.itscreenAddon.result = {};
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg("Registration cleared.");
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy("clear", false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function serviceAction(action) {
|
||||||
|
setBusy(action, true);
|
||||||
|
setMsg(`Service ${action}...`);
|
||||||
|
try {
|
||||||
|
const j = await ui.call(`/api/addon/itscreen/service/${encodeURIComponent(action)}`, {
|
||||||
|
method: "POST",
|
||||||
|
body: "{}"
|
||||||
|
});
|
||||||
|
await ui.loadMain().catch(() => {});
|
||||||
|
await ui.loadDetail("itscreen").catch(() => {});
|
||||||
|
setMsg(`Service ${action} done. Current state: ${j.active || "unknown"}`);
|
||||||
|
} catch (e) {
|
||||||
|
setMsg(e.message || String(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(action, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderItscreenDetail(service) {
|
||||||
|
const cfg = state.itscreenAddon.cfg || {};
|
||||||
|
const login = state.itscreenAddon.login || {};
|
||||||
|
const reg = state.itscreenAddon.registration || { configured: false };
|
||||||
|
|
||||||
|
const deviceId = (cfg.deviceId || state.health?.hostname || "unknown").toString();
|
||||||
|
|
||||||
|
document.getElementById("viewTitle").textContent = service.title;
|
||||||
|
document.getElementById("viewSub").textContent = service.desc || "";
|
||||||
|
document.getElementById("viewActions").innerHTML =
|
||||||
|
`<button class="primary" onclick="window.__itscreenRefresh()">Refresh</button>`;
|
||||||
|
|
||||||
|
document.getElementById("view").innerHTML = `
|
||||||
|
<div class="stack">
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Service status</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Active</div><b class="mono">${esc(service.status?.active || "-")}</b>
|
||||||
|
<div>Started</div><b class="mono">${esc(service.status?.started_at || "-")}</b>
|
||||||
|
<div>State</div><b class="mono">${esc(service.status?.summary || "-")}</b>
|
||||||
|
<div>Running</div><b class="mono">${esc(service.status?.running_for_text || "-")}</b>
|
||||||
|
<div>Unit file</div><b class="mono">${esc(service.status?.unit_file_state || "-")}</b>
|
||||||
|
<div>Unit</div><b class="mono">${esc(service.unit || "-")}</b>
|
||||||
|
</div>
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Start", "", "window.__itscreenStart()", "start", "Starting...")}
|
||||||
|
${btn("Stop", "danger", "window.__itscreenStop()", "stop", "Stopping...")}
|
||||||
|
${btn("Restart", "primary", "window.__itscreenRestart()", "restart", "Restarting...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Registration</div>
|
||||||
|
<div class="kv">
|
||||||
|
<div>Configured</div><b class="mono">${esc(reg.configured ? "yes" : "no")}</b>
|
||||||
|
<div>Device ID</div><b class="mono">${esc(deviceId)}</b>
|
||||||
|
<div>Server</div><b class="mono">${esc(cfg.server || "-")}</b>
|
||||||
|
<div>Username</div><b class="mono">${esc(cfg.username || "-")}</b>
|
||||||
|
<div>Password</div><b class="mono">${esc(cfg.password ? "******" : "-")}</b>
|
||||||
|
<div>Token</div><b class="mono">${esc(cfg.token || "-")}</b>
|
||||||
|
<div>Namespace</div><b class="mono">${esc(cfg.topicNamespace || "-")}</b>
|
||||||
|
<div>Login</div><b class="mono">${esc(login.ok ? "ok" : "not ok")}</b>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Server</div>
|
||||||
|
<input id="its_server" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.server || "")}" placeholder="rest.dev.it-screen.com">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Username</div>
|
||||||
|
<input id="its_user" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.username || "")}" placeholder="device_xxxxx">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Password</div>
|
||||||
|
<input id="its_pass" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.password || "")}" placeholder="device password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:12px">
|
||||||
|
<div class="small">Token</div>
|
||||||
|
<input id="its_token" class="mono" style="width:100%;padding:11px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.04);color:#fff" value="${esc(cfg.token || "")}" placeholder="95687">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="btns" style="margin-top:14px">
|
||||||
|
${btn("Login", "", "window.__itscreenLogin()", "login", "Working...")}
|
||||||
|
${btn("Refresh registration", "", "window.__itscreenRefresh()", "refresh", "Working...")}
|
||||||
|
${btn("Save registration", "primary", "window.__itscreenRegister()", "register", "Saving...")}
|
||||||
|
${btn("Clear registration", "danger", "window.__itscreenClear()", "clear", "Clearing...")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panelTitle">Message</div>
|
||||||
|
<div class="small mono">${esc(state.itscreenAddon.message || "Ready")}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevLoadTabData = ui.loadTabData.bind(ui);
|
||||||
|
const prevRefreshDetail = ui.refreshDetail ? ui.refreshDetail.bind(ui) : async function(){};
|
||||||
|
const prevRender = ui.render.bind(ui);
|
||||||
|
|
||||||
|
ui.loadTabData = async function () {
|
||||||
|
if (state.tab === "itscreen") {
|
||||||
|
await ui.loadDetail("itscreen");
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevLoadTabData();
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.refreshDetail = async function () {
|
||||||
|
if (state.tab === "itscreen") {
|
||||||
|
await ui.loadDetail("itscreen");
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
ui.render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRefreshDetail();
|
||||||
|
};
|
||||||
|
window.refreshDetail = ui.refreshDetail;
|
||||||
|
|
||||||
|
ui.render = function () {
|
||||||
|
if (state.tab === "itscreen" && state.detail?.service?.key === "itscreen") {
|
||||||
|
renderItscreenDetail(state.detail.service);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return prevRender();
|
||||||
|
};
|
||||||
|
window.render = ui.render;
|
||||||
|
|
||||||
|
window.__itscreenRefresh = refreshRemote;
|
||||||
|
window.__itscreenLogin = doLogin;
|
||||||
|
window.__itscreenRegister = doRegister;
|
||||||
|
window.__itscreenClear = doClear;
|
||||||
|
window.__itscreenRestart = () => serviceAction("restart");
|
||||||
|
window.__itscreenStop = () => serviceAction("stop");
|
||||||
|
window.__itscreenStart = () => serviceAction("start");
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
|
try {
|
||||||
|
await loadConfigOnly().catch(() => {});
|
||||||
|
if (state.tab === "itscreen") ui.render();
|
||||||
|
} catch (_) {}
|
||||||
|
}, 0);
|
||||||
|
})();
|
||||||
|
JS
|
||||||
|
|
||||||
|
echo "[5/6] restart"
|
||||||
|
systemctl restart "$SERVICE"
|
||||||
|
|
||||||
|
echo "[6/6] done"
|
||||||
|
echo "Installed backend: $ADDON_BACK/itscreen.js"
|
||||||
|
echo "Installed frontend: $ADDON_FRONT/itscreen.js"
|
||||||
|
echo "Restarted: $SERVICE"
|
||||||
File diff suppressed because it is too large
Load Diff
|
|
@ -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