PreProd stable release (baseline before WiFi changes)

This commit is contained in:
Andrei Smaliak 2026-03-22 14:32:05 +04:00
parent 5914ca217f
commit 172f9787eb
33 changed files with 3321 additions and 3408 deletions

View File

@ -0,0 +1 @@
8702730634:AAGkK557HdfTmIUEWa-Ai3oVyfmyj5tdqGc

View File

@ -1,78 +0,0 @@
# IOMATEX Stage0 — шпаргалка (что сделано)
1. **Логирование Stage0**
- Ведём лог в `/var/log/iomatex-stage0.log`.
2. **PATH фикс глобально**
- Создан `/etc/profile.d/99-iomatex-path.sh` с системным PATH.
3. **APT источники**
- Убран шум `bullseye-backports` из `/etc/apt/sources.list`.
- Удалены backports-листы из `/etc/apt/sources.list.d/`.
4. **APT update**
- Выполнен `apt-get update`.
5. **Базовые пакеты (минимальный набор для поддержки)**
- Установлены: `ca-certificates curl wget sudo openssh-server iproute2 net-tools tzdata htop mc nano rsync checkinstall xz-utils unzip git jq`
- (В v2 также: `procps dos2unix`)
6. **Таймзона**
- Установлена `Asia/Dubai` (`/etc/localtime` + `dpkg-reconfigure tzdata`).
7. **Пользователи (production-структура)**
- Создан/проверен `iomatex` (админ, в группе `sudo`).
- Создан/проверен `itscreen` (runtime user).
- (В v2 добавлен `zigbee2mqtt` (runtime user).)
- `itscreen` добавлен в группы `video,input,render`.
- `iomatex` добавлен в `adm,systemd-journal` (и при необходимости в аппаратные группы).
8. **Hardening vendor user**
- `youngfeel` НЕ удаляем на Stage0.
- (В v2) `youngfeel`: пароль заблокирован, shell отключён, из `sudo` убран.
9. **Структура каталогов /opt**
- Создано:
- `/opt/itscreen/{bin,data,logs}`
- `/opt/iomatex/{bin,conf,logs}`
- (В v2) `/opt/zigbee2mqtt/{app,data,logs}`
- Выставлены владельцы/права на каталоги.
10. **Qt runtime зависимости**
- Установлены библиотеки для Qt/X11 (xcb) и EGL/DRM (conservative set).
11. **SSH**
- `ssh` включён и перезапущен.
12. **Device ID + hostname + branding**
- Device ID хранится в `/userdata/device-id` (создаётся, если нет).
- `hostname` = `g-box-xxxx`.
- `PrettyHostname` = `iomatex@g-box-xxxx`.
- Обновлён `/etc/hosts` строкой `127.0.1.1 <device-id>`.
13. **Cockpit**
- Установлен `cockpit`.
- Включён `cockpit.socket`.
- Добавлен баннер `/etc/issue.cockpit` + конфиг `/etc/cockpit/cockpit.conf`.
- Обновлён `/etc/motd`.
14. **Local MQTT broker (Mosquitto)**
- Установлены `mosquitto` и `mosquitto-clients`.
- Создан основной конфиг `/etc/mosquitto/mosquitto.conf`.
- Приведён `conf.d` к виду без дублирующих `persistence*`.
- Создан MQTT пользователь (логин/пароль) в `/etc/mosquitto/passwd`:
- user: `iomatex`
- pass: `iomatex`
- Включён и перезапущен `mosquitto`, проверка listen `:1883`.
- Создано описание `/etc/iomatex-mqtt-readme.txt`.
- (В v2) Cloud bridge шаблон создан, но **выключен по умолчанию**.
15. **Stage1.5 (опционально, если /userdata смонтирован)**
- Создан swap `/userdata/swapfile` (1GB) + запись в `/etc/fstab`.
- Настроен `vm.swappiness=10`.
- Миграция логов в `/userdata/var-log` и bind-mount в `/var/log`.
- Ограничены размеры journald (`/etc/systemd/journald.conf.d/99-iomatex.conf`).
16. **Финальный summary**
- Печать параметров (hostname, IP, Cockpit URL, MQTT URL, layout /opt) + рекомендация reboot.

View File

@ -8,6 +8,8 @@ LOG="/var/log/iomatex-stage0_1.log"
mkdir -p /var/log >/dev/null 2>&1 || true
APT_UPDATED=0
WRITE_CHANGED=0
DEVICE_ID_FILE="/userdata/device-id"
DEVICE_ID_RE='^g-box-[a-f0-9]{8}$'
log() {
local line="[$(date -u +'%F %T UTC')] $*"
@ -56,6 +58,52 @@ write_if_changed() {
return 0
}
resolve_edge_name() {
local value=""
if [ -f "$DEVICE_ID_FILE" ]; then
value="$(tr -d ' \n\r' < "$DEVICE_ID_FILE" 2>/dev/null || true)"
fi
if printf '%s\n' "${value:-}" | grep -Eq "$DEVICE_ID_RE"; then
printf '%s\n' "$value"
return 0
fi
value="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
value="${value%%.*}"
if printf '%s\n' "${value:-}" | grep -Eq "$DEVICE_ID_RE"; then
printf '%s\n' "$value"
return 0
fi
printf 'g-box-%s\n' "$(cat /proc/sys/kernel/random/uuid | tr -d '-' | cut -c1-8)"
}
ensure_edge_name() {
local edge_name brand_host
edge_name="$(resolve_edge_name)"
mkdir -p "$(dirname "$DEVICE_ID_FILE")"
printf '%s\n' "$edge_name" >"$DEVICE_ID_FILE"
chmod 0644 "$DEVICE_ID_FILE" 2>/dev/null || true
printf '%s\n' "$edge_name" >/etc/hostname
if have hostnamectl; then
hostnamectl set-hostname "$edge_name" || true
else
hostname "$edge_name" || true
fi
brand_host="iomatex@${edge_name}"
if have hostnamectl; then
hostnamectl set-hostname "$brand_host" --pretty || true
fi
if grep -qE '^127\.0\.1\.1' /etc/hosts; then
sed -i "s/^127\.0\.1\.1.*/127.0.1.1 $edge_name/" /etc/hosts
else
echo "127.0.1.1 $edge_name" >> /etc/hosts
fi
log "Hostname set to: $edge_name (pretty: $brand_host) source: $DEVICE_ID_FILE"
}
package_installed() {
dpkg-query -W -f='${Status}\n' "$1" 2>/dev/null | grep -qx 'install ok installed'
}
@ -85,8 +133,21 @@ apt_install_missing() {
return 0
fi
log "RUN: dpkg --configure -a || true"
dpkg --configure -a || true
soft_run "APT repair (install -f)" 900 \
/usr/bin/env DEBIAN_FRONTEND=noninteractive \
/usr/bin/apt-get -y \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
install -f
apt_update_if_needed
run_long "Install packages" 1800 /usr/bin/apt-get install -y "${missing[@]}"
run_long "Install packages" 1800 \
/usr/bin/env DEBIAN_FRONTEND=noninteractive \
/usr/bin/apt-get -y \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
install "${missing[@]}"
}
apt_remove_if_installed() {
@ -271,6 +332,8 @@ apt_install_missing \
jq \
procps \
dos2unix \
logrotate \
rsyslog \
network-manager \
policykit-1
@ -411,112 +474,21 @@ passwd "$u"
EOF
# -------------------------
# Step 9: LightDM autologin -> iomatex (NO restart here)
# -------------------------
step "LightDM: set autologin-user=iomatex (apply after reboot; no screen restart now)"
if [ -f /etc/lightdm/lightdm.conf ]; then
backup_if_exists /etc/lightdm/lightdm.conf
if grep -qE '^[[:space:]]*autologin-user[[:space:]]*=' /etc/lightdm/lightdm.conf; then
sed -i -E "s@^[[:space:]]*autologin-user[[:space:]]*=.*@autologin-user=${IOM_USER}@g" /etc/lightdm/lightdm.conf
else
if ! grep -qE '^\[Seat:\*\]' /etc/lightdm/lightdm.conf; then
printf "\n[Seat:*]\n" >> /etc/lightdm/lightdm.conf
fi
echo "autologin-user=${IOM_USER}" >> /etc/lightdm/lightdm.conf
fi
if grep -qE '^[[:space:]]*autologin-user-timeout[[:space:]]*=' /etc/lightdm/lightdm.conf; then
sed -i -E "s@^[[:space:]]*autologin-user-timeout[[:space:]]*=.*@autologin-user-timeout=0@g" /etc/lightdm/lightdm.conf
else
echo "autologin-user-timeout=0" >> /etc/lightdm/lightdm.conf
fi
log "LightDM autologin set to: ${IOM_USER} (timeout=0)"
else
log "LightDM config not found: /etc/lightdm/lightdm.conf (skipped)"
fi
# -------------------------
# Step 10: Chromium profile lock cleanup (safe)
# -------------------------
step "Chromium: cleanup stale Singleton locks for iomatex (safe; does not delete profile)"
IOM_HOME="$(getent passwd "$IOM_USER" | cut -d: -f6)"
[ -n "${IOM_HOME:-}" ] || IOM_HOME="/home/${IOM_USER}"
soft_run "Remove chromium Singleton* locks (iomatex)" 20 /bin/bash -lc "rm -f '${IOM_HOME}/.config/chromium/Singleton'* 2>/dev/null || true"
# -------------------------
# Step 11: /opt layout (canonical)
# -------------------------
step "Create canonical /opt layout"
install -d -o "$ITS_USER" -g "$ITS_USER" -m 0755 /opt/itscreen /opt/itscreen/bin /opt/itscreen/data /opt/itscreen/logs
install -d -o "$Z2M_USER" -g "$Z2M_USER" -m 0755 /opt/zigbee2mqtt /opt/zigbee2mqtt/app /opt/zigbee2mqtt/data /opt/zigbee2mqtt/logs
install -d -o root -g root -m 0755 /opt/iomatex /opt/iomatex/bin /opt/iomatex/conf /opt/iomatex/logs
install -d -o "$ITS_USER" -g "$ITS_USER" -m 0755 /var/log/itscreen /var/lib/itscreen
install -d -o "$Z2M_USER" -g "$Z2M_USER" -m 0755 /var/log/zigbee2mqtt /var/lib/zigbee2mqtt
# -------------------------
# Step 12: Qt runtime deps (KEEP EXACT LIST)
# -------------------------
step "Install Qt runtime dependencies (X11/xcb + common EGL/DRM libs)"
apt_install_missing \
libgl1 libegl1 libgbm1 libdrm2 libinput10 \
libx11-6 libxcb1 libxkbcommon0 libxkbcommon-x11-0 \
libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-render-util0 \
libxcb-xinerama0 libxcb-xkb1 libxcb-randr0 libxcb-shape0 libxcb-shm0 \
libfontconfig1 libfreetype6 libdbus-1-3 || true
# -------------------------
# Step 13: SSH
# Step 9: SSH
# -------------------------
step "Enable SSH"
systemctl_enable_now_safe ssh
# -------------------------
# Step 14: Hostname (8 hex) + branding
# Step 10: Cockpit baseline + security reminder
# -------------------------
step "Set hostname (8 hex) + PrettyHostname (iomatex@g-box-xxxxxxxx)"
DEVICE_ID_FILE="/userdata/device-id"
DEVICE_ID=""
DEVICE_ID_RE='^g-box-[a-f0-9]{8}$'
if [ -f "$DEVICE_ID_FILE" ]; then
DEVICE_ID="$(tr -d ' \n\r' < "$DEVICE_ID_FILE")"
fi
if ! printf '%s\n' "${DEVICE_ID:-}" | grep -Eq "$DEVICE_ID_RE"; then
[ -n "${DEVICE_ID:-}" ] && log "Invalid device id in ${DEVICE_ID_FILE}: '${DEVICE_ID}' -> regenerating"
DEVICE_ID="g-box-$(cat /proc/sys/kernel/random/uuid | tr -d '-' | cut -c1-8)"
mkdir -p /userdata
echo "$DEVICE_ID" >"$DEVICE_ID_FILE"
chmod 0644 "$DEVICE_ID_FILE" || true
fi
echo "$DEVICE_ID" >/etc/hostname
if have hostnamectl; then
hostnamectl set-hostname "$DEVICE_ID" || true
else
hostname "$DEVICE_ID" || true
fi
BRAND_HOST="iomatex@${DEVICE_ID}"
if have hostnamectl; then
hostnamectl set-hostname "$BRAND_HOST" --pretty || true
fi
if grep -qE '^127\.0\.1\.1' /etc/hosts; then
sed -i "s/^127\.0\.1\.1.*/127.0.1.1 $DEVICE_ID/" /etc/hosts
else
echo "127.0.1.1 $DEVICE_ID" >> /etc/hosts
fi
log "Hostname set to: $DEVICE_ID (pretty: $BRAND_HOST) source: $DEVICE_ID_FILE"
step "Set persistent edge name"
ensure_edge_name
# -------------------------
# Step 15: Cockpit + banner branding + password reminder
# Step 10: Cockpit baseline + security reminder
# -------------------------
step "Install + enable Cockpit + branded banner + security reminder"
step "Install + enable Cockpit baseline + security reminder"
apt_install_missing cockpit cockpit-networkmanager cockpit-storaged cockpit-pcp network-manager
systemctl_enable_now_safe NetworkManager
@ -530,9 +502,6 @@ cat >/etc/issue.cockpit <<EOF
IOMATEX EDGE
======================================================
Device : ${BRAND_HOST}
Hostname : ${DEVICE_ID}
⚠ SECURITY NOTICE
Default password must be changed immediately.
@ -548,15 +517,8 @@ Policy:
Cockpit : https://${IP_MAIN}:9090
Runtime users:
- itscreen (app)
- zigbee2mqtt (zigbee)
Wi-Fi:
- Use command: sudo nmtui (manage Wi-Fi networks)
Notes:
- Device ID file : ${DEVICE_ID_FILE}
======================================================
EOF
chmod 0644 /etc/issue.cockpit
@ -570,7 +532,7 @@ soft_run "Enable cockpit.socket" 60 /bin/systemctl enable --now cockpit.socket
cat >/etc/motd <<EOF
======================================================
IOMATEX EDGE :: ${BRAND_HOST}
IOMATEX EDGE
======================================================
Cockpit: https://${IP_MAIN}:9090
SECURITY: Change admin password (sudo iomatex-passwd)
@ -578,9 +540,9 @@ Wi-Fi: sudo nmtui
EOF
# -------------------------
# Step 15.5: Wi-Fi industrial hardening (AE region + disable P2P + NM only)
# Step 10.5: Wi-Fi industrial hardening (AE region + disable P2P + prefer wlan0 for client Wi-Fi)
# -------------------------
step "Wi-Fi hardening: set region AE + disable system wpa_supplicant + ignore p2p0"
step "Wi-Fi hardening: set region AE + disable P2P + keep p2p0 out of NetworkManager"
apt_install_missing iw wireless-regdb || true
@ -588,6 +550,12 @@ if command -v iw >/dev/null 2>&1; then
iw reg set AE || true
fi
if [ -e /sys/class/net/p2p0 ]; then
log "Detected kernel-created P2P interface: p2p0"
else
log "P2P interface p2p0 not present at install time (policy will still be enforced)"
fi
mkdir -p /etc/modprobe.d
write_if_changed /etc/modprobe.d/cfg80211.conf 0644 <<'EOF'
options cfg80211 ieee80211_regdom=AE
@ -598,31 +566,117 @@ soft_run "Disable system wpa_supplicant" 30 /bin/systemctl disable --now wpa_sup
mkdir -p /etc/NetworkManager
mkdir -p /etc/NetworkManager/conf.d
NM_CFG_CHANGED=0
write_if_changed /etc/NetworkManager/conf.d/10-iomatex-main.conf 0644 root root <<'EOF'
for legacy_nm_cfg in \
/etc/NetworkManager/conf.d/10-iomatex-main.conf \
/etc/NetworkManager/conf.d/20-iomatex-disable-p2p.conf \
/etc/NetworkManager/conf.d/99-iomatex-wifi.conf
do
if [ -f "$legacy_nm_cfg" ]; then
rm -f "$legacy_nm_cfg"
NM_CFG_CHANGED=1
log "Removed legacy NetworkManager Wi-Fi policy: ${legacy_nm_cfg}"
fi
done
write_if_changed /etc/NetworkManager/conf.d/10-iomatex-disable-p2p.conf 0644 root root <<'EOF'
[main]
plugins=keyfile
[device]
wifi.scan-rand-mac-address=no
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
NM_CFG_CHANGED=1
fi
write_if_changed /etc/NetworkManager/conf.d/99-iomatex-wifi.conf 0644 root root <<'EOF'
[keyfile]
unmanaged-devices=interface-name:p2p0;interface-name:p2p-dev-p2p0;interface-name:p2p-dev-wlan0
[device]
wifi.scan-rand-mac-address=no
[connection]
wifi.powersave=2
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
NM_CFG_CHANGED=1
log "Updated NetworkManager Wi-Fi baseline policy: /etc/NetworkManager/conf.d/10-iomatex-disable-p2p.conf"
else
log "NetworkManager Wi-Fi baseline policy already configured"
fi
if [ "$NM_CFG_CHANGED" -eq 1 ]; then
WPA_CFG_CHANGED=0
WPA_CFGS=()
[ -f /etc/wpa_supplicant.conf ] && WPA_CFGS+=(/etc/wpa_supplicant.conf)
[ -f /etc/wpa_supplicant/wpa_supplicant.conf ] && WPA_CFGS+=(/etc/wpa_supplicant/wpa_supplicant.conf)
if [ "${#WPA_CFGS[@]}" -eq 0 ]; then
WPA_CFGS+=(/etc/wpa_supplicant.conf)
fi
for WPA_CFG in "${WPA_CFGS[@]}"; do
tmp_wpa="$(mktemp)"
if [ -f "$WPA_CFG" ]; then
awk '
BEGIN { done=0 }
/^[[:space:]]*p2p_disabled[[:space:]]*=/ {
if (!done) {
print "p2p_disabled=1"
done=1
}
next
}
{ print }
END {
if (!done) {
print "p2p_disabled=1"
}
}
' "$WPA_CFG" >"$tmp_wpa"
else
printf 'p2p_disabled=1\n' >"$tmp_wpa"
fi
if [ -f "$WPA_CFG" ] && cmp -s "$tmp_wpa" "$WPA_CFG"; then
rm -f "$tmp_wpa"
log "wpa_supplicant P2P disable already configured: ${WPA_CFG}"
else
install -D -o root -g root -m 0644 "$tmp_wpa" "$WPA_CFG"
rm -f "$tmp_wpa"
WPA_CFG_CHANGED=1
log "Updated wpa_supplicant P2P disable policy: ${WPA_CFG}"
fi
done
PROFILE_CFG_CHANGED=0
PROFILE_FIX_COUNT=0
shopt -s nullglob
for nm_profile in /etc/NetworkManager/system-connections/*.nmconnection; do
if grep -Eq '^[[:space:]]*interface-name[[:space:]]*=[[:space:]]*p2p0[[:space:]]*$' "$nm_profile"; then
tmp_profile="$(mktemp)"
awk '
/^[[:space:]]*interface-name[[:space:]]*=[[:space:]]*p2p0[[:space:]]*$/ { next }
{ print }
' "$nm_profile" >"$tmp_profile"
if ! cmp -s "$tmp_profile" "$nm_profile"; then
backup_if_exists "$nm_profile"
install -o root -g root -m 0600 "$tmp_profile" "$nm_profile"
PROFILE_CFG_CHANGED=1
PROFILE_FIX_COUNT=$((PROFILE_FIX_COUNT+1))
log "Removed interface-name=p2p0 from NetworkManager profile: $(basename "$nm_profile")"
fi
rm -f "$tmp_profile"
fi
done
shopt -u nullglob
if [ "$PROFILE_FIX_COUNT" -eq 0 ]; then
log "No NetworkManager profiles pinned to p2p0 were found"
else
log "Fixed NetworkManager profiles pinned to p2p0: ${PROFILE_FIX_COUNT}"
fi
if [ "$NM_CFG_CHANGED" -eq 1 ] || [ "$WPA_CFG_CHANGED" -eq 1 ] || [ "$PROFILE_CFG_CHANGED" -eq 1 ]; then
soft_run "Restart NetworkManager" 30 /bin/systemctl restart NetworkManager
else
log "NetworkManager restart not required for P2P policy"
fi
# -------------------------
# Step 15.6: Fix Wi-Fi persistence after reboot (SYSTEM connections) - Debian 11 safe
# Step 10.6: Fix Wi-Fi persistence after reboot (SYSTEM connections) - Debian 11 safe
# -------------------------
step "NetworkManager: enforce SYSTEM Wi-Fi profiles (polkit rule + convert user:* profiles) (Debian 11-safe)"
@ -676,7 +730,7 @@ log "Wi-Fi hardening applied (Region=${REG_NOW:-unknown}, P2P ignored, NM-only m
log "Wi-Fi persistence fix applied (SYSTEM profiles enforced + autoconnect-priority=100)"
# -------------------------
# Step 15.7: Wi-Fi bring-up (connect by UUID, late trigger, print status) - Debian 11 safe
# Step 10.7: Wi-Fi bring-up (connect by UUID, late trigger, print status) - Debian 11 safe
# -------------------------
step "Wi-Fi bring-up (connect by UUID, late trigger, print status) (Debian 11-safe)"
@ -731,12 +785,12 @@ log "--- WIFI STATUS AFTER ---"
nmcli -f DEVICE,TYPE,STATE,CONNECTION dev >>"$LOG" 2>&1 || true
nmcli -f GENERAL.STATE,GENERAL.REASON,GENERAL.CONNECTION dev show "$WIFI_IFACE" >>"$LOG" 2>&1 || true
# -------------------------
# Step 16: /userdata usage (SAFE cold-boot)
# Step 11: /userdata usage (SAFE cold-boot)
# - NO bind-mount /var/log
# - NO fstab entries that can block boot
# - swap + app logs are enabled via systemd oneshot after /userdata is mounted
# - swap + generic app logs are enabled via systemd oneshot after /userdata is mounted
# -------------------------
step "Userdata SAFE: systemd bootstrap (swap on /userdata + persistent app logs) + journald limits"
step "Userdata SAFE: systemd bootstrap (swap on /userdata + generic logs) + log overflow protection"
mkdir -p /etc/systemd/system /usr/local/sbin
@ -746,26 +800,6 @@ set -euo pipefail
log() { echo "[iomatex-userdata-bootstrap] $*"; }
ensure_link_target() {
local link_path="$1"
local target_path="$2"
if [ -L "$link_path" ]; then
if [ "$(readlink "$link_path" 2>/dev/null || true)" = "$target_path" ]; then
return 0
fi
rm -f "$link_path"
ln -s "$target_path" "$link_path"
return 0
fi
if [ -e "$link_path" ]; then
rm -rf "$link_path"
fi
ln -s "$target_path" "$link_path"
}
# Must be a mountpoint to proceed (prevents boot blocks)
if ! mountpoint -q /userdata; then
log "SKIP: /userdata is not mounted"
@ -793,24 +827,10 @@ fi
echo "vm.swappiness=10" >/etc/sysctl.d/99-iomatex-swap.conf
sysctl -p /etc/sysctl.d/99-iomatex-swap.conf >/dev/null 2>&1 || true
# 2) Persistent app logs on /userdata (NO bind of /var/log)
mkdir -p /userdata/logs/{itscreen,zigbee2mqtt,iomatex}
chown -R itscreen:itscreen /userdata/logs/itscreen 2>/dev/null || true
chown -R zigbee2mqtt:zigbee2mqtt /userdata/logs/zigbee2mqtt 2>/dev/null || true
# 2) Generic app log root on /userdata (apps may opt in later)
mkdir -p /userdata/logs/iomatex
# Ensure classic dirs exist
mkdir -p /var/log/itscreen /var/log/zigbee2mqtt /opt/itscreen/logs /opt/zigbee2mqtt/logs /opt/iomatex/logs
# Link /opt/*/logs -> /userdata/logs/* (stable for your apps)
ensure_link_target /opt/itscreen/logs /userdata/logs/itscreen
ensure_link_target /opt/zigbee2mqtt/logs /userdata/logs/zigbee2mqtt
ensure_link_target /opt/iomatex/logs /userdata/logs/iomatex
# Optional: link /var/log/* (so existing tooling still sees logs)
ensure_link_target /var/log/itscreen /userdata/logs/itscreen
ensure_link_target /var/log/zigbee2mqtt /userdata/logs/zigbee2mqtt
log "OK: swap + persistent logs configured (cold-boot safe)"
log "OK: swap + generic userdata log root configured (cold-boot safe)"
exit 0
EOF
@ -847,8 +867,9 @@ JOURNALD_CFG_CHANGED=0
write_if_changed /etc/systemd/journald.conf.d/99-iomatex.conf 0644 <<'EOF'
[Journal]
SystemMaxUse=100M
RuntimeMaxUse=50M
SystemKeepFree=50M
MaxRetentionSec=7day
Compress=yes
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
JOURNALD_CFG_CHANGED=1
@ -857,6 +878,175 @@ if [ "$JOURNALD_CFG_CHANGED" -eq 1 ]; then
soft_run "Restart systemd-journald" 30 /bin/systemctl restart systemd-journald
fi
# logrotate baseline (some EDGE images do not ship it by default)
soft_run "Enable logrotate.timer" 20 /bin/systemctl enable --now logrotate.timer
RSYSLOG_ROTATE_CHANGED=0
write_if_changed /etc/logrotate.d/rsyslog 0644 <<'EOF'
/var/log/syslog
/var/log/mail.info
/var/log/mail.warn
/var/log/mail.err
/var/log/mail.log
/var/log/daemon.log
/var/log/kern.log
/var/log/auth.log
/var/log/user.log
/var/log/lpr.log
/var/log/cron.log
/var/log/debug
/var/log/messages
{
daily
rotate 3
size 50M
compress
delaycompress
missingok
notifempty
copytruncate
}
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
RSYSLOG_ROTATE_CHANGED=1
fi
NM_LOGGING_CHANGED=0
mkdir -p /etc/NetworkManager/conf.d
write_if_changed /etc/NetworkManager/conf.d/logging.conf 0644 root root <<'EOF'
[logging]
level=INFO
domains=DEFAULT
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
NM_LOGGING_CHANGED=1
fi
if [ "$NM_LOGGING_CHANGED" -eq 1 ]; then
soft_run "Restart NetworkManager (logging baseline)" 30 /bin/systemctl restart NetworkManager
fi
MOSQ_LOG_CFG_CHANGED=0
mkdir -p /etc/mosquitto/conf.d /var/log/mosquitto
touch /var/log/mosquitto/mosquitto.log
chown mosquitto:mosquitto /var/log/mosquitto /var/log/mosquitto/mosquitto.log 2>/dev/null || true
chmod 0750 /var/log/mosquitto 2>/dev/null || true
chmod 0640 /var/log/mosquitto/mosquitto.log 2>/dev/null || true
write_if_changed /etc/mosquitto/conf.d/90-iomatex-logging.conf 0644 root root <<'EOF'
# IOMATEX production logging baseline
log_dest file /var/log/mosquitto/mosquitto.log
log_type error
log_type warning
log_type notice
log_type information
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
MOSQ_LOG_CFG_CHANGED=1
fi
MOSQ_ROTATE_CHANGED=0
write_if_changed /etc/logrotate.d/mosquitto-iomatex 0644 <<'EOF'
/var/log/mosquitto/mosquitto.log
{
daily
rotate 7
size 20M
compress
delaycompress
missingok
notifempty
copytruncate
create 0640 mosquitto mosquitto
}
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
MOSQ_ROTATE_CHANGED=1
fi
write_if_changed /usr/local/sbin/iomatex-log-watchdog 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
THRESHOLD="${1:-85}"
ROOT_MOUNT="${2:-/}"
usage_pct="$(df -P "$ROOT_MOUNT" 2>/dev/null | awk 'NR==2 {gsub(/%/, "", $5); print $5}')"
[[ "${usage_pct:-}" =~ ^[0-9]+$ ]] || exit 0
if (( usage_pct < THRESHOLD )); then
exit 0
fi
logger -t iomatex-log-watchdog "disk usage ${usage_pct}% on ${ROOT_MOUNT}, starting emergency log cleanup"
if command -v journalctl >/dev/null 2>&1; then
journalctl --vacuum-size=80M >/dev/null 2>&1 || true
journalctl --vacuum-time=7d >/dev/null 2>&1 || true
fi
if command -v logrotate >/dev/null 2>&1; then
logrotate -f /etc/logrotate.conf >/dev/null 2>&1 || true
fi
for log_path in \
/var/log/syslog \
/var/log/messages \
/var/log/daemon.log \
/var/log/debug \
/var/log/kern.log \
/var/log/auth.log \
/var/log/mosquitto/mosquitto.log
do
[ -f "$log_path" ] || continue
: > "$log_path" || true
done
logger -t iomatex-log-watchdog "emergency log cleanup finished"
exit 0
EOF
WATCHDOG_UNIT_CHANGED=0
write_if_changed /etc/systemd/system/iomatex-log-watchdog.service 0644 <<'EOF'
[Unit]
Description=IOMATEX log overflow watchdog
After=local-fs.target
Wants=local-fs.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-log-watchdog 85 /
TimeoutStartSec=60
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
WATCHDOG_UNIT_CHANGED=1
fi
write_if_changed /etc/systemd/system/iomatex-log-watchdog.timer 0644 <<'EOF'
[Unit]
Description=Run IOMATEX log overflow watchdog every 10 minutes
[Timer]
OnBootSec=5min
OnUnitActiveSec=10min
Persistent=true
[Install]
WantedBy=timers.target
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
WATCHDOG_UNIT_CHANGED=1
fi
if [ "$WATCHDOG_UNIT_CHANGED" -eq 1 ]; then
soft_run "systemd daemon-reload (log watchdog)" 20 /bin/systemctl daemon-reload
fi
soft_run "Enable iomatex-log-watchdog.timer" 20 /bin/systemctl enable --now iomatex-log-watchdog.timer
soft_run "Run iomatex-log-watchdog once (best-effort)" 30 /bin/systemctl start iomatex-log-watchdog.service
if [ "$MOSQ_LOG_CFG_CHANGED" -eq 1 ]; then
soft_run "Restart mosquitto (production logging baseline)" 30 /bin/systemctl restart mosquitto
fi
# Run bootstrap once now (best-effort)
soft_run "Run userdata bootstrap now (best-effort)" 30 /bin/systemctl start iomatex-userdata-bootstrap.service
@ -865,7 +1055,7 @@ soft_run "Run userdata bootstrap now (best-effort)" 30 /bin/systemctl start ioma
# -------------------------
step "Finish (health summary)"
log "=== IOMATEX STAGE0_1 v3.2 COMPLETE ==="
log "Hostname: $(hostname) (pretty: ${BRAND_HOST})"
log "Hostname preserved: $(hostname)"
log "User: iomatex (password MUST be changed on first login)"
log "Cockpit: https://${IP_MAIN}:9090"
log "Log file: $LOG"
@ -877,9 +1067,7 @@ echo "======================================================"
echo " IOMATEX EDGE :: STAGE0_1 COMPLETE"
echo "======================================================"
echo
echo " Hostname : $(hostname)"
echo " Pretty hostname : ${BRAND_HOST}"
echo " Device ID file : ${DEVICE_ID_FILE}"
echo " Hostname : $(hostname) (preserved; not set by stage_env)"
echo
echo " Users:"
echo " - iomatex (admin, sudo) -> password MUST be changed on first login"
@ -890,8 +1078,6 @@ echo " - zigbee2mqtt (runtime)"
echo " - youngfeel (hardened/disabled if existed)"
echo
echo " Password policy : minlen=8 (NO dictionary), pam_unix obscure OFF"
echo " LightDM autologin: ${IOM_USER} (applies after reboot)"
echo " Chromium: Singleton locks cleaned for ${IOM_USER}"
echo
echo " Wi-Fi region : ${REG_NOW:-unknown}"
echo " Wi-Fi persistence: SYSTEM profiles enforced (no login required)"
@ -899,18 +1085,13 @@ echo " Wi-Fi management : use command -> sudo nmtui"
echo
echo " Userdata usage (cold-boot safe):"
echo " - swap on /userdata via systemd oneshot (no fstab)"
echo " - persistent logs in /userdata/logs/* (no /var/log bind mount)"
echo " - generic userdata log root at /userdata/logs/iomatex"
echo
echo " Network IPs:"
ip -4 addr show | awk '/inet /{print " - " $2 " (" $NF ")"}' || true
echo
echo " Cockpit : https://${IP_MAIN}:9090"
echo
echo " /opt layout:"
echo " - /opt/itscreen/{bin,data,logs} (logs -> /userdata/logs/itscreen)"
echo " - /opt/zigbee2mqtt/{app,data,logs} (logs -> /userdata/logs/zigbee2mqtt)"
echo " - /opt/iomatex/{bin,conf,logs} (logs -> /userdata/logs/iomatex)"
echo
echo " Time sync:"
timedatectl status 2>/dev/null | sed -n '1,12p' || true
echo

View File

@ -12,12 +12,15 @@ ITS_WRAPPER="/usr/local/bin/itscreen-run"
ITS_SERVICE="itscreen-x11.service"
LIGHTDM_SERVICE="lightdm.service"
NM_WAIT_SERVICE="NetworkManager-wait-online.service"
IOM_USER="iomatex"
SUDOERS_FILE="/etc/sudoers.d/90-itscreen-power"
XSESSION_HOOK="/etc/X11/Xsession.d/99-iomatex-allow-itscreen"
XWRAPPER_CONFIG="/etc/X11/Xwrapper.config"
ITS_UNIT_FILE="/etc/systemd/system/${ITS_SERVICE}"
LOCK_DIR="/run/itscreen"
LOCK_FILE="${LOCK_DIR}/itscreen.lock"
DEVICE_ID_FILE="/userdata/device-id"
DEVICE_ID_RE='^g-box-[a-f0-9]{8}$'
step_n=0
@ -62,6 +65,58 @@ ensure_dir() {
install -d -m "$mode" -o "$owner" -g "$group" "$path"
}
resolve_edge_name() {
local value=""
if [[ -f "$DEVICE_ID_FILE" ]]; then
value="$(tr -d ' \n\r' < "$DEVICE_ID_FILE" 2>/dev/null || true)"
fi
if printf '%s\n' "${value:-}" | grep -Eq "$DEVICE_ID_RE"; then
printf '%s\n' "$value"
return 0
fi
value="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
value="${value%%.*}"
if printf '%s\n' "${value:-}" | grep -Eq "$DEVICE_ID_RE"; then
printf '%s\n' "$value"
return 0
fi
printf 'g-box-%s\n' "$(cat /proc/sys/kernel/random/uuid | tr -d '-' | cut -c1-8)"
}
ensure_edge_name() {
local edge_name brand_host
step "Ensure persistent edge name"
edge_name="$(resolve_edge_name)"
mkdir -p "$(dirname "$DEVICE_ID_FILE")"
if [[ ! -f "$DEVICE_ID_FILE" ]] || [[ "$(tr -d ' \n\r' < "$DEVICE_ID_FILE" 2>/dev/null || true)" != "$edge_name" ]]; then
printf '%s\n' "$edge_name" >"$DEVICE_ID_FILE"
chmod 0644 "$DEVICE_ID_FILE" || true
fi
if [[ "$(cat /etc/hostname 2>/dev/null || true)" != "$edge_name" ]]; then
printf '%s\n' "$edge_name" >/etc/hostname
fi
if command -v hostnamectl >/dev/null 2>&1; then
hostnamectl set-hostname "$edge_name" >/dev/null 2>&1 || true
else
hostname "$edge_name" >/dev/null 2>&1 || true
fi
brand_host="iomatex@${edge_name}"
if command -v hostnamectl >/dev/null 2>&1; then
hostnamectl set-hostname "$brand_host" --pretty >/dev/null 2>&1 || true
fi
if grep -qE '^127\.0\.1\.1[[:space:]]+' /etc/hosts 2>/dev/null; then
sed -i -E "s/^127\\.0\\.1\\.1[[:space:]].*/127.0.1.1 ${edge_name}/" /etc/hosts
else
printf '127.0.1.1 %s\n' "$edge_name" >>/etc/hosts
fi
log "Persistent edge name: ${edge_name} (source: ${DEVICE_ID_FILE})"
}
write_file() {
local path="$1"
local mode="$2"
@ -118,12 +173,6 @@ spinner() {
sleep 0.2
done
if [[ -t 1 ]]; then
printf "\r[OK] %s. \n" "$msg"
else
echo "[OK] $msg"
fi
if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then
tput cnorm || true
fi
@ -132,19 +181,79 @@ spinner() {
run_long() {
local msg="$1"
local timeout_s="$2"
local rc
shift 2
log "RUN: $msg :: $*"
( timeout "$timeout_s" "$@" >>"$LOG" 2>&1 ) &
local pid=$!
spinner "$pid" "$msg"
wait "$pid"
rc=$?
if [[ "$rc" -eq 0 ]]; then
if [[ -t 1 ]]; then
printf "\r[OK] %s. \n" "$msg"
else
echo "[OK] $msg"
fi
else
if [[ -t 1 ]]; then
printf "\r[FAIL:%s] %s. \n" "$rc" "$msg"
else
echo "[FAIL:$rc] $msg"
fi
fi
return "$rc"
}
soft_run() {
local msg="$1"
local timeout_s="$2"
shift 2
run_long "$msg" "$timeout_s" "$@" || true
if ! run_long "$msg" "$timeout_s" "$@"; then
warn "Soft-failed: ${msg}. See ${LOG}"
return 0
fi
}
install_packages_best_effort() {
local label="$1"
local timeout_s="$2"
shift 2
local pkg
local missing=()
local failed=()
for pkg in "$@"; do
if dpkg-query -W -f='${Status}\n' "$pkg" 2>/dev/null | grep -qx 'install ok installed'; then
continue
fi
missing+=("$pkg")
done
if [[ "${#missing[@]}" -eq 0 ]]; then
log "Packages already installed for ${label}"
return 0
fi
if run_long "$label" "$timeout_s" apt-get install -y "${missing[@]}"; then
return 0
fi
warn "${label} batch install failed; retrying packages one by one"
failed=()
for pkg in "${missing[@]}"; do
if ! soft_run "${label}: ${pkg}" 900 apt-get install -y "$pkg"; then
:
fi
if ! dpkg-query -W -f='${Status}\n' "$pkg" 2>/dev/null | grep -qx 'install ok installed'; then
failed+=("$pkg")
fi
done
if [[ "${#failed[@]}" -gt 0 ]]; then
warn "${label} missing/failed packages: ${failed[*]}"
fi
return 0
}
find_itscreen_binary() {
@ -182,6 +291,8 @@ ensure_runtime_directories() {
step "Ensure runtime directories"
ensure_dir /opt/itscreen 0755 "$ITS_USER" "$ITS_GROUP"
ensure_dir /opt/itscreen/bin 0755 "$ITS_USER" "$ITS_GROUP"
ensure_dir /opt/itscreen/data 0755 "$ITS_USER" "$ITS_GROUP"
ensure_dir /opt/itscreen/logs 0755 "$ITS_USER" "$ITS_GROUP"
ensure_dir /var/lib/itscreen 0755 "$ITS_USER" "$ITS_GROUP"
ensure_dir /var/lib/itscreen/config 0770 "$ITS_USER" "$ITS_GROUP"
ensure_dir /var/lib/itscreen/data 0770 "$ITS_USER" "$ITS_GROUP"
@ -197,13 +308,18 @@ ensure_runtime_directories() {
install_qt_packages() {
step "Install Qt runtime (exact list)"
run_long "Install Qt runtime" 1800 apt-get install -y \
install_packages_best_effort "Install Qt runtime" 1800 \
libgl1 libegl1 libgbm1 libdrm2 libinput10 \
libx11-6 libxcb1 libxkbcommon0 libxkbcommon-x11-0 \
libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-render-util0 \
libxcb-xinerama0 libxcb-xkb1 libxcb-randr0 libxcb-shape0 libxcb-shm0 \
libfontconfig1 libfreetype6 libdbus-1-3 \
libqt5webview5 \
libqt5websockets5 \
libqt5texttospeech5 \
libqt5serialbus5
soft_run "Install Qt extras" 1800 apt-get install -y \
install_packages_best_effort "Install Qt extras" 1800 \
gedit lxterminal clang qtcreator \
libqt5serialbus5-bin \
qtpositioning5-dev qml-module-qtpositioning \
@ -219,6 +335,34 @@ install_qt_packages() {
ldconfig
}
configure_lightdm_autologin() {
step "LightDM autologin for iomatex"
if ! id "$IOM_USER" >/dev/null 2>&1; then
warn "User ${IOM_USER} not found; skipping LightDM autologin"
return 0
fi
if [[ ! -f /etc/lightdm/lightdm.conf ]]; then
warn "LightDM config not found: /etc/lightdm/lightdm.conf"
return 0
fi
if grep -qE '^[[:space:]]*autologin-user[[:space:]]*=' /etc/lightdm/lightdm.conf; then
sed -i -E "s@^[[:space:]]*autologin-user[[:space:]]*=.*@autologin-user=${IOM_USER}@g" /etc/lightdm/lightdm.conf
else
if ! grep -qE '^\[Seat:\*\]' /etc/lightdm/lightdm.conf; then
printf "\n[Seat:*]\n" >> /etc/lightdm/lightdm.conf
fi
echo "autologin-user=${IOM_USER}" >> /etc/lightdm/lightdm.conf
fi
if grep -qE '^[[:space:]]*autologin-user-timeout[[:space:]]*=' /etc/lightdm/lightdm.conf; then
sed -i -E "s@^[[:space:]]*autologin-user-timeout[[:space:]]*=.*@autologin-user-timeout=0@g" /etc/lightdm/lightdm.conf
else
echo "autologin-user-timeout=0" >> /etc/lightdm/lightdm.conf
fi
}
install_itscreen_binary() {
local src
step "Install itscreen binary"
@ -272,6 +416,8 @@ Description=ITSCREEN X11 (requires LightDM)
After=lightdm.service
Wants=network-online.target
After=NetworkManager.service network-online.target
StartLimitIntervalSec=300
StartLimitBurst=3
[Service]
User=itscreen
@ -284,8 +430,6 @@ Environment=QT_QPA_PLATFORM=xcb
ExecStart=/usr/local/bin/itscreen-run
Restart=always
RestartSec=2
StartLimitIntervalSec=300
StartLimitBurst=3
[Install]
WantedBy=multi-user.target
@ -352,11 +496,13 @@ main() {
log "=== IOMATEX STAGE_3 ITSCREEN (X11 ONLY) START ==="
install_base_packages
ensure_edge_name
ensure_runtime_directories
install_qt_packages
install_itscreen_binary
install_sudoers
install_x11_access_files
configure_lightdm_autologin
install_wrapper
install_systemd_unit
enable_managed_services

View File

@ -1,10 +0,0 @@
Stage1 Result
After Stage1:
✔ Local MQTT operational
✔ Bridge auto-managed
✔ Namespace structured
✔ Watcher active
✔ Health supervision enabled
✔ Ready for IT-Screen client integration

View File

@ -1,543 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# --- Notepad++/Windows safety guards (BOM + CRLF) ---
if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then
echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2
exit 1
fi
if grep -q $'\r' "$0" 2>/dev/null; then
echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL in Notepad++." >&2
exit 1
fi
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export DEBIAN_FRONTEND=noninteractive
LOG="/var/log/iomatex-stage1-mqtt.log"
mkdir -p /var/log >/dev/null 2>&1 || true
touch "$LOG" >/dev/null 2>&1 || true
log() {
local line="[$(date -u +'%F %T UTC')] $*"
echo "$line"
echo "$line" >>"$LOG" 2>/dev/null || true
}
step_n=0
step() {
step_n=$((step_n+1))
echo
echo "=== Step ${step_n}: $* ==="
log "STEP ${step_n}: $*"
}
spinner() {
local pid="$1"
local msg="${2:-Working}"
local spin='|/-\'
local i=0
if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput civis || true; fi
while kill -0 "$pid" 2>/dev/null; do
i=$(( (i+1) % 4 ))
if [[ -t 1 ]]; then printf "\r[%c] %s" "${spin:$i:1}" "$msg"; fi
sleep 0.12
done
if [[ -t 1 ]]; then printf "\r[✓] %s\n" "$msg"; else echo "[✓] $msg"; fi
if command -v tput >/dev/null 2>&1 && [[ -t 1 ]]; then tput cnorm || true; fi
}
run_bg() { local msg="$1"; shift; ( "$@" ) & local pid=$!; spinner "$pid" "$msg"; wait "$pid"; }
need_root() { if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then echo "Run as root: sudo $0" >&2; exit 1; fi; }
need_root
ENV_FILE="/etc/iomatex/mqtt_bridge.env"
MOSQ_MAIN="/etc/mosquitto/mosquitto.conf"
MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf"
APPLY="/usr/local/sbin/iomatex-mqtt-apply"
REMOTE_SET="/usr/local/sbin/iomatex-mqtt-remote-set"
step "Install Mosquitto broker + clients"
run_bg "apt-get update" apt-get update
run_bg "install mosquitto + clients" apt-get install -y mosquitto mosquitto-clients
apt-get install -y netcat-openbsd >/dev/null 2>&1 || true
step "Create directories and base env file (DO NOT wipe existing creds)"
mkdir -p /etc/iomatex
if [[ ! -f "$ENV_FILE" ]]; then
cat >"$ENV_FILE" <<'__IOMATEX_ENV__'
# IOMATEX MQTT bridge settings (parsed as key=value, NOT sourced)
# ASCII recommended. No spaces around '='. Values may contain spaces (we do not source this file).
ENABLE_BRIDGE=0
REMOTE_HOST=
REMOTE_PORT=1883
REMOTE_TLS=0
REMOTE_USERNAME=
REMOTE_PASSWORD=
REMOTE_CLIENTID=
__IOMATEX_ENV__
chmod 600 "$ENV_FILE"
chown root:root "$ENV_FILE"
else
chmod 600 "$ENV_FILE" || true
chown root:root "$ENV_FILE" || true
fi
step "Ensure mosquitto.conf includes conf.d and write single source-of-truth listener snippet"
if ! grep -qE '^\s*include_dir\s+/etc/mosquitto/conf\.d\s*$' "$MOSQ_MAIN"; then
cp -a "$MOSQ_MAIN" "${MOSQ_MAIN}.bak.$(date -u +%Y%m%d%H%M%S)"
echo >>"$MOSQ_MAIN"
echo "include_dir /etc/mosquitto/conf.d" >>"$MOSQ_MAIN"
fi
cat >"$MAIN_SNIPPET" <<'__IOMATEX_LISTENER__'
# IOMATEX managed main listener (single source of truth)
# Change bind here if needed:
# listener 1883 0.0.0.0 (LAN)
# listener 1883 127.0.0.1 (localhost only)
per_listener_settings true
listener 1883 0.0.0.0
protocol mqtt
allow_anonymous true
log_dest syslog
__IOMATEX_LISTENER__
chmod 644 "$MAIN_SNIPPET"
rm -f /etc/mosquitto/conf.d/00-iomatex-local.conf 2>/dev/null || true
step "Install apply tool: iomatex-mqtt-apply (CLI; edits env; generates bridge; restarts mosquitto)"
cat >"$APPLY" <<'__IOMATEX_APPLY__'
#!/usr/bin/env bash
set -euo pipefail
ENV_FILE="/etc/iomatex/mqtt_bridge.env"
BRIDGE_CONF="/etc/mosquitto/conf.d/50-iomatex-bridge.conf"
MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf"
STAMP="/run/iomatex-mqtt-apply.sha"
log(){ echo "[$(date -u +'%F %T UTC')] $*"; }
die(){ echo "ERROR: $*" >&2; exit 1; }
require_root(){ [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Run as root (use sudo)."; }
DEVICE_ID="$(hostname -s 2>/dev/null || hostname)"
DEFAULT_CLIENTID="${DEVICE_ID}-bridge"
# In-memory settings loaded from env
ENABLE_BRIDGE="0"
REMOTE_HOST=""
REMOTE_PORT="1883"
REMOTE_TLS="0"
REMOTE_USERNAME=""
REMOTE_PASSWORD=""
REMOTE_CLIENTID="$DEFAULT_CLIENTID"
usage(){
cat <<'__USAGE__'
iomatex-mqtt-apply - Manage Mosquitto bridge via /etc/iomatex/mqtt_bridge.env
Actions:
--print
--enable [--allow-anon]
--disable
--check (TCP connect to host:port before apply)
Setters:
--set-host HOST
--set-port PORT
--set-tls 0|1
--set-user USER
--set-pass PASS
--set-clientid ID
Examples:
sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass '***' --set-port 1883 --set-tls 0 --enable --check --print
sudo iomatex-mqtt-apply --disable --print
__USAGE__
}
ensure_env_file(){
mkdir -p /etc/iomatex
if [[ ! -f "$ENV_FILE" ]]; then
cat >"$ENV_FILE" <<__ENV__
ENABLE_BRIDGE=0
REMOTE_HOST=
REMOTE_PORT=1883
REMOTE_TLS=0
REMOTE_USERNAME=
REMOTE_PASSWORD=
REMOTE_CLIENTID=${DEFAULT_CLIENTID}
__ENV__
chmod 600 "$ENV_FILE"
chown root:root "$ENV_FILE"
fi
if head -c 3 "$ENV_FILE" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then die "BOM detected in $ENV_FILE"; fi
if grep -q $'\r' "$ENV_FILE" 2>/dev/null; then die "CRLF detected in $ENV_FILE"; fi
}
get_kv(){
local k="$1"
local line
line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)"
if [[ -z "$line" ]]; then echo ""; return 0; fi
echo "${line#${k}=}"
}
load_env(){
ENABLE_BRIDGE="$(get_kv ENABLE_BRIDGE)"
REMOTE_HOST="$(get_kv REMOTE_HOST)"
REMOTE_PORT="$(get_kv REMOTE_PORT)"
REMOTE_TLS="$(get_kv REMOTE_TLS)"
REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)"
REMOTE_PASSWORD="$(get_kv REMOTE_PASSWORD)"
REMOTE_CLIENTID="$(get_kv REMOTE_CLIENTID)"
: "${ENABLE_BRIDGE:=0}"
: "${REMOTE_HOST:=}"
: "${REMOTE_PORT:=1883}"
: "${REMOTE_TLS:=0}"
: "${REMOTE_USERNAME:=}"
: "${REMOTE_PASSWORD:=}"
: "${REMOTE_CLIENTID:=${DEFAULT_CLIENTID}}"
}
validate_value(){
local v="$1"
[[ "$v" != *$'\n'* && "$v" != *$'\r'* ]] || die "Invalid value contains newline/CR"
}
set_kv(){
local k="$1" v="$2"
validate_value "$v"
local tmp; tmp="$(mktemp)"
awk -v k="$k" -v v="$v" 'BEGIN{found=0}
$0 ~ "^"k"=" {print k"="v; found=1; next}
{print}
END{if(!found) print k"="v}
' "$ENV_FILE" >"$tmp"
cat "$tmp" >"$ENV_FILE"
rm -f "$tmp"
}
read_local_bind(){
LOCAL_BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' "$MAIN_SNIPPET" 2>/dev/null || true)"
: "${LOCAL_BIND:=<unknown>}"
}
check_remote(){
command -v nc >/dev/null 2>&1 || (apt-get update >/dev/null 2>&1 && apt-get install -y netcat-openbsd >/dev/null 2>&1) || true
[[ -n "$REMOTE_HOST" ]] || die "Cannot --check: REMOTE_HOST empty"
log "Checking TCP connect to ${REMOTE_HOST}:${REMOTE_PORT} ..."
nc -zvw3 "$REMOTE_HOST" "$REMOTE_PORT" >/dev/null 2>&1 || die "Remote not reachable: ${REMOTE_HOST}:${REMOTE_PORT}"
log "Remote reachable OK"
}
write_bridge_conf(){
rm -f "$BRIDGE_CONF" || true
if [[ "$ENABLE_BRIDGE" != "1" ]]; then
log "ENABLE_BRIDGE=0 -> bridge disabled (no $BRIDGE_CONF)"
return 0
fi
[[ -n "$REMOTE_HOST" ]] || die "REMOTE_HOST is empty but bridge is enabled."
cat >"$BRIDGE_CONF" <<__BRIDGE__
# IOMATEX bridge to external MQTT
connection iomatex_bridge
address ${REMOTE_HOST}:${REMOTE_PORT}
bridge_protocol_version mqttv311
cleansession true
try_private true
notifications false
clientid ${REMOTE_CLIENTID}
__BRIDGE__
if [[ -n "$REMOTE_USERNAME" ]]; then echo "remote_username ${REMOTE_USERNAME}" >>"$BRIDGE_CONF"; fi
if [[ -n "$REMOTE_PASSWORD" ]]; then echo "remote_password ${REMOTE_PASSWORD}" >>"$BRIDGE_CONF"; fi
if [[ "${REMOTE_TLS}" == "1" ]]; then
cat >>"$BRIDGE_CONF" <<'__TLS__'
bridge_cafile /etc/ssl/certs/ca-certificates.crt
bridge_tls_version tlsv1.2
__TLS__
fi
cat >>"$BRIDGE_CONF" <<__MAP__
# Topic mapping (hostname-root, inbound cmd only)
topic ${DEVICE_ID}/# out 0 "" ""
topic ${DEVICE_ID}/cmd/# in 0 "" ""
__MAP__
chmod 644 "$BRIDGE_CONF" || true
}
restart_broker_if_changed(){
systemctl daemon-reload >/dev/null 2>&1 || true
local sha
sha="$(
( sha256sum "$ENV_FILE" 2>/dev/null || true
sha256sum "$MAIN_SNIPPET" 2>/dev/null || true
sha256sum "$BRIDGE_CONF" 2>/dev/null || true ) | sha256sum | awk '{print $1}'
)"
if [[ -f "$STAMP" ]] && [[ "$(cat "$STAMP" 2>/dev/null)" == "$sha" ]]; then
log "No config changes -> skip mosquitto restart"
return 0
fi
echo "$sha" >"$STAMP" 2>/dev/null || true
systemctl restart mosquitto
log "mosquitto restarted"
}
report(){
load_env
read_local_bind
echo
echo "=== IOMATEX MQTT BRIDGE REPORT ==="
echo "Hostname : ${DEVICE_ID}"
echo "Local bind : ${LOCAL_BIND}:1883 (source: ${MAIN_SNIPPET})"
echo "Remote host : ${REMOTE_HOST:-<empty>}"
echo "Remote port : ${REMOTE_PORT:-1883}"
echo "Remote TLS : ${REMOTE_TLS:-0}"
echo "Remote user : ${REMOTE_USERNAME:-<empty>}"
echo "Remote password : <hidden>"
echo "Remote clientid : ${REMOTE_CLIENTID:-<empty>}"
echo "Bridge enabled : ${ENABLE_BRIDGE:-0}"
echo
echo "Bridge policy:"
echo " OUT: ${DEVICE_ID}/# -> ${DEVICE_ID}/#"
echo " IN : ${DEVICE_ID}/cmd/# -> ${DEVICE_ID}/cmd/#"
echo
}
main(){
require_root
ensure_env_file
load_env
local WANT_PRINT=0 WANT_DISABLE=0 WANT_ENABLE=0 ALLOW_ANON=0 DO_CHECK=0
local SET_HOST=0 SET_PORT=0 SET_TLS=0 SET_USER=0 SET_PASS=0 SET_CID=0
local V_HOST="" V_PORT="" V_TLS="" V_USER="" V_PASS="" V_CID=""
while [[ $# -gt 0 ]]; do
case "$1" in
--print) WANT_PRINT=1; shift;;
--disable) WANT_DISABLE=1; shift;;
--enable) WANT_ENABLE=1; shift;;
--allow-anon) ALLOW_ANON=1; shift;;
--check) DO_CHECK=1; shift;;
--set-host) SET_HOST=1; V_HOST="${2-}"; shift 2;;
--set-port) SET_PORT=1; V_PORT="${2-}"; shift 2;;
--set-tls) SET_TLS=1; V_TLS="${2-}"; shift 2;;
--set-user) SET_USER=1; V_USER="${2-}"; shift 2;;
--set-pass) SET_PASS=1; V_PASS="${2-}"; shift 2;;
--set-clientid) SET_CID=1; V_CID="${2-}"; shift 2;;
-h|--help) usage; exit 0;;
*) die "Unknown arg: $1 (use --help)";;
esac
done
[[ "$SET_HOST" == "1" ]] && set_kv REMOTE_HOST "$V_HOST"
[[ "$SET_PORT" == "1" ]] && set_kv REMOTE_PORT "$V_PORT"
[[ "$SET_TLS" == "1" ]] && set_kv REMOTE_TLS "$V_TLS"
[[ "$SET_USER" == "1" ]] && set_kv REMOTE_USERNAME "$V_USER"
[[ "$SET_PASS" == "1" ]] && set_kv REMOTE_PASSWORD "$V_PASS"
[[ "$SET_CID" == "1" ]] && set_kv REMOTE_CLIENTID "$V_CID"
chmod 600 "$ENV_FILE" || true
chown root:root "$ENV_FILE" || true
load_env
if [[ "$WANT_DISABLE" == "1" ]]; then
set_kv ENABLE_BRIDGE "0"
load_env
fi
if [[ "$WANT_ENABLE" == "1" ]]; then
[[ -n "$REMOTE_HOST" ]] || die "Cannot enable: REMOTE_HOST empty"
if [[ "$ALLOW_ANON" == "0" ]]; then
[[ -n "$REMOTE_USERNAME" ]] || die "Cannot enable: REMOTE_USERNAME empty (or use --allow-anon)"
[[ -n "$REMOTE_PASSWORD" ]] || die "Cannot enable: REMOTE_PASSWORD empty (or use --allow-anon)"
fi
set_kv ENABLE_BRIDGE "1"
load_env
fi
if [[ "$DO_CHECK" == "1" ]]; then
check_remote
fi
write_bridge_conf
restart_broker_if_changed
if [[ "$WANT_PRINT" == "1" ]]; then
report
else
log "Applied. enabled=${ENABLE_BRIDGE} remote=${REMOTE_HOST}:${REMOTE_PORT} hostname=${DEVICE_ID}"
fi
}
main "$@"
__IOMATEX_APPLY__
chmod 0755 "$APPLY"
chown root:root "$APPLY"
step "Install interactive remote-set tool (wrapper over iomatex-mqtt-apply; does not wipe on empty input)"
cat >"$REMOTE_SET" <<'__IOMATEX_REMOTE_SET__'
#!/usr/bin/env bash
set -euo pipefail
require_root() { if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then echo "Run as root: sudo iomatex-mqtt-remote-set" >&2; exit 1; fi; }
require_root
ENV_FILE="/etc/iomatex/mqtt_bridge.env"
get_kv(){
local k="$1" line
line="$(grep -m1 -E "^${k}=" "$ENV_FILE" 2>/dev/null || true)"
[[ -n "$line" ]] && echo "${line#${k}=}" || echo ""
}
REMOTE_HOST="$(get_kv REMOTE_HOST)"
REMOTE_PORT="$(get_kv REMOTE_PORT)"; : "${REMOTE_PORT:=1883}"
REMOTE_TLS="$(get_kv REMOTE_TLS)"; : "${REMOTE_TLS:=0}"
REMOTE_USERNAME="$(get_kv REMOTE_USERNAME)"
prompt() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-empty}): " input; echo "${input}"; }
prompt_port() { local label="$1" current="$2" input; read -r -p "${label} (current: ${current:-1883}, default 1883): " input; [[ -z "$input" ]] && echo "${current:-1883}" || echo "$input"; }
prompt_tls() { local label="$1" current="$2" input; read -r -p "${label} [0/1] (current: ${current:-0}, default 0): " input; [[ -z "$input" ]] && echo "${current:-0}" || echo "$input"; }
echo
echo "Enter external MQTT connection."
echo "NOTE: This tool calls iomatex-mqtt-apply (single source of truth)."
echo "TIP : Press Enter to KEEP current values."
echo
h="$(prompt "REMOTE_HOST" "$REMOTE_HOST")"
u="$(prompt "REMOTE_USERNAME" "$REMOTE_USERNAME")"
read -r -s -p "REMOTE_PASSWORD (hidden; Enter to keep current): " p; echo
pr="$(prompt_port "REMOTE_PORT" "$REMOTE_PORT")"
tls="$(prompt_tls "REMOTE_TLS" "$REMOTE_TLS")"
args=()
[[ -n "$h" ]] && args+=(--set-host "$h")
[[ -n "$u" ]] && args+=(--set-user "$u")
[[ -n "$p" ]] && args+=(--set-pass "$p")
args+=(--set-port "$pr")
args+=(--set-tls "$tls")
args+=(--enable --print)
exec /usr/local/sbin/iomatex-mqtt-apply "${args[@]}"
__IOMATEX_REMOTE_SET__
chmod 0755 "$REMOTE_SET"
chown root:root "$REMOTE_SET"
step "Allow itscreen user to run iomatex-mqtt-apply via sudo (NOPASSWD)"
install -d -m 0755 /etc/sudoers.d
cat >/etc/sudoers.d/90-iomatex-mqtt-apply <<'__IOMATEX_SUDOERS__'
# Allow itscreen to manage MQTT bridge without password
itscreen ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-mqtt-apply
__IOMATEX_SUDOERS__
chmod 0440 /etc/sudoers.d/90-iomatex-mqtt-apply
if command -v visudo >/dev/null 2>&1; then visudo -cf /etc/sudoers.d/90-iomatex-mqtt-apply >/dev/null; fi
step "Create systemd watcher: auto-apply on env changes"
cat >/etc/systemd/system/iomatex-mqtt-bridge.service <<'__IOMATEX_PATH_SVC__'
[Unit]
Description=IOMATEX MQTT Apply (regen mosquitto conf)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-mqtt-apply
__IOMATEX_PATH_SVC__
cat >/etc/systemd/system/iomatex-mqtt-bridge.path <<'__IOMATEX_PATH__'
[Unit]
Description=Watch /etc/iomatex/mqtt_bridge.env and re-apply mosquitto config
[Path]
PathChanged=/etc/iomatex/mqtt_bridge.env
[Install]
WantedBy=multi-user.target
__IOMATEX_PATH__
step "Create health timer (publishes under hostname root)"
cat >/usr/local/sbin/iomatex-mqtt-health.sh <<'__IOMATEX_HEALTH_SH__'
#!/usr/bin/env bash
set -euo pipefail
if ! systemctl is-active --quiet mosquitto; then systemctl start mosquitto || systemctl restart mosquitto || true; fi
ts="$(date -u +'%F %T UTC')"
h="$(hostname -s)"
mosquitto_pub -h 127.0.0.1 -t "${h}/health/ping" -m "ping ${ts}" >/dev/null 2>&1 || true
__IOMATEX_HEALTH_SH__
chmod 0755 /usr/local/sbin/iomatex-mqtt-health.sh
chown root:root /usr/local/sbin/iomatex-mqtt-health.sh
cat >/etc/systemd/system/iomatex-mqtt-health.service <<'__IOMATEX_HEALTH_SVC__'
[Unit]
Description=IOMATEX MQTT health check
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-mqtt-health.sh
__IOMATEX_HEALTH_SVC__
cat >/etc/systemd/system/iomatex-mqtt-health.timer <<'__IOMATEX_HEALTH_TIMER__'
[Unit]
Description=Run IOMATEX MQTT health check every minute
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=15s
Persistent=true
[Install]
WantedBy=timers.target
__IOMATEX_HEALTH_TIMER__
step "Enable services, apply config now"
systemctl daemon-reload
systemctl enable mosquitto >/dev/null 2>&1 || true
systemctl enable --now iomatex-mqtt-bridge.path
systemctl enable --now iomatex-mqtt-health.timer
/usr/local/sbin/iomatex-mqtt-apply --print || true
step "Cleanup any temporary debug config (if exists)"
rm -f /etc/mosquitto/conf.d/99-iomatex-debug.conf >/dev/null 2>&1 || true
step "Print quick status + tips"
H="$(hostname -s)"
BIND="$(awk '($1=="listener" && $2=="1883"){print $3; exit}' /etc/mosquitto/conf.d/01-iomatex-main-listener.conf 2>/dev/null || true)"
echo
echo "Local broker listener (SOURCE OF TRUTH): /etc/mosquitto/conf.d/01-iomatex-main-listener.conf"
echo " listener 1883 ${BIND:-<unknown>}"
echo
echo "Effective listeners (runtime):"
ss -lntp 2>/dev/null | grep -E ":(1883)\b" || true
echo
echo "ENV: $ENV_FILE"
grep -n -E '^(ENABLE_BRIDGE|REMOTE_HOST|REMOTE_PORT|REMOTE_TLS|REMOTE_USERNAME|REMOTE_CLIENTID|REMOTE_PASSWORD)=' "$ENV_FILE" 2>/dev/null | sed -E 's/^(REMOTE_PASSWORD=).*/\1<hidden>/' || true
echo
echo "Bridge conf:"
ls -la /etc/mosquitto/conf.d/50-iomatex-bridge.conf 2>/dev/null || echo " (not present: bridge disabled)"
echo
echo "Manual remote set + report:"
echo " sudo iomatex-mqtt-remote-set"
echo
echo "Non-interactive apply example (for itscreen):"
echo " sudo iomatex-mqtt-apply --set-host dev.it-screen.com --set-user broadcaster --set-pass \"PASS\" --set-port 1883 --set-tls 0 --enable --check --print"
echo
log "Stage1 MQTT finished successfully."

View File

@ -17,6 +17,8 @@ export DEBIAN_FRONTEND=noninteractive
LOG="/var/log/iomatex-stage1-mqtt.log"
mkdir -p /var/log >/dev/null 2>&1 || true
touch "$LOG" >/dev/null 2>&1 || true
DEVICE_ID_FILE="/userdata/device-id"
DEVICE_ID_RE='^g-box-[a-f0-9]{8}$'
log() {
local line="[$(date -u +'%F %T UTC')] $*"
@ -24,6 +26,13 @@ log() {
echo "$line" >>"$LOG" 2>/dev/null || true
}
apt_noninteractive() {
apt-get -y \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
"$@"
}
safe_systemctl() {
local action="$1"
shift
@ -74,7 +83,25 @@ need_root() {
}
need_root
HOSTNAME_SHORT="$(hostname -s 2>/dev/null || hostname)"
resolve_edge_name() {
local value=""
if [[ -f "$DEVICE_ID_FILE" ]]; then
value="$(tr -d ' \n\r' < "$DEVICE_ID_FILE" 2>/dev/null || true)"
fi
if printf '%s\n' "${value:-}" | grep -Eq "$DEVICE_ID_RE"; then
printf '%s\n' "$value"
return 0
fi
value="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
value="${value%%.*}"
if [[ -n "${value:-}" ]]; then
printf '%s\n' "$value"
return 0
fi
printf '%s\n' "unknown-edge"
}
HOSTNAME_SHORT="$(resolve_edge_name)"
ENV_FILE="/etc/iomatex/mqtt_bridge.env"
MOSQ_MAIN="/etc/mosquitto/mosquitto.conf"
@ -149,9 +176,12 @@ touch "$LOG" >/dev/null 2>&1 || true
log "OK: cleaned mosquitto configs, iomatex tools/env, mosquitto DB, systemd units, and logs. Ready for clean install."
step "Install Mosquitto broker + clients"
log "RUN: dpkg --configure -a || true"
dpkg --configure -a || true
run_bg "APT repair (install -f)" apt_noninteractive install -f
run_bg "apt-get update" apt-get update
run_bg "install mosquitto + clients" apt-get install -y mosquitto mosquitto-clients
apt-get install -y netcat-openbsd >/dev/null 2>&1 || true
run_bg "install mosquitto + clients" apt_noninteractive install mosquitto mosquitto-clients
apt_noninteractive install netcat-openbsd >/dev/null 2>&1 || true
step "Create directories and base env file"
mkdir -p /etc/iomatex
@ -172,6 +202,18 @@ chmod 600 "$ENV_FILE"
chown root:root "$ENV_FILE"
step "Ensure mosquitto.conf includes conf.d and write single source-of-truth listener snippet"
if grep -qE '^\s*log_dest\s+file\s+' "$MOSQ_MAIN" || grep -qE '^\s*log_type\s+' "$MOSQ_MAIN"; then
cp -a "$MOSQ_MAIN" "${MOSQ_MAIN}.bak.$(date -u +%Y%m%d%H%M%S)"
tmp_main="$(mktemp)"
awk '
/^[[:space:]]*log_dest[[:space:]]+file[[:space:]]+/ { next }
/^[[:space:]]*log_type[[:space:]]+/ { next }
{ print }
' "$MOSQ_MAIN" >"$tmp_main"
install -m 0644 "$tmp_main" "$MOSQ_MAIN"
rm -f "$tmp_main"
fi
if ! grep -qE '^\s*include_dir\s+/etc/mosquitto/conf\.d\s*$' "$MOSQ_MAIN"; then
cp -a "$MOSQ_MAIN" "${MOSQ_MAIN}.bak.$(date -u +%Y%m%d%H%M%S)"
echo >>"$MOSQ_MAIN"
@ -184,9 +226,13 @@ per_listener_settings true
listener 1883 0.0.0.0
protocol mqtt
allow_anonymous true
log_dest syslog
__IOMATEX_LISTENER__
chmod 644 "$MAIN_SNIPPET"
mkdir -p /var/log/mosquitto
touch /var/log/mosquitto/mosquitto.log
chown mosquitto:mosquitto /var/log/mosquitto /var/log/mosquitto/mosquitto.log 2>/dev/null || true
chmod 0750 /var/log/mosquitto 2>/dev/null || true
chmod 0640 /var/log/mosquitto/mosquitto.log 2>/dev/null || true
step "Install apply tool: iomatex-mqtt-apply"
cat >"$APPLY" <<'__IOMATEX_APPLY__'
@ -201,8 +247,21 @@ STAMP="/run/iomatex-mqtt-apply.sha"
log(){ echo "[$(date -u +'%F %T UTC')] $*"; }
die(){ echo "ERROR: $*" >&2; exit 1; }
require_root(){ [[ "${EUID:-$(id -u)}" -eq 0 ]] || die "Run as root (use sudo)."; }
resolve_edge_name(){
local value=""
if [[ -f /userdata/device-id ]]; then
value="$(tr -d ' \n\r' < /userdata/device-id 2>/dev/null || true)"
fi
if printf '%s\n' "${value:-}" | grep -Eq '^g-box-[a-f0-9]{8}$'; then
printf '%s\n' "$value"
return 0
fi
value="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
value="${value%%.*}"
[[ -n "${value:-}" ]] && printf '%s\n' "$value" || printf '%s\n' "unknown-edge"
}
DEVICE_ID="$(hostname -s 2>/dev/null || hostname)"
DEVICE_ID="$(resolve_edge_name)"
DEFAULT_CLIENTID="${DEVICE_ID}"
ENABLE_BRIDGE="0"
@ -308,7 +367,13 @@ read_local_bind(){
}
check_remote(){
command -v nc >/dev/null 2>&1 || (apt-get update >/dev/null 2>&1 && apt-get install -y netcat-openbsd >/dev/null 2>&1) || true
command -v nc >/dev/null 2>&1 || (
apt-get update >/dev/null 2>&1 &&
apt-get -y \
-o Dpkg::Options::="--force-confdef" \
-o Dpkg::Options::="--force-confold" \
install netcat-openbsd >/dev/null 2>&1
) || true
[[ -n "$REMOTE_HOST" ]] || die "Cannot --check: REMOTE_HOST empty"
log "Checking TCP connect to ${REMOTE_HOST}:${REMOTE_PORT} ..."
nc -zvw3 "$REMOTE_HOST" "$REMOTE_PORT" >/dev/null 2>&1 || die "Remote not reachable: ${REMOTE_HOST}:${REMOTE_PORT}"
@ -619,7 +684,7 @@ if ! systemctl is-active --quiet mosquitto; then
systemctl start mosquitto || systemctl restart mosquitto || true
fi
h="$(hostname -s 2>/dev/null || hostname)"
h="$(if [[ -f /userdata/device-id ]]; then tr -d ' \n\r' < /userdata/device-id; else hostname -s 2>/dev/null || hostname; fi)"
BRIDGE_BASE_TOPIC="$(get_kv BRIDGE_BASE_TOPIC)"; : "${BRIDGE_BASE_TOPIC:=v1/edge}"
ts_main="$(date -u '+%F, %T UTC')"

View File

@ -1,27 +0,0 @@
# Stage4: Reverse Tunnel — памятка инженеру
1. Определяем `hostname` устройства и используем его как уникальный идентификатор.
2. Формируем имя пользователя на VPS по правилу: `tunnel_<hostname>`.
3. На EDGE создаём (если нет) отдельный SSH-ключ `ed25519` с именем `iomatex-<hostname>` в `~/.ssh/`.
4. Проверяем и фиксируем правильные права на `~/.ssh` и ключи.
5. Устанавливаем `autossh` (если не установлен).
6. Создаём systemd-сервис `iomatex-remote`, который стартует после поднятия сети.
7. Настраиваем reverse-проброс портов:
- VPS порт Cockpit → EDGE Cockpit (9090)
- VPS порт Z2M → EDGE Z2M (8081)
8. Включаем автозапуск сервиса и запускаем его сразу.
9. Включаем логирование работы туннеля (systemd + файл логов autossh).
10. Выводим в консоль публичный ключ EDGE.
11. Выводим готовую команду для VPS: создать пользователя `tunnel_<hostname>` и установить ключ в `authorized_keys` с ограничениями.
12. Результат: после перезагрузки EDGE туннель поднимается автоматически и восстанавливается при потере интернета.

View File

@ -1,68 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# iomatex-calc-port
# Usage: iomatex-calc-port <hostname>
#
# Computes deterministic ports (same logic as Stage4):
# crc = cksum(hostname).field1
# slot = crc % PORT_SLOTS
# cockpit = PORT_BASE + slot*2
# z2m = PORT_BASE + slot*2 + 1
#
# Also prints ready-to-paste commands for:
# - PowerShell (laptop)
# - Linux/macOS (laptop)
# - VPS quick checks (curl)
HN="${1:-}"
if [[ -z "$HN" ]]; then
echo "Usage: $(basename "$0") <hostname>"
exit 2
fi
# Keep these in sync with Stage4 defaults
PORT_BASE="${PORT_BASE:-20000}"
PORT_SLOTS="${PORT_SLOTS:-4000}"
# VPS connection (defaults for Protect)
VPS_HOST="${VPS_HOST:-193.42.111.54}"
VPS_PORT="${VPS_PORT:-2200}"
VPS_USER="${VPS_USER:-broadcaster}"
# Local ports on laptop
LAPTOP_COCKPIT_PORT="${LAPTOP_COCKPIT_PORT:-9090}"
LAPTOP_Z2M_PORT="${LAPTOP_Z2M_PORT:-8081}"
CRC="$(cksum <<<"$HN" | awk '{print $1}')"
SLOT="$(( CRC % PORT_SLOTS ))"
COCKPIT="$(( PORT_BASE + SLOT*2 ))"
Z2M="$(( PORT_BASE + SLOT*2 + 1 ))"
echo
echo "Hostname: $HN"
echo "CRC: $CRC"
echo "Cockpit: $COCKPIT"
echo "Z2M: $Z2M"
echo
echo "VPS checks:"
echo " curl -I http://localhost:$COCKPIT"
echo " curl -I http://localhost:$Z2M"
echo
echo "Laptop command (PowerShell):"
echo " ssh -N -p $VPS_PORT -o ExitOnForwardFailure=yes -L $LAPTOP_COCKPIT_PORT:127.0.0.1:$COCKPIT -L $LAPTOP_Z2M_PORT:127.0.0.1:$Z2M $VPS_USER@$VPS_HOST"
echo
echo "Laptop command (Linux/macOS):"
echo " ssh -N -p $VPS_PORT -o ExitOnForwardFailure=yes \\"
echo " -L $LAPTOP_COCKPIT_PORT:127.0.0.1:$COCKPIT \\"
echo " -L $LAPTOP_Z2M_PORT:127.0.0.1:$Z2M \\"
echo " $VPS_USER@$VPS_HOST"
echo
echo "Open in browser:"
echo " Cockpit: https://localhost:$LAPTOP_COCKPIT_PORT"
echo " Z2M: http://localhost:$LAPTOP_Z2M_PORT"
echo

View File

@ -58,10 +58,47 @@ preflight_checks() {
require_cmd id
require_cmd cksum
require_cmd awk
require_cmd cut
require_cmd getent
require_cmd runuser
require_cmd sed
require_cmd ssh-keygen
require_cmd systemctl
require_cmd tee
require_cmd hostname
}
validate_uint() {
local value="$1"
local name="$2"
[[ "$value" =~ ^[0-9]+$ ]] || die "${name} must be a non-negative integer: ${value}"
}
validate_port() {
local value="$1"
local name="$2"
validate_uint "$value" "$name"
(( value >= 1 && value <= 65535 )) || die "${name} must be in range 1..65535: ${value}"
}
validate_settings() {
local max_remote_port
validate_port "$VPS_PORT" "VPS_PORT"
validate_port "$COCKPIT_LOCAL_PORT" "COCKPIT_LOCAL_PORT"
validate_port "$Z2M_LOCAL_PORT" "Z2M_LOCAL_PORT"
validate_port "$WEBUI_LOCAL_PORT" "WEBUI_LOCAL_PORT"
validate_uint "$PORT_BASE" "PORT_BASE"
validate_uint "$PORT_SLOTS" "PORT_SLOTS"
(( PORT_SLOTS >= 1 )) || die "PORT_SLOTS must be >= 1"
max_remote_port="$(( PORT_BASE + (PORT_SLOTS - 1) * 3 + 2 ))"
(( PORT_BASE >= 1 )) || die "PORT_BASE must be >= 1"
(( max_remote_port <= 65535 )) || die "Computed remote port range exceeds 65535: ${PORT_BASE}..${max_remote_port}"
}
shell_quote() {
printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\"'\"'/g")"
}
ensure_autossh_installed() {
@ -239,6 +276,7 @@ main() {
require_root
preflight_checks
validate_settings
ensure_autossh_installed
hostname_value="$(hostname)"
@ -270,7 +308,7 @@ main() {
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\""
vps_bootstrap_cmd="EDGE_HOSTNAME=$(shell_quote "$hostname_value"); EDGE_IP=$(shell_quote "$edge_ip"); EDGE_PUBKEY_LINE=$(shell_quote "$public_key_line"); COCKPIT_REMOTE_PORT=$(shell_quote "$cockpit_remote_port"); Z2M_REMOTE_PORT=$(shell_quote "$z2m_remote_port"); WEBUI_REMOTE_PORT=$(shell_quote "$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" \

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3
import glob
import importlib.util
import ipaddress
import json
import os
import shutil
@ -37,6 +38,8 @@ AP_UP_SCRIPT = "/usr/local/sbin/iomatex-ap-up"
AP_DOWN_SCRIPT = "/usr/local/sbin/iomatex-ap-down"
WIFI_STATUS_SCRIPT = "/usr/local/sbin/iomatex-wifi-status"
WIFI_SETUP_SCRIPT = "/usr/local/sbin/iomatex-wifi-setup"
DEVICE_ID_PATH = "/userdata/device-id"
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
AP_PASSWORD_RE = re.compile(r"^[a-z0-9]{8,}$")
DEFAULT_AP_UI_PORT = "80"
CAPTIVE_PORTAL_PATH = "/portal"
@ -139,6 +142,13 @@ def read_env_file(path):
return data
def get_persistent_edge_name():
value = read_text(DEVICE_ID_PATH).strip()
if DEVICE_ID_RE.fullmatch(value):
return value
return ""
def write_env_file(path, values):
directory = os.path.dirname(path) or "."
os.makedirs(directory, exist_ok=True)
@ -156,6 +166,9 @@ def write_env_file(path, values):
def get_system_hostname():
persistent = get_persistent_edge_name()
if persistent:
return persistent
hostname = ""
try:
hostname = os.uname().nodename
@ -173,6 +186,19 @@ def get_system_hostname():
return ""
def get_primary_ipv4():
rc, stdout, _ = run(["hostname", "-I"])
if rc == 0:
for token in (stdout or "").split():
try:
parsed = ipaddress.ip_address(token.strip())
except ValueError:
continue
if isinstance(parsed, ipaddress.IPv4Address):
return str(parsed)
return ""
def get_device_serial():
raw = read_text("/proc/cpuinfo")
for line in raw.splitlines():
@ -403,8 +429,21 @@ def get_os_label():
def get_identity_payload():
hostname = get_system_hostname() or os.uname().nodename
serial_number = get_device_serial()
primary_ipv4 = get_primary_ipv4()
endpoint_host = primary_ipv4 or hostname
host_label = hostname or "-"
if hostname and primary_ipv4:
host_label = f"{hostname} ({primary_ipv4})"
elif primary_ipv4:
host_label = primary_ipv4
return {
"hostname": hostname,
"serial_number": serial_number,
"primary_ipv4": primary_ipv4,
"endpoint_host": endpoint_host,
"host_label": host_label,
"mdns_hostname": f"{hostname}.local" if hostname else "",
"edge_id": get_edge_id(),
"os_label": get_os_label(),
}
@ -490,6 +529,13 @@ def get_disk_usage():
}
def get_cpu_cores():
try:
return int(os.cpu_count() or 0)
except Exception:
return 0
def get_health_summary():
sensors = read_thermal_sensors()
disk = get_disk_usage()
@ -497,6 +543,7 @@ def get_health_summary():
return {
"ok": True,
"cpu_usage_percent": cpu_usage,
"cpu_cores": get_cpu_cores(),
"load_average": get_load_average(),
"disk": disk,
"temperatures": sensors,
@ -1012,6 +1059,7 @@ def build_status_payload():
"systemd_unit": systemd_unit,
"run": run,
"get_ap_status_card": ap_status_card,
"get_identity_payload": get_identity_payload,
}
cards = []
provider_names = []
@ -1038,7 +1086,7 @@ def build_status_payload():
payload = {
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"hostname": os.uname().nodename,
"hostname": get_system_hostname() or os.uname().nodename,
"identity": get_identity_payload(),
"services": cards,
"providers": provider_names,
@ -1059,6 +1107,26 @@ def find_service_card(service_id):
return None
def restart_service_card(service_id):
allowed_units = {
"zigbee2mqtt": "zigbee2mqtt.service",
}
service_id = str(service_id or "").strip()
unit_name = allowed_units.get(service_id)
if not unit_name:
raise ValueError("Unsupported service")
rc, _, stderr = run(["systemctl", "restart", unit_name], timeout=20)
if rc != 0:
raise RuntimeError(stderr or f"Failed to restart {unit_name}")
invalidate_cache()
payload = find_service_card(service_id)
if not payload:
raise RuntimeError("Service card not found after restart")
return payload
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
return
@ -1331,6 +1399,27 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/service/restart":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
service_id = str(payload.get("service_id", "")).strip()
if not service_id:
self.send_json({"ok": False, "error": "service_id is required"}, code=400)
return
try:
refreshed = restart_service_card(service_id)
self.send_json({
"ok": True,
"message": f"Restart requested for {service_id}",
**refreshed,
})
except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=400)
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
self.send_error(404)

View File

@ -21,9 +21,20 @@ DEFAULT_SERVER = "rest.uae.iomatex.com"
REGISTER_TIMEOUT_SEC = 25
REPLY_TIMEOUT_SEC = 6
HOST_RE = re.compile(r"^(?=.{1,253}$)(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.(?!-)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
DEVICE_ID_PATH = "/userdata/device-id"
DEVICE_ID_RE = re.compile(r"^g-box-[a-f0-9]{8}$")
def _device_hostname():
device_id = ""
if os.path.exists(DEVICE_ID_PATH):
try:
with open(DEVICE_ID_PATH, "r", encoding="utf-8", errors="ignore") as fh:
device_id = fh.read().strip()
except Exception:
device_id = ""
if DEVICE_ID_RE.fullmatch(device_id):
return device_id
host = ""
try:
host = os.uname().nodename

View File

@ -169,6 +169,20 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
}
.splitMeta section{min-width:0}
.meta .key{color:var(--muted)}
.metricValueStack{display:grid;gap:4px}
.metricHeadline{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.metricState{
display:inline-flex;
align-items:center;
border-radius:999px;
padding:3px 8px;
font-size:11px;
font-weight:700;
}
.metricState.tone-ok{background:rgba(14,122,83,.10);color:var(--accent)}
.metricState.tone-warn{background:rgba(154,106,0,.10);color:var(--warn)}
.metricState.tone-error{background:rgba(185,52,52,.10);color:var(--error)}
.metricHint,.metricSubline{color:var(--muted);font-size:12px}
.list{margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}
.serviceCard .list:last-of-type{margin-top:auto}
.listTitle{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px}
@ -178,6 +192,124 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
}
.pill.good{background:rgba(14,122,83,.10);color:var(--accent)}
.pill.bad{background:rgba(185,52,52,.10);color:var(--error)}
.reverseTunnelCard{gap:0}
.tunnelSummaryGrid{
display:grid;
grid-template-columns:repeat(4,minmax(0,1fr));
gap:10px;
margin-top:16px;
}
.tunnelSummaryItem{
border:1px solid var(--line);
border-radius:12px;
background:#fbfcfb;
padding:10px 12px;
display:grid;
gap:4px;
}
.tunnelSummaryLabel{
font-size:11px;
text-transform:uppercase;
letter-spacing:.08em;
color:var(--muted);
}
.tunnelSummaryValue{
font-size:18px;
line-height:1.1;
}
.reverseTunnelGroups{
display:grid;
gap:8px;
}
.tunnelAccordion{
border:1px solid var(--line);
border-radius:14px;
background:#fbfcfb;
overflow:hidden;
}
.tunnelAccordionToggle{
width:100%;
border:0;
background:transparent;
padding:11px 14px;
display:flex;
align-items:center;
justify-content:space-between;
gap:10px;
text-align:left;
color:var(--ink);
cursor:pointer;
font:inherit;
}
.tunnelAccordionToggle:hover{background:#f3f7f5}
.tunnelAccordionLabel{font-size:13px;font-weight:700}
.connectorSummaryText{
margin-left:auto;
color:var(--muted);
font-size:12px;
font-weight:500;
}
.tunnelAccordionChevron{
color:var(--muted);
font-size:12px;
min-width:14px;
text-align:center;
}
.tunnelAccordionBody{
padding:0 14px 12px;
border-top:1px solid var(--line);
animation:tunnelAccordionIn .18s ease;
}
.tunnelTable{
display:grid;
gap:2px;
margin-top:10px;
}
.tunnelTableHead,
.tunnelCompactRow{
display:grid;
grid-template-columns:minmax(88px,1.2fr) 72px minmax(92px,1fr);
gap:10px;
align-items:center;
}
.tunnelTable.has-latency .tunnelTableHead,
.tunnelTable.has-latency .tunnelCompactRow{
grid-template-columns:minmax(88px,1.2fr) 72px minmax(92px,1fr) 72px;
}
.tunnelTableHead{
color:var(--muted);
font-size:11px;
text-transform:uppercase;
letter-spacing:.08em;
padding:0 0 6px;
}
.tunnelCompactRow{
font-size:13px;
padding:7px 0;
border-top:1px solid rgba(34,48,43,.08);
}
.tunnelCompactRow:first-of-type{border-top:0}
.tunnelName{
font-weight:700;
overflow-wrap:anywhere;
}
.tunnelPort,
.tunnelLatency{
font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
}
.tunnelStatus{font-weight:700}
.tunnelStatus.tone-ok{color:var(--accent)}
.tunnelStatus.tone-warn{color:var(--warn)}
.tunnelStatus.tone-error{color:var(--error)}
.tunnelEmpty{
color:var(--muted);
font-size:13px;
padding-top:10px;
}
@keyframes tunnelAccordionIn{
from{opacity:0;transform:translateY(-4px)}
to{opacity:1;transform:translateY(0)}
}
.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;
@ -275,12 +407,19 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.manualSteps li + li{margin-top:8px}
.manualNotes{margin-top:10px}
.connectorList{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:12px}
.connectorCard{border:1px solid var(--line);border-radius:14px;padding:14px;background:#fbfcfb}
.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:12px}
.connectorListCompact{gap:10px}
.connectorCard{border:1px solid var(--line);border-radius:14px;padding:11px 12px;background:#fbfcfb}
.connectorHead{display:flex;justify-content:space-between;gap:10px;align-items:flex-start;margin-bottom:8px}
.connectorSubhead{margin-top:3px;color:var(--muted);font-size:12px}
.connectorState{font-size:12px;font-weight:700;border-radius:999px;padding:6px 10px}
.connectorState.is-connected{background:rgba(14,122,83,.10);color:var(--accent)}
.connectorState.is-idle{background:rgba(154,106,0,.10);color:var(--warn)}
.connectorMeta{margin-top:0}
.connectorMeta{
margin-top:0;
grid-template-columns:110px 1fr;
gap:6px 10px;
font-size:12px;
}
.modeBadge{
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;
}
@ -407,7 +546,25 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.networkOverviewGrid{grid-template-columns:1fr}
.manualGrid{grid-template-columns:1fr}
.specTable{grid-template-columns:1fr}
.tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
.brandDevice{width:min(70vw, 260px);max-height:180px}
.wideCard,.displayCard,.accessPointCard{grid-column:auto}
.displayHeroText{font-size:18px}
}
@media (max-width:680px){
.connectorSummaryText{
width:100%;
margin-left:0;
order:3;
}
.tunnelSummaryGrid{grid-template-columns:1fr}
.tunnelTableHead,
.tunnelCompactRow,
.tunnelTable.has-latency .tunnelTableHead,
.tunnelTable.has-latency .tunnelCompactRow{
grid-template-columns:1fr;
gap:4px;
}
.tunnelTableHead{display:none}
.tunnelCompactRow{padding:9px 0}
}

View File

@ -38,6 +38,15 @@
focused: false,
seeded: false
},
serviceActions: {
busyById: {}
},
displayUi: {
connectorsOpen: false
},
reverseTunnelUi: {
openGroups: {}
},
isPolling: false
};
@ -136,10 +145,53 @@
function renderKeyValueRows(items) {
return items.map((item) => `
<div class="key">${esc(item.label || "-")}</div>
<div>${esc(textValue(item.value, "Not available"))}</div>
<div>${item && item.html ? item.html : esc(textValue(item.value, "Not available"))}</div>
`).join("");
}
function formatMetricNumber(value, digits = 2) {
const number = Number(value);
if (!Number.isFinite(number)) return "";
return number.toFixed(digits);
}
function loadAverageState(normalizedLoad) {
if (!Number.isFinite(normalizedLoad)) return { label: "Unknown", tone: "warn" };
if (normalizedLoad <= 0.7) return { label: "Normal", tone: "ok" };
if (normalizedLoad <= 1.0) return { label: "Busy", tone: "warn" };
if (normalizedLoad <= 2.0) return { label: "High", tone: "warn" };
return { label: "Overloaded", tone: "error" };
}
function renderLoadAverageMetric(health) {
const loads = Array.isArray(health && health.load_average) ? health.load_average.map((item) => Number(item)) : [];
const cpuCores = Number(health && health.cpu_cores);
if (!loads.length || !Number.isFinite(loads[0])) {
return { label: "Load average", value: "Not available" };
}
const currentLoad = loads[0];
const normalizedLoad = cpuCores > 0 ? currentLoad / cpuCores : NaN;
const state = loadAverageState(normalizedLoad);
const cpuPercent = Number.isFinite(normalizedLoad) ? Math.round(normalizedLoad * 100) : null;
const tooltip = "Load average = number of processes waiting for CPU";
return {
label: "Load average",
html: `
<div class="metricValueStack" title="${esc(tooltip)}">
<div class="metricHeadline">
<span>${esc(formatMetricNumber(currentLoad) || "Not available")}</span>
<span class="metricState tone-${state.tone}">${esc(state.label)}</span>
${cpuPercent !== null ? `<span class="metricHint">(≈ ${esc(String(cpuPercent))}% of CPU)</span>` : ""}
</div>
<div class="metricSubline">1m / 5m / 15m: ${esc(loads.map((item) => formatMetricNumber(item) || "-").join(" / "))}</div>
<div class="metricSubline">CPU cores: ${esc(cpuCores > 0 ? String(cpuCores) : "Not available")}</div>
</div>
`
};
}
function renderSimplePanel(title, rows, extraClass = "") {
return `
<article class="panel card ${extraClass}">
@ -151,6 +203,116 @@
`;
}
function tunnelTone(tunnel) {
if (tunnel && tunnel.state === "failed") return "error";
if (tunnel && tunnel.active) return "ok";
return "warn";
}
function reverseTunnelGroupKey(cardId, groupName) {
return `${cardId || "reverse_tunnel"}:${groupName}`;
}
function reverseTunnelLatency(tunnel) {
const candidates = [tunnel && tunnel.latency, tunnel && tunnel.latency_ms, tunnel && tunnel.latencyMs];
for (const value of candidates) {
const text = textValue(value, "");
if (text) return text;
}
return "";
}
function renderTunnelRows(items) {
const tunnels = Array.isArray(items) ? items : [];
if (!tunnels.length) {
return `<div class="tunnelEmpty">No tunnels in this group.</div>`;
}
const showLatency = tunnels.some((item) => reverseTunnelLatency(item));
return `
<div class="tunnelTable ${showLatency ? "has-latency" : ""}">
<div class="tunnelTableHead">
<span>Name</span>
<span>Port</span>
<span>Status</span>
${showLatency ? `<span>Latency</span>` : ""}
</div>
${tunnels.map((tunnel) => `
<div class="tunnelCompactRow">
<span class="tunnelName">${esc((tunnel.name || "").toUpperCase() || "-")}</span>
<span class="tunnelPort">${esc(textValue(tunnel.local_port, "-"))}</span>
<span class="tunnelStatus tone-${tunnelTone(tunnel)}">${esc(tunnel.status_text || tunnel.state || "Unknown")}</span>
${showLatency ? `<span class="tunnelLatency">${esc(reverseTunnelLatency(tunnel) || "-")}</span>` : ""}
</div>
`).join("")}
</div>
`;
}
function renderTunnelAccordion(card, groupName, label, items) {
const groupKey = reverseTunnelGroupKey(card && card.id, groupName);
const expanded = !!state.reverseTunnelUi.openGroups[groupKey];
const tunnels = Array.isArray(items) ? items : [];
return `
<div class="tunnelAccordion ${expanded ? "is-open" : ""}">
<button
class="tunnelAccordionToggle"
type="button"
aria-expanded="${expanded ? "true" : "false"}"
onclick="window.__toggleTunnelGroup('${esc(groupKey)}')"
>
<span class="tunnelAccordionLabel">${esc(label)} (${tunnels.length})</span>
<span class="tunnelAccordionChevron">${expanded ? "▼" : "▶"}</span>
</button>
<div class="tunnelAccordionBody" ${expanded ? "" : "hidden"}>
${renderTunnelRows(tunnels)}
</div>
</div>
`;
}
function renderReverseTunnelCard(card) {
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const tunnels = Array.isArray(card.tunnels) ? card.tunnels : [];
const activeTunnels = tunnels.filter((tunnel) => !!tunnel.active);
const failedTunnels = tunnels.filter((tunnel) => (tunnel.state || "") === "failed");
const summaryRows = [
{ label: "Total", value: String(tunnels.length) },
{ label: "Active", value: String(activeTunnels.length) },
{ label: "Failed", value: String(failedTunnels.length) },
{ label: "Overall", value: card.active ? "OK" : "Degraded" }
];
return `
<article class="panel card serviceCard reverseTunnelCard">
<div class="cardTop">
<div>
<h2>${esc(card.title)}</h2>
${card.subtitle ? `<p class="cardSubtitle">${esc(card.subtitle)}</p>` : ""}
<div class="badge"><span class="dot ${tone}"></span>${esc(card.status_text || card.state || "Unknown")}</div>
</div>
</div>
<div class="tunnelSummaryGrid">
${summaryRows.map((item) => `
<div class="tunnelSummaryItem">
<span class="tunnelSummaryLabel">${esc(item.label)}</span>
<strong class="tunnelSummaryValue">${esc(item.value)}</strong>
</div>
`).join("")}
</div>
<div class="list reverseTunnelGroups">
${renderTunnelAccordion(card, "active", "Active tunnels", activeTunnels)}
${renderTunnelAccordion(card, "failed", "Failed tunnels", failedTunnels)}
${renderTunnelAccordion(card, "all", "All tunnels", tunnels)}
</div>
${renderServiceActions(card)}
${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 itscreenServerMode(host) {
const value = textValue(host, "").toLowerCase();
if (value === "rest.uae.iomatex.com") return "uae";
@ -227,22 +389,23 @@
const connectors = Array.isArray(card.connectors) ? card.connectors : [];
const connectedCount = connectors.filter((item) => item && item.connected).length;
const status = card.display_status || {};
const connectorsOpen = !!state.displayUi.connectorsOpen;
function renderConnector(connector) {
const rows = [
{ label: "Interface", value: connector.interface },
{ label: "Connector", value: connector.connector },
{ label: "Status", value: connector.connected ? "Connected" : connector.status },
{ label: "Monitor", value: connector.monitor_name },
{ label: "Manufacturer", value: connector.manufacturer },
{ label: "Current resolution", value: connector.current_resolution },
{ label: "Refresh rate", value: connector.refresh_rate },
{ label: "Preferred mode", value: connector.preferred_mode }
{ label: "Refresh", value: connector.refresh_rate }
];
return `
<article class="connectorCard">
<div class="connectorHead">
<div>
<strong>${esc(textValue(connector.connector, "Connector"))}</strong>
<div class="connectorSubhead">${esc(textValue(connector.interface, "Other"))}</div>
</div>
<span class="connectorState ${connector.connected ? "is-connected" : "is-idle"}">${esc(connector.connected ? "Connected" : textValue(connector.status, "Unknown"))}</span>
</div>
<div class="meta connectorMeta">${renderKeyValueRows(rows)}</div>
@ -270,8 +433,21 @@
</section>
<div class="meta">${renderKeyValueRows(details)}</div>
<div class="list">
<div class="listTitle">Connectors</div>
${connectors.length ? `<div class="connectorList">${connectors.map(renderConnector).join("")}</div>` : `<div class="emptyInline">No DRM connectors detected.</div>`}
<div class="tunnelAccordion ${connectorsOpen ? "is-open" : ""}">
<button
class="tunnelAccordionToggle"
type="button"
aria-expanded="${connectorsOpen ? "true" : "false"}"
onclick="window.__toggleDisplayConnectors()"
>
<span class="tunnelAccordionLabel">${esc(`Connectors (${connectors.length})`)}</span>
<span class="connectorSummaryText">${esc(`${connectors.length} total (${connectedCount} connected)`)}</span>
<span class="tunnelAccordionChevron">${connectorsOpen ? "▼" : "▶"}</span>
</button>
<div class="tunnelAccordionBody" ${connectorsOpen ? "" : "hidden"}>
${connectors.length ? `<div class="connectorList connectorListCompact">${connectors.map(renderConnector).join("")}</div>` : `<div class="emptyInline">No DRM connectors detected.</div>`}
</div>
</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>` : ""}
@ -453,17 +629,23 @@
`;
}
function currentHostName() {
return textValue(state.status && state.status.identity && state.status.identity.hostname, window.location.hostname || "localhost");
function currentAccessHost() {
const identity = state.status && state.status.identity;
return textValue(identity && identity.endpoint_host, textValue(identity && identity.primary_ipv4, textValue(identity && identity.hostname, window.location.hostname || "localhost")));
}
function currentHostLabel() {
const identity = state.status && state.status.identity;
return textValue(identity && identity.host_label, textValue(identity && identity.hostname, window.location.hostname || "localhost"));
}
function serviceOpenTarget(card) {
const host = currentHostName();
const host = currentAccessHost();
if (card.id === "zigbee2mqtt") {
return {
label: "Open",
href: `http://${host}:8081`,
disabled: !card.installed,
disabled: !card.installed || !card.listening_8081,
title: "Open Zigbee2MQTT Web UI",
badge: ":8081"
};
@ -472,7 +654,7 @@
return {
label: "Open",
href: `https://${host}:9090`,
disabled: !card.installed,
disabled: !card.installed || !card.listening_9090,
title: "Open Cockpit Web UI",
badge: ":9090"
};
@ -482,15 +664,20 @@
function renderServiceActions(card) {
const action = serviceOpenTarget(card);
if (!action) return "";
const restartable = !!card.restartable;
const busy = !!state.serviceActions.busyById[card.id];
if (!action && !restartable) return "";
return `
<div class="list">
<div class="listTitle">Actions</div>
<div class="actionRow serviceActionRow">
${action.disabled
${action ? (action.disabled
? `<button class="actionBtn" type="button" disabled title="${esc(action.title)}">${esc(action.label)}</button>`
: `<a class="actionBtn" href="${esc(action.href)}" target="_blank" rel="noopener noreferrer" title="${esc(action.title)}">${esc(action.label)}</a>`
}
) : ""}
${restartable
? `<button class="actionBtn secondary" type="button" ${busy ? "disabled" : ""} onclick="window.__restartService('${esc(card.id)}')">${esc(busy ? "Restarting..." : "Restart")}</button>`
: ""}
${action.badge ? `<span class="actionBadge">${esc(action.badge)}</span>` : ""}
</div>
</div>
@ -500,6 +687,7 @@
function renderServiceCard(card) {
if (card.id === "display") return renderDisplayCard(card);
if (card.id === "access_point") return renderAccessPointCard(card);
if (card.id === "reverse_tunnel") return renderReverseTunnelCard(card);
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
@ -541,7 +729,7 @@
const health = state.health || {};
const metrics = [
{ label: "CPU usage", value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? "Collecting..." : `${health.cpu_usage_percent}%` },
{ label: "Load average", value: Array.isArray(health.load_average) && health.load_average.length ? health.load_average.join(" / ") : "Not available" },
renderLoadAverageMetric(health),
{ label: "Disk usage", value: health.disk && health.disk.used_percent !== undefined ? `${health.disk.used_percent}% used` : "Not available" }
];
const temps = Array.isArray(health.temperatures) ? health.temperatures : [];
@ -1015,8 +1203,8 @@
function updateIdentity(identity) {
const safe = identity || {};
nodes.edgeId.textContent = safe.edge_id || "-";
nodes.hostName.textContent = safe.hostname || "-";
nodes.edgeId.textContent = safe.serial_number || "-";
nodes.hostName.textContent = currentHostLabel();
nodes.osLabel.textContent = "Unified diagnostics, network operations and gateway commissioning.";
}
@ -1035,6 +1223,11 @@
return payload;
}
function replaceServiceCard(nextCard) {
if (!nextCard || !state.status || !Array.isArray(state.status.services)) return;
state.status.services = state.status.services.map((card) => (card && card.id === nextCard.id ? nextCard : card));
}
async function loadStatus() {
state.status = await fetchJson("/api/status", { cache: "no-store" });
updateIdentity(state.status.identity || {});
@ -1318,6 +1511,42 @@
}
};
window.__restartService = async function (serviceId) {
if (!serviceId || state.serviceActions.busyById[serviceId]) return;
state.serviceActions.busyById[serviceId] = true;
if (state.activeTab === "health") renderActiveTab();
try {
const payload = await fetchJson("/api/service/restart", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ service_id: serviceId })
});
if (payload && payload.service) {
replaceServiceCard(payload.service);
}
showToast("success", payload.message || `Restart requested for ${serviceId}`);
await loadStatus();
if (state.activeTab === "health") renderActiveTab();
} catch (error) {
showToast("error", error.message || `Failed to restart ${serviceId}`);
} finally {
delete state.serviceActions.busyById[serviceId];
if (state.activeTab === "health") renderActiveTab();
}
};
window.__toggleTunnelGroup = function (groupKey) {
if (!groupKey) return;
state.reverseTunnelUi.openGroups[groupKey] = !state.reverseTunnelUi.openGroups[groupKey];
if (state.activeTab === "health") renderActiveTab();
};
window.__toggleDisplayConnectors = function () {
state.displayUi.connectorsOpen = !state.displayUi.connectorsOpen;
if (state.activeTab === "health") renderActiveTab();
};
window.__toggleItscreenPassword = function () {
state.itscreen.showPassword = !state.itscreen.showPassword;
if (state.activeTab === "tscreen") renderActiveTab();

View File

@ -21,11 +21,11 @@
</div>
<section class="panel identityPanel">
<div class="identityItem">
<span class="label">Edge ID</span>
<span class="label">Edge Serial Number</span>
<strong id="edgeId">-</strong>
</div>
<div class="identityItem">
<span class="label">Hostname</span>
<span class="label">Host / IP</span>
<strong id="hostName">-</strong>
</div>
<div class="identityItem identityItemWide">

View File

@ -1,3 +1,4 @@
import glob
import math
import os
import re
@ -56,6 +57,14 @@ def _strict_active(installed, configured, unit):
return bool(installed and configured and unit["active"])
def _listening_tcp(ctx, port):
rc, stdout, _ = ctx["run"](["ss", "-ltn"], timeout=8)
if rc != 0:
return False
needle = f":{port}"
return any(needle in line for line in (stdout or "").splitlines())
def _fallback(value, default="Not available"):
text = str(value or "").strip()
return text if text else default
@ -277,19 +286,44 @@ def _display_details(primary):
def _z2m_parse_config(ctx):
config_path = "/opt/zigbee2mqtt/data/configuration.yaml"
raw = ctx["read_text"](config_path)
mqtt_server = ""
mqtt_base_topic = ""
port = ""
adapter = ""
# Keep parsing intentionally narrow and section-aware to avoid false matches
# from unrelated `port:`/`adapter:` keys elsewhere in configuration.yaml.
def section_scalar(section_name, key_name):
if not raw:
return ""
pattern = re.compile(
rf'(?ms)^[ \t]*{re.escape(section_name)}:[ \t]*\n(?P<body>(?:^[ \t]+.*\n?)*)'
)
match = pattern.search(raw)
if not match:
return ""
body = match.group("body") or ""
key_match = re.search(
rf'^[ \t]+{re.escape(key_name)}:[ \t]*["\']?([^"\'\n#]+)["\']?[ \t]*$',
body,
re.MULTILINE,
)
return key_match.group(1).strip() if key_match else ""
if raw:
port_match = re.search(r'^\s*port:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE)
if port_match:
port = port_match.group(1).strip()
adapter_match = re.search(r'^\s*adapter:\s*["\']?([^"\'\n#]+)["\']?\s*$', raw, re.MULTILINE)
if adapter_match:
adapter = adapter_match.group(1).strip()
mqtt_server = section_scalar("mqtt", "server")
mqtt_base_topic = section_scalar("mqtt", "base_topic")
port = section_scalar("serial", "port")
adapter = section_scalar("serial", "adapter")
valid = bool(raw and mqtt_server and mqtt_base_topic and port and adapter)
return {
"config_path": config_path,
"raw": raw,
"exists": bool(raw),
"valid": valid,
"mqtt_server": mqtt_server,
"mqtt_base_topic": mqtt_base_topic,
"port": port,
"adapter": adapter,
}
@ -323,6 +357,14 @@ def _z2m_usb_diagnostics(ctx):
entry for entry in by_id_entries
if re.search(r"(zigbee|sonoff|cc2652|ember|ezsp|zbdongle|nabu|slae|thirdreality|tubeszb)", entry, re.IGNORECASE)
]
likely_by_id_paths = [os.path.join(by_id_path, entry) for entry in likely_by_id]
tty_candidates = []
try:
tty_candidates.extend(sorted(glob.glob("/dev/ttyUSB*")))
tty_candidates.extend(sorted(glob.glob("/dev/ttyACM*")))
except Exception:
tty_candidates = []
rc, lsusb_out, _ = ctx["run"](["/usr/bin/lsusb"], timeout=8)
usb_lines = [line.strip() for line in lsusb_out.splitlines() if line.strip()] if rc == 0 else []
@ -331,6 +373,19 @@ def _z2m_usb_diagnostics(ctx):
if re.search(r"(zigbee|sonoff|cc2652|ezsp|ember|nabu|slae|silicon labs|texas instruments|tubeszb|dongle)", line, re.IGNORECASE)
]
fallback_port = ""
resolved_fallback = ""
if likely_by_id_paths:
fallback_port = likely_by_id_paths[0]
elif tty_candidates:
fallback_port = tty_candidates[0]
if fallback_port:
try:
resolved_fallback = os.path.realpath(fallback_port)
except Exception:
resolved_fallback = fallback_port
coordinator_present = False
reason = ""
if not config["exists"]:
@ -341,20 +396,35 @@ def _z2m_usb_diagnostics(ctx):
coordinator_present = True
elif port_exists:
coordinator_present = True
elif fallback_port:
coordinator_present = True
reason = "Configured path not present, fallback coordinator detected"
else:
reason = "USB coordinator not found"
configured = bool(config["exists"] and port and (network_port or port_exists))
resolved_device = resolved_port or resolved_fallback
coordinator_ready = bool(
config["valid"] and coordinator_present and (network_port or bool(resolved_device))
)
configured = bool(config["valid"])
return {
"configured": configured,
"reason": reason,
"config_exists": config["exists"],
"config_valid": config["valid"],
"config_path": config["config_path"],
"mqtt_server": config["mqtt_server"],
"mqtt_base_topic": config["mqtt_base_topic"],
"configured_port": port,
"configured_port_exists": port_exists,
"configured_port_resolved": resolved_port,
"adapter": adapter,
"coordinator_present": coordinator_present,
"coordinator_ready": coordinator_ready,
"device_detected": coordinator_present,
"resolved_device": resolved_device,
"fallback_port": fallback_port,
"fallback_port_resolved": resolved_fallback,
"likely_by_id_count": len(likely_by_id),
"likely_usb_count": len(likely_usb),
}
@ -419,23 +489,35 @@ def mosquitto_card(ctx):
def mqtt_bridge_card(ctx):
env = ctx["read_env_file"]("/etc/iomatex/mqtt_bridge.env")
bridge_conf_exists = ctx["file_exists"]("/etc/mosquitto/conf.d/50-iomatex-bridge.conf")
installed = ctx["any_exists"]([
"/etc/iomatex/mqtt_bridge.env",
"/usr/local/sbin/iomatex-mqtt-apply",
"/etc/systemd/system/iomatex-mqtt-bridge.service",
"/etc/systemd/system/iomatex-mqtt-bridge.path",
])
enabled = str(env.get("ENABLE_BRIDGE", "0")).strip() == "1"
configured = bool(env.get("REMOTE_HOST", "").strip())
configured = bool(
ctx["file_exists"]("/etc/iomatex/mqtt_bridge.env") and
ctx["file_exists"]("/usr/local/sbin/iomatex-mqtt-apply") and
ctx["any_exists"]([
"/etc/systemd/system/iomatex-mqtt-bridge.service",
"/etc/systemd/system/iomatex-mqtt-bridge.path",
])
)
remote_host = str(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"])
active = bool(enabled and bridge_conf_exists and (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:
if installed and enabled and not remote_host:
errors.append("REMOTE_HOST is empty")
state, status_text = _lifecycle(installed, configured, active)
if installed and enabled and not bridge_conf_exists:
warnings.append("Bridge config missing")
state, status_text = _lifecycle(installed, configured, active, failed=bridge_service["active_state"] == "failed")
if installed and configured and not active and not enabled:
status_text = "Disabled"
return _service_card(
@ -449,11 +531,19 @@ def mqtt_bridge_card(ctx):
status_text,
errors[:2],
warnings[:2],
details=[
{"label": "Enable bridge", "value": "Yes" if enabled else "No"},
{"label": "Remote host", "value": remote_host or "-"},
{"label": "Bridge config", "value": "Present" if bridge_conf_exists else "Missing"},
{"label": "Path watcher", "value": bridge_path["active_state"] or "inactive"},
{"label": "Apply unit", "value": bridge_service["active_state"] or "inactive"},
],
)
def zigbee_card(ctx):
unit = ctx["systemd_unit"]("zigbee2mqtt.service")
web_unit = ctx["systemd_unit"]("iomatex-z2m-web.service")
app_footprint = ctx["any_exists"]([
"/opt/zigbee2mqtt/package.json",
"/opt/zigbee2mqtt/index.js",
@ -462,13 +552,30 @@ def zigbee_card(ctx):
"/etc/systemd/system/zigbee2mqtt.service",
"/lib/systemd/system/zigbee2mqtt.service",
])
installed = bool(app_footprint or unit_footprint or unit["installed"])
web_footprint = ctx["any_exists"]([
"/etc/systemd/system/iomatex-z2m-web.service",
"/usr/local/lib/iomatex-z2m-web.js",
])
installed = bool(app_footprint or unit_footprint or unit["installed"] or web_footprint or web_unit["installed"])
usb = _z2m_usb_diagnostics(ctx)
configured = bool(installed and usb["configured"])
active = bool(installed and configured and unit["active"])
configured = bool(installed and usb["config_valid"])
device_detected = bool(usb["device_detected"])
coordinator_ready = bool(usb["coordinator_ready"])
service_active = bool(unit["active"])
web_active = bool(web_unit["active"])
listening_8081 = _listening_tcp(ctx, 8081)
web_ready = bool(web_active or listening_8081)
runtime_ready = bool(service_active or web_ready)
active = bool(installed and configured and runtime_ready and coordinator_ready)
warnings = []
errors = _short_unit_errors(unit)
web_errors = _short_unit_errors(web_unit)
for item in web_errors:
if item not in errors:
errors.append(item)
# Layered runtime model:
# installed -> config_valid -> device_detected -> service_active/web_ready -> final state.
if not installed:
state = "not installed"
status_text = "Not installed"
@ -476,16 +583,36 @@ def zigbee_card(ctx):
elif not configured:
state = "installed_not_configured"
status_text = "Not configured"
warnings.append(usb["reason"] or "Coordinator not set in USB")
warnings.append("configuration.yaml is incomplete or invalid")
elif not coordinator_ready and runtime_ready:
state = "degraded"
status_text = "Degraded"
errors.append("No coordinator")
warnings.append("Hint: check USB / serial port")
elif runtime_ready:
state = "active"
status_text = "Running"
elif unit["active_state"] == "failed":
state = "failed"
status_text = "Failed"
elif active:
state = "active"
status_text = "Active"
status_text = "Error"
elif not coordinator_ready:
state = "coordinator_missing"
status_text = "Coordinator not found"
errors.append("No coordinator")
warnings.append("Hint: check USB / serial port")
else:
state = "inactive"
status_text = "Inactive"
status_text = "Error"
if not coordinator_ready:
coordinator_reason = usb["reason"] or "USB coordinator not found"
if coordinator_reason not in errors:
errors.append(coordinator_reason)
if installed and configured and not web_footprint:
warnings.append("Web gateway not installed")
elif installed and configured and not web_ready:
warnings.append("Web gateway on :8081 not available")
return _service_card(
"zigbee2mqtt",
@ -496,13 +623,26 @@ def zigbee_card(ctx):
active,
state,
status_text,
errors,
errors[:2],
warnings[:2],
restartable=True,
service_active=service_active,
web_active=web_active,
web_ready=web_ready,
device_detected=device_detected,
coordinator_ready=coordinator_ready,
listening_8081=listening_8081,
details=[
{"label": "Coordinator", "value": usb["reason"] if not configured else "USB coordinator detected"},
{"label": "Coordinator", "value": "Connected" if coordinator_ready else ("Detected" if device_detected else (usb["reason"] or "Not detected"))},
{"label": "USB port", "value": usb["configured_port"] or "Not set"},
{"label": "Resolved device", "value": usb["configured_port_resolved"] or "Not available"},
{"label": "Resolved device", "value": usb["resolved_device"] or "Not available"},
{"label": "Adapter", "value": usb["adapter"] or "Auto"},
{"label": "Config valid", "value": "Yes" if usb["config_valid"] else "No"},
{"label": "MQTT server", "value": usb["mqtt_server"] or "Not set"},
{"label": "Base topic", "value": usb["mqtt_base_topic"] or "Not set"},
{"label": "Service active", "value": "Yes" if service_active else "No"},
{"label": "Web gateway", "value": "Ready" if web_ready else "Unavailable"},
{"label": "Listening :8081", "value": "Yes" if listening_8081 else "No"},
],
)
@ -542,6 +682,19 @@ def _reverse_tunnel_key_paths(ctx):
return paths
def _reverse_tunnel_item_state(installed, configured, unit):
active = bool(installed and configured and unit["active"])
if not installed:
return "not installed", "Not installed", active
if unit["active_state"] == "failed":
return "failed", "Failed", active
if active:
return "active", "Active", active
if not configured:
return "installed_not_configured", "Not configured", active
return "inactive", "Inactive", active
def reverse_tunnel_card(ctx):
service_states = []
installed_checks = []
@ -563,18 +716,23 @@ def reverse_tunnel_card(ctx):
]
has_unit = any(path and ctx["file_exists"](path) for path in unit_file_candidates) or unit["installed"]
has_script = ctx["file_exists"](script_path)
is_active = unit["active"]
configured = bool(has_script and key_present)
item_state, item_status_text, is_active = _reverse_tunnel_item_state(has_unit or has_script, configured, unit)
installed_checks.append(has_unit or has_script)
configured_checks.append(has_script and key_present)
configured_checks.append(configured)
service_states.append({
"name": item["name"],
"unit": item["unit"],
"local_port": item["local_port"],
"installed": has_unit or has_script,
"configured": has_script and key_present,
"configured": configured,
"active": is_active,
"enabled": unit["unit_file_state"] in ("enabled", "static", "generated", "linked", "linked-runtime", "alias"),
"state": item_state,
"status_text": item_status_text,
"active_state": unit["active_state"],
"sub_state": unit["sub_state"],
})
if has_unit and has_script and not is_active:
@ -613,9 +771,14 @@ def reverse_tunnel_card(ctx):
if item["installed"] and not item["active"]
)
details = [
{"label": "SSH key", "value": "Present" if key_present else "Missing"},
{"label": "Active tunnels", "value": f"{active_count}/{total}" if total else "0/0"},
]
return _service_card(
"reverse_tunnel",
"Reverse Tunnel",
"Reverse Tunnels",
",".join(_reverse_tunnel_unit_names()),
installed,
configured,
@ -624,6 +787,8 @@ def reverse_tunnel_card(ctx):
status_text,
errors[:2],
warnings[:3],
details=details,
tunnels=service_states,
)

View File

@ -6,75 +6,126 @@ def _systemctl_flag(ctx, unit_name, command):
return False, text
def _which(ctx, binary_name):
rc, stdout, _ = ctx["run"](["which", binary_name], timeout=8)
return rc == 0 and bool((stdout or "").strip())
def _package_installed(ctx, package_name):
rc, stdout, _ = ctx["run"](
["dpkg-query", "-W", "-f=${Status}", package_name],
timeout=8,
)
return rc == 0 and "install ok installed" in (stdout or "").strip().lower()
def _cockpit_status(socket_unit, service_unit):
if socket_unit["active_state"] == "failed" or service_unit["active_state"] == "failed":
return "failed", "Error"
if socket_unit["active"] or service_unit["active"]:
def _listening_9090(ctx):
rc, stdout, _ = ctx["run"](["ss", "-ltn"], timeout=8)
if rc != 0:
return False
for line in (stdout or "").splitlines():
if ":9090" in line:
return True
return False
def _cockpit_status(*, installed, configured, socket_active, service_active, listening_9090, detected_mode, failed):
if not installed:
return "not installed", "Cockpit not installed"
if failed:
return "failed", "Cockpit failed"
if socket_active or service_active or listening_9090:
if detected_mode == "socket_activation":
return "active", "Ready (socket activation)"
return "active", "Active"
return "inactive", "Not running"
if not configured:
return "installed_not_configured", "Not configured"
return "inactive", "Not listening on :9090"
def get_cards(ctx):
socket_unit = ctx["systemd_unit"]("cockpit.socket")
service_unit = ctx["systemd_unit"]("cockpit.service")
cockpit_ws_present = _which(ctx, "cockpit-ws")
installed = bool(cockpit_ws_present or socket_unit["installed"] or service_unit["installed"])
identity = ctx["get_identity_payload"]()
endpoint_host = identity.get("endpoint_host") or "<host>"
package_installed = _package_installed(ctx, "cockpit")
socket_unit_exists = bool(socket_unit["installed"])
service_unit_exists = bool(service_unit["installed"])
socket_enabled, socket_enabled_text = _systemctl_flag(ctx, "cockpit.socket", "is-enabled")
service_enabled, service_enabled_text = _systemctl_flag(ctx, "cockpit.service", "is-enabled")
socket_active = bool(socket_unit["active"])
service_active = bool(service_unit["active"])
listening_9090 = _listening_9090(ctx)
installed = bool(package_installed or socket_unit_exists or service_unit_exists)
configured = bool(
(socket_unit_exists and socket_enabled) or
(service_unit_exists and service_enabled)
)
failed = socket_unit["active_state"] == "failed" or service_unit["active_state"] == "failed"
if not installed:
return [{
"id": "cockpit",
"title": "Cockpit",
"subtitle": "System administration",
"installed": False,
"configured": False,
"active": False,
"state": "not installed",
"status_text": "Not installed",
"warnings": [],
"errors": [],
"details": [
{"label": "Listener", "value": "cockpit.socket"},
{"label": "Enabled", "value": "No"},
{"label": "Web UI", "value": "https://<host>:9090"},
],
}]
detected_mode = "not_installed"
elif socket_unit_exists and (socket_enabled or socket_active or listening_9090):
detected_mode = "socket_activation"
elif service_unit_exists:
detected_mode = "service"
else:
detected_mode = "not_installed"
active = bool(socket_active or service_active or listening_9090)
state, status_text = _cockpit_status(
installed=installed,
configured=configured,
socket_active=socket_active,
service_active=service_active,
listening_9090=listening_9090,
detected_mode=detected_mode,
failed=failed,
)
enabled, enabled_text = _systemctl_flag(ctx, "cockpit.socket", "is-enabled")
active = bool(socket_unit["active"] or service_unit["active"])
state, status_text = _cockpit_status(socket_unit, service_unit)
listener = "cockpit.socket" if socket_unit["installed"] else "cockpit.service"
errors = []
warnings = []
if state == "failed":
if failed:
errors.append("Cockpit unit failed")
elif not active:
warnings.append("Cockpit web service is not running")
elif installed and not active:
warnings.append("Cockpit Web UI is not listening on :9090")
if not enabled and enabled_text and enabled_text not in ("disabled", "masked"):
warnings.append(f"socket state: {enabled_text}")
if installed and not configured:
warnings.append("Cockpit units are present but not enabled")
if socket_unit_exists and not socket_enabled and socket_enabled_text and socket_enabled_text not in ("disabled", "masked", "not-found"):
warnings.append(f"cockpit.socket state: {socket_enabled_text}")
if service_unit_exists and not service_enabled and service_enabled_text and service_enabled_text not in ("disabled", "masked", "static", "not-found"):
warnings.append(f"cockpit.service state: {service_enabled_text}")
return [{
"id": "cockpit",
"title": "Cockpit",
"subtitle": "System administration",
"installed": True,
"configured": True,
"installed": installed,
"configured": configured,
"active": active,
"state": state,
"status_text": status_text,
"package_installed": package_installed,
"socket_unit_exists": socket_unit_exists,
"service_unit_exists": service_unit_exists,
"socket_enabled": socket_enabled,
"socket_active": socket_active,
"service_enabled": service_enabled,
"service_active": service_active,
"listening_9090": listening_9090,
"detected_mode": detected_mode,
"warnings": warnings[:2],
"errors": errors[:2],
"details": [
{"label": "Listener", "value": listener},
{"label": "socket state", "value": socket_unit["active_state"] or "inactive"},
{"label": "service state", "value": service_unit["active_state"] or "inactive"},
{"label": "Enabled", "value": "Yes" if enabled else "No"},
{"label": "Web UI", "value": "https://<host>:9090"},
{"label": "Package installed", "value": "Yes" if package_installed else "No"},
{"label": "Socket unit", "value": "Present" if socket_unit_exists else "Missing"},
{"label": "Socket enabled", "value": "Yes" if socket_enabled else (socket_enabled_text or "No")},
{"label": "Socket active", "value": "Yes" if socket_active else (socket_unit["active_state"] or "No")},
{"label": "Service unit", "value": "Present" if service_unit_exists else "Missing"},
{"label": "Service enabled", "value": "Yes" if service_enabled else (service_enabled_text or "No")},
{"label": "Service active", "value": "Yes" if service_active else (service_unit["active_state"] or "No")},
{"label": "Listening :9090", "value": "Yes" if listening_9090 else "No"},
{"label": "Detected mode", "value": detected_mode},
{"label": "Web UI", "value": f"https://{endpoint_host}:9090" if listening_9090 else "Unavailable"},
],
}]

View File

@ -30,7 +30,6 @@ PROVIDERS_DIR="${APP_DIR}/providers.d"
FRONTEND_DIR="${APP_DIR}/frontend"
SERVICE_NAME="iomatex-console.service"
LEGACY_SERVICE_NAME="iomatex-webipc.service"
LEGACY_WIFI_UI_SERVICE_NAME="iomatex-wifi-ui.service"
CFG_PATH="/etc/iomatex/console.json"
SRC_LOGO="${LOGO_SOURCE:-$SCRIPT_DIR/iomatex_logo_source.png}"
SRC_GBOX="${GBOX_SOURCE:-$SCRIPT_DIR/g-box.png}"
@ -40,22 +39,11 @@ ts="$(date +%s)"
PREV_DIR="${APP_DIR}.prev.${ts}"
LEGACY_APP_DIR="/opt/iomatex-process1-webipc"
LEGACY_PREV_DIR="${LEGACY_APP_DIR}.prev.${ts}"
LEGACY_WIFI_UI_DIR="/opt/iomatex-wifi-ui"
LEGACY_WIFI_UI_PREV_DIR="${LEGACY_WIFI_UI_DIR}.prev.${ts}"
STAGE_DIR="${APP_DIR}.staging.${ts}"
STAGE_PUBLIC_DIR="${STAGE_DIR}/public"
STAGE_BACKEND_DIR="${STAGE_DIR}/backend"
STAGE_PROVIDERS_DIR="${STAGE_DIR}/providers.d"
STAGE_FRONTEND_DIR="${STAGE_DIR}/frontend"
IFACE="wlan0"
AP_IP="10.10.10.1"
AP_CIDR="${AP_IP}/24"
DHCP_START="10.10.10.50"
DHCP_END="10.10.10.150"
DHCP_LEASE="12h"
UI_PORT="80"
COUNTRY_CODE="NL"
AP_CHANNEL="6"
copy_tree() {
local src="$1"
@ -127,76 +115,6 @@ remove_if_exists() {
return 0
}
have() {
command -v "$1" >/dev/null 2>&1
}
trim_text() {
printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//'
}
load_env_value() {
local path="$1"
local key="$2"
awk -F= -v k="$key" '
$0 ~ "^[[:space:]]*" k "=" {
v = substr($0, index($0, "=") + 1)
gsub(/^[[:space:]]+|[[:space:]]+$/, "", v)
gsub(/^["\047]|["\047]$/, "", v)
print v
exit
}
' "$path" 2>/dev/null || true
}
get_system_hostname() {
local host=""
host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
host="$(trim_text "$host")"
[ -n "$host" ] || host="iomatex"
printf '%s\n' "$host"
}
get_ap_password_suffix() {
local host="$1"
local suffix=""
suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
[ ${#suffix} -eq 4 ] || { echo "ERROR: failed to derive AP password suffix from hostname '$host'" >&2; exit 1; }
printf '%s\n' "$suffix"
}
build_ap_ssid() {
printf 'Iomatex %s\n' "$1"
}
generate_factory_ap_password() {
local host="$1"
local password
password="iomatex$(get_ap_password_suffix "$host")"
[[ "$password" =~ ^[a-z0-9]{8,}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
printf '%s\n' "$password"
}
normalize_password_mode() {
local mode
mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')"
case "$mode" in
custom) printf 'custom\n' ;;
*) printf 'factory\n' ;;
esac
}
get_active_ap_password() {
local mode="$1"
local custom_password="$2"
local factory_password="$3"
if [[ "$mode" == "custom" && -n "$custom_password" ]]; then
printf '%s\n' "$custom_password"
return 0
fi
printf '%s\n' "$factory_password"
}
echo "[0/8] Validate source tree"
for path in \
"$SRC_ROOT/backend/app.py" \
@ -213,22 +131,13 @@ done
echo "[1/8] Ensure runtime packages exist"
apt-get update
apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw hostapd dnsmasq rfkill iptables
if update-alternatives --list iptables >/dev/null 2>&1; then
update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true
fi
if update-alternatives --list ip6tables >/dev/null 2>&1; then
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy >/dev/null 2>&1 || true
fi
apt-get install -y python3 python3-pil python3-paho-mqtt network-manager iw
python3 --version
echo "[1/8] Skip setcap: service runs as root and can bind port 80 without extra capabilities"
systemctl_try disable --now hostapd
systemctl_try disable --now dnsmasq
echo "[2/8] Stop previous service"
stop_disable_reset_unit "${SERVICE_NAME}"
stop_disable_reset_unit "${LEGACY_SERVICE_NAME}"
stop_disable_reset_unit "${LEGACY_WIFI_UI_SERVICE_NAME}"
echo "[3/8] Prepare directories and preserve previous install"
mkdir -p /etc/iomatex
@ -236,23 +145,8 @@ if [ -d "$LEGACY_APP_DIR" ]; then
rm -rf "$LEGACY_PREV_DIR"
mv "$LEGACY_APP_DIR" "$LEGACY_PREV_DIR"
fi
if [ -d "$LEGACY_WIFI_UI_DIR" ]; then
rm -rf "$LEGACY_WIFI_UI_PREV_DIR"
mv "$LEGACY_WIFI_UI_DIR" "$LEGACY_WIFI_UI_PREV_DIR"
fi
remove_if_exists "/etc/systemd/system/${LEGACY_WIFI_UI_SERVICE_NAME}"
rm -rf "$STAGE_DIR"
mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR" /etc/hostapd /etc/dnsmasq.d /usr/local/sbin
HOSTNAME_SHORT="$(get_system_hostname)"
FACTORY_AP_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
PASSWORD_MODE="$(normalize_password_mode "$(load_env_value /etc/iomatex/ap.env PASSWORD_MODE)")"
CUSTOM_PASSWORD="$(load_env_value /etc/iomatex/ap.env CUSTOM_PASSWORD)"
if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
PASSWORD_MODE="factory"
fi
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
ACTIVE_AP_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_AP_PASSWORD")"
mkdir -p "$STAGE_DIR" "$STAGE_PUBLIC_DIR" "$STAGE_BACKEND_DIR" "$STAGE_PROVIDERS_DIR" "$STAGE_FRONTEND_DIR"
cat > "$CFG_PATH" <<JSON
{
@ -262,53 +156,6 @@ cat > "$CFG_PATH" <<JSON
}
JSON
cat > /etc/iomatex/ap.env <<EOF
IFACE="${IFACE}"
AP_IP="${AP_IP}"
AP_CIDR="${AP_CIDR}"
DHCP_START="${DHCP_START}"
DHCP_END="${DHCP_END}"
DHCP_LEASE="${DHCP_LEASE}"
SSID="${SSID}"
PASSWORD_MODE="${PASSWORD_MODE}"
CUSTOM_PASSWORD="${CUSTOM_PASSWORD}"
UI_PORT="${UI_PORT}"
EOF
cat > /etc/hostapd/iomatex-ap.conf <<EOF
interface=${IFACE}
driver=nl80211
ssid=${SSID}
hw_mode=g
channel=${AP_CHANNEL}
country_code=${COUNTRY_CODE}
ieee80211n=1
wmm_enabled=1
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=${ACTIVE_AP_PASSWORD}
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
EOF
chmod 0600 /etc/hostapd/iomatex-ap.conf
cat > /etc/dnsmasq.d/iomatex-ap.conf <<EOF
interface=${IFACE}
bind-interfaces
port=53
domain-needed
bogus-priv
no-resolv
server=8.8.8.8
server=1.1.1.1
dhcp-range=${DHCP_START},${DHCP_END},${DHCP_LEASE}
dhcp-option=3,${AP_IP}
dhcp-option=6,${AP_IP}
dhcp-option=114,http://${AP_IP}/captive-portal
address=/#/${AP_IP}
EOF
echo "[4/8] Install console core files"
copy_tree "$SRC_ROOT/backend" "$STAGE_BACKEND_DIR"
copy_tree "$SRC_ROOT/frontend" "$STAGE_FRONTEND_DIR"
@ -325,482 +172,6 @@ require_file "$STAGE_FRONTEND_DIR/console.css"
require_file "$STAGE_PROVIDERS_DIR/00_core_services.py"
require_file "$SRC_GBOX"
echo "[5/8] Install Wi-Fi helper scripts"
cat > /usr/local/sbin/iomatex-ap-sync-config <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
ENV_PATH="/etc/iomatex/ap.env"
HOSTAPD_PATH="/etc/hostapd/iomatex-ap.conf"
COUNTRY_CODE="NL"
AP_CHANNEL="6"
trim_text() {
printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//'
}
get_system_hostname() {
local host=""
host="$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)"
host="$(trim_text "$host")"
[[ -n "$host" ]] || { echo "ERROR: failed to determine system hostname" >&2; exit 1; }
printf '%s\n' "$host"
}
get_ap_password_suffix() {
local host="$1"
local suffix=""
suffix="$(printf '%s' "$host" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9' | tail -c 4)"
[[ ${#suffix} -eq 4 ]] || { echo "ERROR: failed to derive AP password suffix from hostname '$host'" >&2; exit 1; }
printf '%s\n' "$suffix"
}
build_ap_ssid() { printf 'Iomatex %s\n' "$1"; }
generate_factory_ap_password() {
local host="$1"
local password
password="iomatex$(get_ap_password_suffix "$host")"
[[ "$password" =~ ^[a-z0-9]{8,}$ ]] || { echo "ERROR: failed to generate valid factory AP password" >&2; exit 1; }
printf '%s\n' "$password"
}
normalize_password_mode() {
local mode
mode="$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')"
case "$mode" in
custom) printf 'custom\n' ;;
*) printf 'factory\n' ;;
esac
}
get_active_ap_password() {
local mode="$1" custom_password="$2" factory_password="$3"
if [[ "$mode" == "custom" && -n "$custom_password" ]]; then
printf '%s\n' "$custom_password"
return 0
fi
printf '%s\n' "$factory_password"
}
IFACE="wlan0"
AP_IP="10.10.10.1"
AP_CIDR="${AP_IP}/24"
DHCP_START="10.10.10.50"
DHCP_END="10.10.10.150"
DHCP_LEASE="12h"
UI_PORT="80"
PASSWORD_MODE="factory"
CUSTOM_PASSWORD=""
if [[ -f "$ENV_PATH" ]]; then
. "$ENV_PATH"
fi
PASSWORD_MODE="$(normalize_password_mode "${PASSWORD_MODE:-factory}")"
CUSTOM_PASSWORD="${CUSTOM_PASSWORD:-}"
if [[ "$PASSWORD_MODE" == "custom" && -z "$CUSTOM_PASSWORD" ]]; then
PASSWORD_MODE="factory"
fi
HOSTNAME_SHORT="$(get_system_hostname)"
SSID="$(build_ap_ssid "$HOSTNAME_SHORT")"
FACTORY_PASSWORD="$(generate_factory_ap_password "$HOSTNAME_SHORT")"
ACTIVE_PASSWORD="$(get_active_ap_password "$PASSWORD_MODE" "$CUSTOM_PASSWORD" "$FACTORY_PASSWORD")"
tmp_env="$(mktemp)"
cat >"$tmp_env" <<ENVEOF
IFACE="$IFACE"
AP_IP="$AP_IP"
AP_CIDR="$AP_CIDR"
DHCP_START="$DHCP_START"
DHCP_END="$DHCP_END"
DHCP_LEASE="$DHCP_LEASE"
SSID="$SSID"
PASSWORD_MODE="$PASSWORD_MODE"
CUSTOM_PASSWORD="$CUSTOM_PASSWORD"
UI_PORT="$UI_PORT"
ENVEOF
install -D -m 0644 "$tmp_env" "$ENV_PATH"
rm -f "$tmp_env"
tmp_hostapd="$(mktemp)"
cat >"$tmp_hostapd" <<HOSTEOF
interface=$IFACE
driver=nl80211
ssid=$SSID
hw_mode=g
channel=$AP_CHANNEL
country_code=$COUNTRY_CODE
ieee80211n=1
wmm_enabled=1
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=$ACTIVE_PASSWORD
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
HOSTEOF
install -D -m 0600 "$tmp_hostapd" "$HOSTAPD_PATH"
rm -f "$tmp_hostapd"
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-sync-config
cat > /usr/local/sbin/iomatex-ap-reset-password <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
ENV_PATH="/etc/iomatex/ap.env"
IFACE="wlan0"
AP_IP="10.10.10.1"
AP_CIDR="${AP_IP}/24"
DHCP_START="10.10.10.50"
DHCP_END="10.10.10.150"
DHCP_LEASE="12h"
UI_PORT="80"
SSID=""
if [[ -f "$ENV_PATH" ]]; then
. "$ENV_PATH"
fi
tmp_env="$(mktemp)"
cat >"$tmp_env" <<ENVEOF
IFACE="$IFACE"
AP_IP="$AP_IP"
AP_CIDR="$AP_CIDR"
DHCP_START="$DHCP_START"
DHCP_END="$DHCP_END"
DHCP_LEASE="$DHCP_LEASE"
SSID="$SSID"
PASSWORD_MODE="factory"
CUSTOM_PASSWORD=""
UI_PORT="$UI_PORT"
ENVEOF
install -D -m 0644 "$tmp_env" "$ENV_PATH"
rm -f "$tmp_env"
/usr/local/sbin/iomatex-ap-sync-config
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true
fi
/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true
echo "OK: AP password reset to factory mode"
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-reset-password
cat > /usr/local/sbin/iomatex-ap-up <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
/usr/local/sbin/iomatex-ap-sync-config >/dev/null 2>&1 || true
. /etc/iomatex/ap.env
rfkill unblock all >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev disconnect "$IFACE" >/dev/null 2>&1 || true
nmcli dev set "$IFACE" managed no >/dev/null 2>&1 || true
fi
ip link set "$IFACE" up >/dev/null 2>&1 || true
ip addr flush dev "$IFACE" >/dev/null 2>&1 || true
ip addr add "$AP_CIDR" dev "$IFACE"
systemctl start iomatex-console.service >/dev/null 2>&1 || true
systemctl start iomatex-dnsmasq.service
systemctl start iomatex-hostapd.service
iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
iptables -t nat -A PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-up
cat > /usr/local/sbin/iomatex-ap-down <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
systemctl stop iomatex-hostapd.service 2>/dev/null || true
systemctl stop iomatex-dnsmasq.service 2>/dev/null || true
iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
ip addr flush dev "$IFACE" 2>/dev/null || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true
fi
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-down
cat > /usr/local/sbin/iomatex-wifi-status <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
ap_active=0
systemctl is-active --quiet iomatex-hostapd.service && ap_active=1
nm_state="n/a"
nm_con="n/a"
if command -v nmcli >/dev/null 2>&1; then
nm_state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)"
nm_con="$(nmcli -t -f DEVICE,CONNECTION dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)"
fi
sta_connected=no
if command -v iw >/dev/null 2>&1; then
iw dev "$IFACE" link 2>/dev/null | grep -q "^Connected to " && sta_connected=yes
fi
ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
echo "IFACE=$IFACE"
echo "AP_ACTIVE=$ap_active"
echo "NM_STATE=$nm_state"
echo "NM_CONNECTION=$nm_con"
echo "STA_CONNECTED=$sta_connected"
echo "IP4=$ip4"
echo "WATCH_STATE=$(cat /run/iomatex-ap.state 2>/dev/null || echo n/a)"
EOF
chmod 0755 /usr/local/sbin/iomatex-wifi-status
cat > /usr/local/sbin/iomatex-wifi-setup <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
SSID_IN="${1:-}"
PASS_IN="${2:-}"
[ -n "$SSID_IN" ] || { echo "ERROR: SSID required" >&2; exit 2; }
command -v nmcli >/dev/null 2>&1 || { echo "ERROR: nmcli not found" >&2; exit 3; }
LOCK="/run/iomatex-wifi-setup.lock"
exec 9>"$LOCK"
flock -n 9 || { echo "ERROR: busy" >&2; exit 4; }
AP_LOCK="/run/iomatex-ap.lock"
exec 8>"$AP_LOCK"
flock 8
CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)"
[ -n "$CN" ] || CN="iomatex-wifi"
sta_ok() {
nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1
ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1
return 0
}
wait_for_nm_device_ready() {
local attempt state=""
for attempt in $(seq 1 20); do
state="$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d="$IFACE" '$1==d{print $2; exit}' || true)"
case "$state" in
disconnected|connecting|connected)
return 0
;;
esac
sleep 1
done
echo "ERROR: NetworkManager did not reclaim $IFACE (state=${state:-unknown})" >&2
return 1
}
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
nmcli dev set "$IFACE" managed yes >/dev/null 2>&1 || true
ip addr flush dev "$IFACE" >/dev/null 2>&1 || true
ip link set "$IFACE" up >/dev/null 2>&1 || true
wait_for_nm_device_ready
existing_type="$(nmcli -g connection.type con show "$CN" 2>/dev/null || true)"
case "$existing_type" in
"" )
nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null
;;
wifi|802-11-wireless)
nmcli con mod "$CN" connection.interface-name "$IFACE" 802-11-wireless.ssid "$SSID_IN" >/dev/null
;;
* )
nmcli con delete id "$CN" >/dev/null 2>&1 || true
nmcli con add type wifi ifname "$IFACE" con-name "$CN" ssid "$SSID_IN" >/dev/null
;;
esac
if [ -n "$PASS_IN" ]; then
nmcli con mod "$CN" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$PASS_IN" >/dev/null
else
nmcli con mod "$CN" wifi-sec.key-mgmt none >/dev/null 2>&1 || true
fi
nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null
up_output=""
if ! up_output="$(nmcli --wait 25 con up id "$CN" 2>&1)"; then
echo "ERROR: failed to start Wi-Fi profile '$CN': ${up_output}" >&2
else
echo "INFO: Wi-Fi profile '$CN' activation requested: ${up_output}" >&2
fi
sleep 10
if sta_ok; then
ip4="$(ip -4 -o addr show dev "$IFACE" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
{ echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; echo "WIFI_IP4=\"${ip4:-}\""; } > /etc/iomatex/wifi.env
chmod 0644 /etc/iomatex/wifi.env
echo "OK: STA connected (profile=$CN) IP=${ip4:-n/a}"
exit 0
fi
/usr/local/sbin/iomatex-ap-up >/dev/null 2>&1 || true
echo "ERROR: STA not connected / no IPv4; AP restored (NM_STATE=$(nmcli -t -f DEVICE,STATE dev | awk -F: -v d=\"$IFACE\" '\$1==d{print \$2; exit}' || echo unknown))" >&2
exit 10
EOF
chmod 0755 /usr/local/sbin/iomatex-wifi-setup
cat > /usr/local/sbin/iomatex-ap-watch <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
STATE="/run/iomatex-ap.state"
LOCK="/run/iomatex-ap.lock"
exec 9>"$LOCK"
flock -n 9 || exit 0
eth_ok() {
[ "$(cat /sys/class/net/eth0/carrier 2>/dev/null || echo 0)" = "1" ] || return 1
return 0
}
sta_ok() {
command -v nmcli >/dev/null 2>&1 || return 1
nmcli -t -f DEVICE,STATE dev | grep -q "^${IFACE}:connected$" || return 1
ip -4 -o addr show dev "$IFACE" 2>/dev/null | grep -q "inet " || return 1
return 0
}
ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; }
if eth_ok || sta_ok; then
ap_is_up && /usr/local/sbin/iomatex-ap-down || true
echo "uplink_ok" > "$STATE"
exit 0
fi
ap_is_up || /usr/local/sbin/iomatex-ap-up
echo "ap_on_no_uplink" > "$STATE"
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-watch
cat > /usr/local/sbin/iomatex-ap-resetd <<'EOF'
#!/usr/bin/env python3
import os
import select
import struct
import subprocess
import sys
import time
EVENT_PATH = "/dev/input/event8"
RESET_HELPER = "/usr/local/sbin/iomatex-ap-reset-password"
EV_KEY = 0x01
KEY_VOLUMEUP = 115
INPUT_EVENT = struct.Struct("llHHI")
HOLD_SECONDS = 10.0
RETRY_DELAY_SECONDS = 1.0
def log(message):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(f"[{timestamp} UTC] {message}", flush=True)
def run_reset():
result = subprocess.run(
[RESET_HELPER],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
output = (result.stdout or "").strip()
if result.returncode == 0:
log(f"AP password reset helper completed: {output or 'success'}")
return True
log(f"ERROR: AP password reset helper failed: {output or result.returncode}")
return False
def main():
pressed_since = None
reset_triggered = False
event_fd = None
last_open_error = 0.0
log("iomatex-ap-resetd started")
while True:
now = time.monotonic()
if event_fd is None:
try:
event_fd = os.open(EVENT_PATH, os.O_RDONLY)
log(f"button device opened: {EVENT_PATH}")
except Exception as exc:
if now - last_open_error >= 30.0:
log(f"WARNING: failed to open button device {EVENT_PATH}: {exc}")
last_open_error = now
time.sleep(RETRY_DELAY_SECONDS)
continue
if pressed_since is not None and not reset_triggered and now - pressed_since >= HOLD_SECONDS:
reset_triggered = True
log(f"reset threshold reached: hold duration {now - pressed_since:.1f}s")
if run_reset():
log("AP password reset to factory")
try:
readable, _, _ = select.select([event_fd], [], [], 0.1)
except OSError as exc:
log(f"WARNING: button device select failed, reopening: {exc}")
try:
os.close(event_fd)
except Exception:
pass
event_fd = None
pressed_since = None
reset_triggered = False
continue
if not readable:
continue
payload = os.read(event_fd, INPUT_EVENT.size)
if len(payload) != INPUT_EVENT.size:
continue
_, _, event_type, event_code, event_value = INPUT_EVENT.unpack(payload)
if event_type != EV_KEY or event_code != KEY_VOLUMEUP:
continue
if event_value == 1:
if pressed_since is None:
pressed_since = time.monotonic()
reset_triggered = False
log("button press detected")
elif event_value == 0:
hold = 0.0 if pressed_since is None else time.monotonic() - pressed_since
log(f"button release detected: hold duration {hold:.1f}s")
pressed_since = None
reset_triggered = False
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
except Exception as exc:
log(f"FATAL: {exc}")
sys.exit(1)
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-resetd
echo "[6/8] Generate logo and favicon"
if [ ! -f "$SRC_LOGO" ]; then
echo "ERROR: logo source image not found: $SRC_LOGO" >&2
@ -825,38 +196,6 @@ fav.save(fav_out, format="PNG")
PY
echo "[7/8] Install systemd service"
cat > /etc/systemd/system/iomatex-hostapd.service <<'UNIT'
[Unit]
Description=IOMATEX hostapd (AP)
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/sbin/hostapd -dd /etc/hostapd/iomatex-ap.conf
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
cat > /etc/systemd/system/iomatex-dnsmasq.service <<'UNIT'
[Unit]
Description=IOMATEX dnsmasq (DHCP/DNS for AP)
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-ap.conf
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
cat > "/etc/systemd/system/${SERVICE_NAME}" <<UNIT
[Unit]
Description=IOMATEX Console Core
@ -876,47 +215,6 @@ Group=root
WantedBy=multi-user.target
UNIT
cat > /etc/systemd/system/iomatex-ap-watch.service <<'UNIT'
[Unit]
Description=IOMATEX AP Watch
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-ap-watch
UNIT
cat > /etc/systemd/system/iomatex-ap-watch.timer <<'UNIT'
[Unit]
Description=IOMATEX AP Watch timer
[Timer]
OnBootSec=20
OnUnitActiveSec=15
AccuracySec=2
Unit=iomatex-ap-watch.service
[Install]
WantedBy=timers.target
UNIT
cat > /etc/systemd/system/iomatex-ap-resetd.service <<'UNIT'
[Unit]
Description=IOMATEX AP password reset daemon
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/local/sbin/iomatex-ap-resetd
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
UNIT
echo "[8/8] Remove optional mDNS alias artifacts"
remove_if_exists /etc/avahi/services/iomatex-console.service
remove_if_exists /usr/local/sbin/iomatex-mdns-alias
@ -924,7 +222,6 @@ remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service
echo "[9/9] Validate and restart"
python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_PROVIDERS_DIR/00_core_services.py"
python3 -m py_compile /usr/local/sbin/iomatex-ap-resetd
require_file "$STAGE_PUBLIC_DIR/index.html"
require_file "$STAGE_PUBLIC_DIR/console.js"
require_file "$STAGE_PUBLIC_DIR/console.css"
@ -941,24 +238,11 @@ require_file "$FRONTEND_DIR/console.css"
require_file "$PROVIDERS_DIR/00_core_services.py"
systemctl daemon-reload
systemctl_try disable --now iomatex-mdns-alias.service
systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true
systemctl enable iomatex-ap-resetd.service >/dev/null 2>&1 || true
if ! systemctl enable --now "${SERVICE_NAME}"; then
echo "ERROR: failed to start ${SERVICE_NAME}; rolling back deploy" >&2
rollback_deploy
exit 1
fi
if systemctl is-active --quiet iomatex-ap-watch.timer; then
systemctl_try restart iomatex-ap-watch.timer
else
systemctl_try start iomatex-ap-watch.timer
fi
if systemctl is-active --quiet iomatex-ap-resetd.service; then
systemctl_try restart iomatex-ap-resetd.service
else
systemctl_try start iomatex-ap-resetd.service
fi
/usr/local/sbin/iomatex-ap-watch >/dev/null 2>&1 || true
if ! systemctl is-active --quiet "${SERVICE_NAME}"; then
echo "ERROR: ${SERVICE_NAME} is not active after restart; rolling back deploy" >&2
rollback_deploy
@ -985,4 +269,3 @@ echo "Public dir: ${PUBLIC_DIR}"
echo "Config: ${CFG_PATH}"
echo "Previous install backup: ${PREV_DIR}"
echo "Legacy backup: ${LEGACY_PREV_DIR}"
echo "Legacy Wi-Fi UI backup: ${LEGACY_WIFI_UI_PREV_DIR}"

View File

@ -1,708 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
# ======================================
# IOMATEX FAILBACK (FINAL, PRODUCTION-SAFE, NO-GRACE)
# Debian 11 / NetworkManager
#
# Modes:
# A) eth0 production uplink (IPv4 + default route via eth0) -> AP OFF, ETH failback OFF
# B) eth0 cable present but NO production uplink -> AP OFF, ETH failback ON (10.10.10.2/24 + DHCP)
# C) no eth0 cable:
# - if Wi-Fi STA connected -> AP OFF
# - else -> AP ON (10.10.10.1/24 + captive HTTP->UI)
#
# UI:
# - always listens on 0.0.0.0:18080 (reachable via AP/ETH/STA IP)
#
# Addresses:
# - wlan0 AP : 10.10.10.1/24
# - eth0 FB : 10.10.10.2/24
#
# ======================================
# --- Notepad++/Windows safety guards (BOM + CRLF) ---
if head -c 3 "$0" 2>/dev/null | grep -q $'^\xEF\xBB\xBF'; then
echo "ERROR: UTF-8 BOM detected. Save as UTF-8 (without BOM)." >&2
exit 1
fi
if grep -q $'\r' "$0" 2>/dev/null; then
echo "ERROR: CRLF detected. Convert file to UNIX (LF) EOL in Notepad++." >&2
exit 1
fi
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export DEBIAN_FRONTEND=noninteractive
LOG="/var/log/iomatex-failback-install.log"
mkdir -p /var/log >/dev/null 2>&1 || true
exec > >(tee -a "$LOG") 2>&1
# ---------- Config ----------
WLAN_IF="wlan0"
ETH_IF="eth0"
AP_IP="10.10.10.1"
AP_CIDR="${AP_IP}/24"
AP_DHCP_START="10.10.10.50"
AP_DHCP_END="10.10.10.150"
AP_DHCP_LEASE="12h"
ETH_FB_IP="10.10.10.2"
ETH_FB_CIDR="${ETH_FB_IP}/24"
ETH_DHCP_START="10.10.10.200"
ETH_DHCP_END="10.10.10.230"
ETH_DHCP_LEASE="12h"
UI_PORT="18080"
AP_SSID="$(hostname -s)"
AP_PASS="iomatex123"
COUNTRY_CODE="NL"
AP_CHANNEL="6"
ts="$(date +%Y%m%d-%H%M%S)"
backup_if_exists() { local f="$1"; [[ -e "$f" ]] && cp -a "$f" "${f}.bak.${ts}" || true; }
echo "=== IOMATEX Failback installer (FINAL, prod-safe, no-grace) ==="
date -u +"UTC: %F %T"
echo "Log: $LOG"
echo
echo "WLAN_IF=$WLAN_IF AP=${AP_CIDR} SSID=${AP_SSID} UI=${UI_PORT}"
echo "ETH_IF=$ETH_IF FB=${ETH_FB_CIDR}"
echo
# ---------- Preflight ----------
if [[ ${EUID:-$(id -u)} -ne 0 ]]; then
echo "ERROR: Run as root: sudo bash $0" >&2
exit 1
fi
# ---------- Packages ----------
echo "[1/10] Install packages..."
apt-get update -y
apt-get install -y hostapd dnsmasq iw rfkill python3 network-manager iptables iproute2 curl
echo "[2/10] Prefer iptables-legacy if available..."
if update-alternatives --list iptables >/dev/null 2>&1; then
update-alternatives --set iptables /usr/sbin/iptables-legacy >/dev/null 2>&1 || true
fi
if update-alternatives --list ip6tables >/dev/null 2>&1; then
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy >/dev/null 2>&1 || true
fi
echo "[3/10] Stop/disable stock services (we use our own units)..."
systemctl disable --now hostapd 2>/dev/null || true
systemctl disable --now dnsmasq 2>/dev/null || true
# ---------- Paths ----------
echo "[4/10] Write configs..."
mkdir -p /etc/iomatex /etc/hostapd /etc/dnsmasq.d /opt/iomatex-wifi-ui /usr/local/sbin
backup_if_exists /etc/iomatex/failback.env
cat > /etc/iomatex/failback.env <<EOF
WLAN_IF="$WLAN_IF"
ETH_IF="$ETH_IF"
AP_IP="$AP_IP"
AP_CIDR="$AP_CIDR"
AP_DHCP_START="$AP_DHCP_START"
AP_DHCP_END="$AP_DHCP_END"
AP_DHCP_LEASE="$AP_DHCP_LEASE"
ETH_FB_IP="$ETH_FB_IP"
ETH_FB_CIDR="$ETH_FB_CIDR"
ETH_DHCP_START="$ETH_DHCP_START"
ETH_DHCP_END="$ETH_DHCP_END"
ETH_DHCP_LEASE="$ETH_DHCP_LEASE"
UI_PORT="$UI_PORT"
AP_SSID="$AP_SSID"
AP_PASS="$AP_PASS"
COUNTRY_CODE="$COUNTRY_CODE"
AP_CHANNEL="$AP_CHANNEL"
EOF
chmod 0644 /etc/iomatex/failback.env
backup_if_exists /etc/hostapd/iomatex-ap.conf
cat > /etc/hostapd/iomatex-ap.conf <<EOF
interface=${WLAN_IF}
driver=nl80211
ssid=${AP_SSID}
hw_mode=g
channel=${AP_CHANNEL}
country_code=${COUNTRY_CODE}
ieee80211n=1
wmm_enabled=1
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=${AP_PASS}
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP
EOF
chmod 0600 /etc/hostapd/iomatex-ap.conf
backup_if_exists /etc/dnsmasq.d/iomatex-ap.conf
cat > /etc/dnsmasq.d/iomatex-ap.conf <<EOF
# IOMATEX AP DHCP/DNS (wlan0)
interface=${WLAN_IF}
bind-interfaces
port=53
domain-needed
bogus-priv
no-resolv
server=8.8.8.8
server=1.1.1.1
dhcp-authoritative
dhcp-range=${AP_DHCP_START},${AP_DHCP_END},${AP_DHCP_LEASE}
dhcp-option=3,${AP_IP}
dhcp-option=6,${AP_IP}
# DNS hijack: all domains -> AP IP
address=/#/${AP_IP}
EOF
chmod 0644 /etc/dnsmasq.d/iomatex-ap.conf
backup_if_exists /etc/dnsmasq.d/iomatex-eth.conf
cat > /etc/dnsmasq.d/iomatex-eth.conf <<EOF
# IOMATEX ETH direct failback DHCP-only (eth0)
interface=${ETH_IF}
bind-interfaces
dhcp-authoritative
dhcp-range=${ETH_DHCP_START},${ETH_DHCP_END},${ETH_DHCP_LEASE}
dhcp-option=1,255.255.255.0
# Do NOT provide default gateway (laptop keeps Wi-Fi internet)
dhcp-option=3,0.0.0.0
# Provide public DNS (for laptop via Wi-Fi)
dhcp-option=6,1.1.1.1,8.8.8.8
# DHCP-only
port=0
EOF
chmod 0644 /etc/dnsmasq.d/iomatex-eth.conf
# ---------- systemd units ----------
echo "[5/10] systemd units..."
backup_if_exists /etc/systemd/system/iomatex-hostapd.service
cat > /etc/systemd/system/iomatex-hostapd.service <<'EOF'
[Unit]
Description=IOMATEX hostapd (Wi-Fi AP)
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/sbin/hostapd -dd /etc/hostapd/iomatex-ap.conf
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
backup_if_exists /etc/systemd/system/iomatex-dnsmasq-ap.service
cat > /etc/systemd/system/iomatex-dnsmasq-ap.service <<'EOF'
[Unit]
Description=IOMATEX dnsmasq (AP DHCP/DNS)
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-ap.conf
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
backup_if_exists /etc/systemd/system/iomatex-dnsmasq-eth.service
cat > /etc/systemd/system/iomatex-dnsmasq-eth.service <<'EOF'
[Unit]
Description=IOMATEX dnsmasq (ETH DHCP-only)
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/sbin/dnsmasq --no-daemon --conf-file=/etc/dnsmasq.d/iomatex-eth.conf
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
# ---------- UI app ----------
cat > /opt/iomatex-wifi-ui/app.py <<'PY'
#!/usr/bin/env python3
import json, urllib.parse, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
def run(cmd):
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
return p.returncode, (p.stdout or "").strip()
HTML = """<!doctype html><html><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>IOMATEX Wi-Fi Setup</title>
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial;margin:24px;max-width:760px}
.card{border:1px solid #ddd;border-radius:12px;padding:16px;margin:12px 0}
label{display:block;margin:8px 0 4px}
input{width:100%;padding:10px;border:1px solid #ccc;border-radius:10px}
button{padding:10px 14px;border-radius:10px;border:1px solid #111;background:#111;color:#fff;cursor:pointer}
.small{color:#666;font-size:13px}
pre{white-space:pre-wrap;background:#f6f6f6;border-radius:10px;padding:12px}
</style></head><body>
<h2>IOMATEX Wi-Fi Setup</h2>
<div class="card">
<b>Status</b>
<pre id="raw">Loading…</pre>
<button onclick="refresh()">Refresh</button>
</div>
<div class="card">
<b>Connect to external Wi-Fi</b>
<div class="small">In AP/ETH mode scanning may be unavailable; enter SSID manually.</div>
<label>SSID</label><input id="ssid" placeholder="e.g. HotelWiFi">
<label>Password</label><input id="pass" type="password" placeholder="(empty = open network)">
<div style="margin-top:12px"><button onclick="connect()">Connect</button></div>
<div class="small" id="msg" style="margin-top:10px"></div>
</div>
<script>
async function refresh(){
const r = await fetch("/api/status"); const j = await r.json();
document.getElementById("raw").textContent = j.output || "";
}
async function connect(){
const ssid=document.getElementById("ssid").value.trim();
const pass=document.getElementById("pass").value;
const msg=document.getElementById("msg");
if(!ssid){ msg.textContent="SSID required"; return; }
msg.textContent="Connecting…";
const r = await fetch("/api/connect",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},
body:new URLSearchParams({ssid,pass}).toString()});
const j = await r.json();
msg.textContent = (j.ok ? "OK: " : "ERROR: ") + (j.output || "");
await refresh();
}
refresh();
</script>
</body></html>
"""
class H(BaseHTTPRequestHandler):
def address_string(self):
return self.client_address[0]
def log_message(self, fmt, *args):
return
def _send(self, code, body, ctype):
b = body.encode("utf-8") if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def do_GET(self):
if self.path.startswith("/api/status"):
rc, out = run(["/usr/local/sbin/iomatex-failback-status"])
self._send(200, json.dumps({"ok": rc == 0, "output": out}), "application/json")
return
self._send(200, HTML, "text/html; charset=utf-8")
def do_POST(self):
if self.path.startswith("/api/connect"):
n = int(self.headers.get("Content-Length", "0"))
data = self.rfile.read(n).decode("utf-8", "ignore")
form = urllib.parse.parse_qs(data)
ssid = (form.get("ssid", [""])[0] or "").strip()
pw = (form.get("pass", [""])[0] or "")
if not ssid:
self._send(400, json.dumps({"ok": False, "output": "SSID required"}), "application/json")
return
rc, out = run(["/usr/local/sbin/iomatex-wifi-setup", ssid, pw])
self._send(200, json.dumps({"ok": rc == 0, "rc": rc, "output": out}), "application/json")
return
self._send(404, "Not Found", "text/plain; charset=utf-8")
def main():
HTTPServer.allow_reuse_address = True
HTTPServer(("0.0.0.0", 18080), H).serve_forever()
if __name__ == "__main__":
main()
PY
chmod 0755 /opt/iomatex-wifi-ui/app.py
backup_if_exists /etc/systemd/system/iomatex-wifi-ui.service
cat > /etc/systemd/system/iomatex-wifi-ui.service <<'EOF'
[Unit]
Description=IOMATEX Wi-Fi Setup UI
After=network.target
Wants=network.target
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/iomatex-wifi-ui/app.py
Restart=on-failure
RestartSec=2
[Install]
WantedBy=multi-user.target
EOF
# ---------- Control scripts ----------
echo "[6/10] Control scripts..."
# Captive iptables chain (no flushing PREROUTING)
cat > /usr/local/sbin/iomatex-iptables-captive <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
CHAIN="IOMATEX_CAPTIVE"
ensure_chain() {
iptables -t nat -L "$CHAIN" >/dev/null 2>&1 || iptables -t nat -N "$CHAIN"
iptables -t nat -C PREROUTING -j "$CHAIN" >/dev/null 2>&1 || iptables -t nat -I PREROUTING 1 -j "$CHAIN"
}
enable() {
ensure_chain
iptables -t nat -C "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} >/dev/null 2>&1 \
|| iptables -t nat -A "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT}
}
disable() {
iptables -t nat -D "$CHAIN" -i "$WLAN_IF" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} >/dev/null 2>&1 || true
}
case "${1:-}" in
on) enable ;;
off) disable ;;
*) echo "usage: $0 on|off" >&2; exit 2 ;;
esac
EOF
chmod 0755 /usr/local/sbin/iomatex-iptables-captive
cat > /usr/local/sbin/iomatex-ap-up <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
rfkill unblock all >/dev/null 2>&1 || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev disconnect "$WLAN_IF" >/dev/null 2>&1 || true
nmcli dev set "$WLAN_IF" managed no >/dev/null 2>&1 || true
fi
ip link set "$WLAN_IF" up >/dev/null 2>&1 || true
ip addr flush dev "$WLAN_IF" >/dev/null 2>&1 || true
ip addr add "$AP_CIDR" dev "$WLAN_IF"
systemctl start iomatex-dnsmasq-ap.service
systemctl start iomatex-hostapd.service
/usr/local/sbin/iomatex-iptables-captive on >/dev/null 2>&1 || true
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-up
cat > /usr/local/sbin/iomatex-ap-down <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
systemctl stop iomatex-hostapd.service 2>/dev/null || true
systemctl stop iomatex-dnsmasq-ap.service 2>/dev/null || true
/usr/local/sbin/iomatex-iptables-captive off >/dev/null 2>&1 || true
ip addr flush dev "$WLAN_IF" 2>/dev/null || true
if command -v nmcli >/dev/null 2>&1; then
nmcli dev set "$WLAN_IF" managed yes >/dev/null 2>&1 || true
fi
EOF
chmod 0755 /usr/local/sbin/iomatex-ap-down
cat > /usr/local/sbin/iomatex-eth-fb-up <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
ip link set "$ETH_IF" up >/dev/null 2>&1 || true
# Add fallback IP only if absent
if ! ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | grep -q "^${ETH_FB_IP}/"; then
ip addr add "$ETH_FB_CIDR" dev "$ETH_IF" 2>/dev/null || true
fi
systemctl start iomatex-dnsmasq-eth.service
EOF
chmod 0755 /usr/local/sbin/iomatex-eth-fb-up
cat > /usr/local/sbin/iomatex-eth-fb-down <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
systemctl stop iomatex-dnsmasq-eth.service 2>/dev/null || true
ip addr del "$ETH_FB_CIDR" dev "$ETH_IF" 2>/dev/null || true
EOF
chmod 0755 /usr/local/sbin/iomatex-eth-fb-down
cat > /usr/local/sbin/iomatex-wifi-setup <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
SSID_IN="${1:-}"
PASS_IN="${2:-}"
[[ -n "$SSID_IN" ]] || { echo "ERROR: SSID required" >&2; exit 2; }
command -v nmcli >/dev/null 2>&1 || { echo "ERROR: nmcli not found" >&2; exit 3; }
LOCK="/run/iomatex-wifi-setup.lock"
exec 9>"$LOCK"
flock -n 9 || { echo "ERROR: busy" >&2; exit 4; }
sta_ok() {
nmcli -t -f DEVICE,STATE dev | grep -q "^${WLAN_IF}:connected$" || return 1
ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | grep -q "inet " || return 1
return 0
}
# Ensure AP is down to return wlan0 to NM
/usr/local/sbin/iomatex-ap-down >/dev/null 2>&1 || true
nmcli dev set "$WLAN_IF" managed yes >/dev/null 2>&1 || true
ip addr flush dev "$WLAN_IF" >/dev/null 2>&1 || true
ip link set "$WLAN_IF" up >/dev/null 2>&1 || true
CN="$(echo "$SSID_IN" | tr -cd "[:alnum:] ._-" | sed -E "s/[[:space:]]+/ /g" | cut -c1-64)"
[[ -n "$CN" ]] || CN="iomatex-wifi"
nmcli con delete id "$CN" >/dev/null 2>&1 || true
nmcli con add type wifi ifname "$WLAN_IF" con-name "$CN" ssid "$SSID_IN" >/dev/null
if [[ -n "$PASS_IN" ]]; then
nmcli con mod "$CN" wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$PASS_IN" >/dev/null
else
nmcli con mod "$CN" wifi-sec.key-mgmt none >/dev/null 2>&1 || true
fi
nmcli con mod "$CN" connection.autoconnect yes connection.autoconnect-priority 10 ipv4.method auto ipv6.method ignore >/dev/null
nmcli dev disconnect "$WLAN_IF" >/dev/null 2>&1 || true
nmcli con up id "$CN" >/dev/null 2>&1 || true
sleep 10
if sta_ok; then
ip4="$(ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
{ echo "WIFI_PROFILE=\"$CN\""; echo "WIFI_SSID=\"$SSID_IN\""; echo "WIFI_IP4=\"${ip4:-}\""; } > /etc/iomatex/wifi.env
chmod 0644 /etc/iomatex/wifi.env
echo "OK: STA connected (profile=$CN) IP=${ip4:-n/a}"
exit 0
fi
echo "ERROR: STA not connected / no IPv4" >&2
exit 10
EOF
chmod 0755 /usr/local/sbin/iomatex-wifi-setup
cat > /usr/local/sbin/iomatex-failback-status <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
ap_active=0; systemctl is-active --quiet iomatex-hostapd.service && ap_active=1
eth_dhcp=0; systemctl is-active --quiet iomatex-dnsmasq-eth.service && eth_dhcp=1
sta_connected=no
if command -v iw >/dev/null 2>&1; then
iw dev "$WLAN_IF" link 2>/dev/null | grep -q "^Connected to " && sta_connected=yes
fi
wlan_ip4="$(ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | awk '{print $4}' | head -n1 || true)"
eth_ip4_list="$(ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | tr '\n' ' ' || true)"
def_eth="$(ip -4 route show default dev "$ETH_IF" 2>/dev/null | head -n1 || true)"
state="$(cat /run/iomatex-failback.state 2>/dev/null || echo n/a)"
echo "STATE=${state}"
echo
echo "WLAN_IF=${WLAN_IF}"
echo " AP_ACTIVE=${ap_active} (AP=${AP_CIDR})"
echo " STA_CONNECTED=${sta_connected}"
echo " IP4=${wlan_ip4:-none}"
echo
echo "ETH_IF=${ETH_IF}"
echo " DHCP_ACTIVE=${eth_dhcp} (FB=${ETH_FB_CIDR})"
echo " IP4_LIST=${eth_ip4_list:-none}"
echo " DEFAULT_ROUTE_ETH=${def_eth:-none}"
echo
echo "UI:"
echo " AP : http://${AP_IP}:${UI_PORT}"
echo " ETH : http://${ETH_FB_IP}:${UI_PORT}"
if [[ -n "${wlan_ip4:-}" ]]; then
echo " STA : http://${wlan_ip4%/*}:${UI_PORT}"
fi
EOF
chmod 0755 /usr/local/sbin/iomatex-failback-status
cat > /usr/local/sbin/iomatex-ip <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
echo "HOSTNAME=$(hostname -s)"
echo "---- eth0 ----"; ip -4 addr show dev "$ETH_IF" 2>/dev/null || true
echo "---- wlan0 ----"; ip -4 addr show dev "$WLAN_IF" 2>/dev/null || true
echo "---- default ----"; ip -4 route show default 2>/dev/null || true
echo "---- tips ----"
echo "AP mode : UI http://${AP_IP}:${UI_PORT} ; SSH -> ${AP_IP}"
echo "ETH mode: UI http://${ETH_FB_IP}:${UI_PORT} ; SSH -> ${ETH_FB_IP}"
EOF
chmod 0755 /usr/local/sbin/iomatex-ip
# ---------- Watcher (NO-GRACE, prod-safe) ----------
echo "[7/10] Watcher (enforces policy, no-grace)..."
cat > /usr/local/sbin/iomatex-failback-watch <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/failback.env
STATE="/run/iomatex-failback.state"
LOCK="/run/iomatex-failback.lock"
exec 9>"$LOCK"
flock -n 9 || exit 0
eth_carrier_up() {
[[ -r "/sys/class/net/${ETH_IF}/carrier" ]] && [[ "$(cat "/sys/class/net/${ETH_IF}/carrier" 2>/dev/null || echo 0)" == "1" ]]
}
eth_has_non_fallback_ipv4() {
ip -4 -o addr show dev "$ETH_IF" 2>/dev/null | awk '{print $4}' | grep -v -q "^${ETH_FB_IP}/"
}
eth_has_default_route() {
ip -4 route show default dev "$ETH_IF" 2>/dev/null | grep -q "^default "
}
# Production uplink ONLY if: non-fallback IPv4 + default route via eth0
eth_prod_ok() {
eth_has_non_fallback_ipv4 && eth_has_default_route
}
sta_ok() {
command -v nmcli >/dev/null 2>&1 || return 1
nmcli -t -f DEVICE,STATE dev | grep -q "^${WLAN_IF}:connected$" || return 1
ip -4 -o addr show dev "$WLAN_IF" 2>/dev/null | grep -q "inet " || return 1
return 0
}
ap_is_up() { systemctl is-active --quiet iomatex-hostapd.service; }
eth_fb_is_up() { systemctl is-active --quiet iomatex-dnsmasq-eth.service; }
set_state() { echo "$1" > "$STATE"; }
# 1) Production via eth0 -> no failbacks, AP off
if eth_prod_ok; then
eth_fb_is_up && /usr/local/sbin/iomatex-eth-fb-down || true
ap_is_up && /usr/local/sbin/iomatex-ap-down || true
set_state "prod_eth_ok"
exit 0
fi
# 2) If cable present and not production -> ETH failback ON, AP OFF
if eth_carrier_up; then
ap_is_up && /usr/local/sbin/iomatex-ap-down || true
eth_fb_is_up || /usr/local/sbin/iomatex-eth-fb-up
set_state "eth_failback"
exit 0
fi
# 3) No cable -> ETH failback OFF
eth_fb_is_up && /usr/local/sbin/iomatex-eth-fb-down || true
# 4) No cable: if STA ok -> AP off
if sta_ok; then
ap_is_up && /usr/local/sbin/iomatex-ap-down || true
set_state "sta_ok"
exit 0
fi
# 5) No cable and no STA -> AP on
ap_is_up || /usr/local/sbin/iomatex-ap-up
set_state "ap_on_no_uplink"
EOF
chmod 0755 /usr/local/sbin/iomatex-failback-watch
backup_if_exists /etc/systemd/system/iomatex-failback-watch.service
cat > /etc/systemd/system/iomatex-failback-watch.service <<'EOF'
[Unit]
Description=IOMATEX Failback Watch (prod-safe, no-grace)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-failback-watch
EOF
backup_if_exists /etc/systemd/system/iomatex-failback-watch.timer
cat > /etc/systemd/system/iomatex-failback-watch.timer <<'EOF'
[Unit]
Description=IOMATEX Failback Watch timer
[Timer]
OnBootSec=20
OnUnitActiveSec=15
AccuracySec=2
Unit=iomatex-failback-watch.service
[Install]
WantedBy=timers.target
EOF
# ---------- Enable ----------
echo "[8/10] Enable services..."
systemctl daemon-reload
systemctl enable --now iomatex-wifi-ui.service
systemctl enable --now iomatex-failback-watch.timer
# ---------- Initial enforce ----------
echo "[9/10] Initial enforce..."
/usr/local/sbin/iomatex-failback-watch || true
# ---------- Quick self-test ----------
echo "[10/10] Quick self-test (local UI)..."
for i in 1 2 3 4 5; do
ss -lnt 2>/dev/null | awk '{print $4}' | grep -qE "(:${UI_PORT})$" && break
sleep 1
done
curl -m 2 -fsS "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 || true
echo
echo "=== INSTALL DONE ==="
echo "Wi-Fi AP:"
echo " SSID : ${AP_SSID}"
echo " PASS : ${AP_PASS}"
echo " IP : ${AP_IP}"
echo "ETH failback:"
echo " IP : ${ETH_FB_IP}"
echo "UI:"
echo " AP : http://${AP_IP}:${UI_PORT} (also http://${AP_IP} captive HTTP)"
echo " ETH : http://${ETH_FB_IP}:${UI_PORT}"
echo
echo "DIAG:"
echo " /usr/local/sbin/iomatex-failback-status"
echo " /usr/local/sbin/iomatex-ip"
echo " systemctl status iomatex-wifi-ui.service iomatex-failback-watch.timer --no-pager"
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-failback-watch.service --no-pager -n 200"

View File

@ -8,7 +8,7 @@ set -euo pipefail
#
# Working policy intentionally preserved:
# - Uplink OK via eth0 carrier OR wlan0 STA (NM connected + IPv4) => AP OFF
# - Else => AP ON (wlan0 AP), captive HTTP(80) -> UI
# - Else => AP ON (wlan0 AP), captive HTTP(80) -> console when healthy, legacy Wi-Fi UI as fallback
# - UI "Connect" => AP down -> try STA connect -> if fail -> AP back
#
# Defaults:
@ -783,9 +783,7 @@ systemctl start iomatex-wifi-ui.service >/dev/null 2>&1 || true
systemctl start iomatex-dnsmasq.service
systemctl start iomatex-hostapd.service
# Captive: ONLY HTTP -> UI (no HTTPS DNAT)
iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
iptables -t nat -A PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
EOF
write_managed_file /usr/local/sbin/iomatex-ap-down 0755 <<'EOF'
@ -797,6 +795,7 @@ systemctl stop iomatex-hostapd.service 2>/dev/null || true
systemctl stop iomatex-dnsmasq.service 2>/dev/null || true
iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
rm -f /run/iomatex-ap-landing.state 2>/dev/null || true
ip addr flush dev "$IFACE" 2>/dev/null || true
@ -834,6 +833,68 @@ echo "NM_CONNECTION=$nm_con"
echo "STA_CONNECTED=$sta_connected"
echo "IP4=$ip4"
echo "WATCH_STATE=$(cat /run/iomatex-ap.state 2>/dev/null || echo n/a)"
echo "LANDING_TARGET=$(cat /run/iomatex-ap-landing.state 2>/dev/null || echo unknown)"
EOF
write_managed_file /usr/local/sbin/iomatex-ap-refresh-landing 0755 <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
. /etc/iomatex/ap.env
STATE_FILE="/run/iomatex-ap-landing.state"
CONSOLE_CFG="/etc/iomatex/console.json"
CONSOLE_PORT="80"
if [[ -f "$CONSOLE_CFG" ]] && command -v python3 >/dev/null 2>&1; then
detected_port="$(
python3 - "$CONSOLE_CFG" <<'PY' 2>/dev/null || true
import json, sys
path = sys.argv[1]
try:
with open(path, "r", encoding="utf-8") as fh:
data = json.load(fh)
port = data.get("port", 80)
print(int(port))
except Exception:
pass
PY
)"
if [[ "$detected_port" =~ ^[0-9]+$ ]]; then
CONSOLE_PORT="$detected_port"
fi
fi
console_ready=0
if systemctl is-active --quiet iomatex-console.service; then
if command -v curl >/dev/null 2>&1; then
if curl -m 2 -fsS "http://127.0.0.1:${CONSOLE_PORT}/api/status" >/dev/null 2>&1; then
console_ready=1
fi
elif command -v python3 >/dev/null 2>&1; then
if python3 - "$CONSOLE_PORT" >/dev/null 2>&1 <<'PY'
import sys
import urllib.request
port = sys.argv[1]
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/api/status", timeout=2) as response:
raise SystemExit(0 if response.status == 200 else 1)
except Exception:
raise SystemExit(1)
PY
then
console_ready=1
fi
fi
fi
iptables -t nat -D PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
if [[ "$console_ready" -eq 1 ]]; then
echo "console:http://${AP_IP}:${CONSOLE_PORT}/" >"$STATE_FILE"
else
iptables -t nat -A PREROUTING -i "$IFACE" -p tcp --dport 80 -j DNAT --to-destination ${AP_IP}:${UI_PORT} 2>/dev/null || true
echo "legacy:http://${AP_IP}:${UI_PORT}/" >"$STATE_FILE"
fi
EOF
write_managed_file /usr/local/sbin/iomatex-wifi-setup 0755 <<'EOF'
@ -962,6 +1023,7 @@ if eth_ok || sta_ok; then
fi
ap_is_up || /usr/local/sbin/iomatex-ap-up
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
echo "ap_on_no_uplink" > "$STATE"
EOF
if [[ "$LAST_WRITE_CHANGED" -eq 1 ]]; then
@ -1175,6 +1237,7 @@ if [[ "$SYSTEMD_UNITS_CHANGED" -eq 1 ]]; then
fi
/usr/local/sbin/iomatex-ap-sync-config
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
systemctl enable iomatex-wifi-ui.service >/dev/null 2>&1 || true
systemctl enable iomatex-ap-watch.timer >/dev/null 2>&1 || true
@ -1215,6 +1278,7 @@ step "Initial enforce"
step "Quick self-test"
curl -m 2 -fsS "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1 || true
/usr/local/sbin/iomatex-ap-refresh-landing >/dev/null 2>&1 || true
echo
echo "=== INSTALL DONE ==="
@ -1222,11 +1286,13 @@ echo "AP SSID : ${SSID}"
echo "AP MODE : ${PASSWORD_MODE}"
echo "FACTORY AP PASS : ${FACTORY_AP_PASSWORD}"
echo "AP IP : ${AP_IP}"
echo "UI : http://${AP_IP}:${UI_PORT} (also: http://${AP_IP} via captive HTTP)"
echo "PRIMARY UI : http://${AP_IP}/ (console when healthy)"
echo "FALLBACK UI: http://${AP_IP}:${UI_PORT}/ (legacy Wi-Fi rescue UI)"
echo
echo "TEST:"
echo " - No uplink (unplug eth / no STA): connect to WiFi SSID=${SSID}"
echo " - Open: http://10.10.10.1 (NOT https)"
echo " - If console is down, landing should fall back to: http://${AP_IP}:${UI_PORT}/"
echo
echo "DIAG:"
echo " /usr/local/sbin/iomatex-wifi-status"

View File

@ -1,40 +0,0 @@
enabled: false
mqtt:
server: mqtt://uae.iomatex.com:1883
user: broadcaster
password: Y6gDoqbayn36ozn3a
base_topic: zigbee2mqtt/g-box-8514
device_options:
legacy: false
availability:
enabled: true
serial:
port: /dev/serial/by-id/usb-1a86_USB_Serial-if00-port0
adapter: zigate
frontend:
enabled: true
port: 8081
host: 0.0.0.0
advanced:
log_level: info
cache_state: true
cache_state_persistent: true
cache_state_send_on_startup: true
network_key:
- 8
- 94
- 167
- 174
- 199
- 184
- 213
- 106
- 196
- 250
- 112
- 149
- 97
- 173
- 1
- 172
version: 5

142
stage_z2m/stage_z2m.sh Executable file
View File

@ -0,0 +1,142 @@
#!/usr/bin/env bash
set -Eeuo pipefail
# IOMATEX Zigbee2MQTT stage orchestrator.
# Stages:
# 01_base OS/toolchain bootstrap only
# 02_user_dirs user, groups, directories, data perms
# 03_code sync bundled Zigbee2MQTT code only (no git on edge)
# 04_config serial detect + safe configuration.yaml patch/create
# 05_deps pnpm config + pnpm install only
# 06_build isolated tsc + writehash only
# 07_runtime wrapper, systemd units, web proxy, help command
# 08_enable enable/restart services + summary
# Manual usage:
# sudo bash stage_z2m.sh all
# sudo bash stage_z2m.sh 05_deps
# sudo bash stage_z2m.sh 06_build
# sudo bash stage_z2m.sh from 05_deps
# sudo bash stage_z2m.sh to 04_config
# Build problem diagnostics:
# Run 01_base, 03_code, 05_deps, 06_build in sequence.
# Bundle layout for 03_code:
# place Zigbee2MQTT source as ./zigbee2mqtt/ or ./zigbee2mqtt.tar.gz next to this script.
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
usage() {
cat <<'EOF'
Usage:
sudo bash stage_z2m.sh all
sudo bash stage_z2m.sh <stage>
sudo bash stage_z2m.sh from <stage>
sudo bash stage_z2m.sh to <stage>
Stages:
01_base
02_user_dirs
03_code
04_config
05_deps
06_build
07_runtime
08_enable
EOF
}
run_stage() {
local ref="$1"
local normalized script_path stage_key stage_slug stage_log
local start_ts end_ts duration rc
normalized="$(normalize_stage_ref "$ref")" || die "Unknown stage: ${ref}"
script_path="$(stage_script_path_for_ref "$normalized")"
[ -f "$script_path" ] || die "Stage script not found: ${script_path}"
stage_key="${normalized%%_*}"
stage_slug="${normalized#*_}"
stage_log="$(stage_log_path "$stage_key" "$stage_slug")"
start_ts="$(date +%s)"
log "RUN stage=${normalized} script=${script_path} log=${stage_log}"
set +e
bash "$script_path"
rc=$?
set -e
end_ts="$(date +%s)"
duration=$((end_ts - start_ts))
log "END stage=${normalized} rc=${rc} duration=${duration}s"
[ "$rc" -eq 0 ] || die "Stage failed: ${normalized}"
}
run_all() {
local stage
for stage in "${STAGE_SEQUENCE[@]}"; do
run_stage "$stage"
done
}
run_from() {
local ref="$1"
local normalized seen=0 stage
normalized="$(normalize_stage_ref "$ref")" || die "Unknown stage: ${ref}"
for stage in "${STAGE_SEQUENCE[@]}"; do
if [ "$stage" = "$normalized" ]; then
seen=1
fi
if [ "$seen" -eq 1 ]; then
run_stage "$stage"
fi
done
}
run_to() {
local ref="$1"
local normalized stage
normalized="$(normalize_stage_ref "$ref")" || die "Unknown stage: ${ref}"
for stage in "${STAGE_SEQUENCE[@]}"; do
run_stage "$stage"
if [ "$stage" = "$normalized" ]; then
break
fi
done
}
main() {
case "${1:-all}" in
help|-h|--help)
usage
;;
all)
[ "$#" -le 1 ] || die "Usage: stage_z2m.sh all"
require_root
orchestrator_init
run_all
;;
from)
[ "$#" -eq 2 ] || die "Usage: stage_z2m.sh from <stage>"
require_root
orchestrator_init
run_from "$2"
;;
to)
[ "$#" -eq 2 ] || die "Usage: stage_z2m.sh to <stage>"
require_root
orchestrator_init
run_to "$2"
;;
*)
[ "$#" -eq 1 ] || die "Usage: stage_z2m.sh <stage>"
require_root
orchestrator_init
run_stage "$1"
;;
esac
}
main "$@"

27
stage_z2m/stage_z2m_01_base.sh Executable file
View File

@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "01" "base"
require_cmd apt-get awk cmp hostname id install mktemp mv sed systemctl tar tee
step "Preflight"
install_base_packages
require_cmd curl gpg jq python3 sudo
step "Install Node.js ${NODE_MAJOR}.x if needed"
install_node_if_needed
require_cmd node npm corepack
node -v
npm -v
step "Enable pnpm via corepack"
ensure_pnpm_available
}
main "$@"

View File

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "02" "user_dirs"
step "Ensure system user"
ensure_z2m_user
step "Ensure directories"
ensure_directories
}
main "$@"

170
stage_z2m/stage_z2m_03_code.sh Executable file
View File

@ -0,0 +1,170 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
Z2M_REF="${Z2M_REF:-master}"
Z2M_REPO_OWNER="Koenkk"
Z2M_REPO_NAME="zigbee2mqtt"
TMPDIR_STAGE=""
ARCHIVE_PATH=""
EXTRACT_DIR=""
SOURCE_ROOT=""
DEPLOY_ROOT=""
PRESERVED_DATA_DIR=""
PRESERVED_PREVIOUS_DIR=""
DEPLOY_COMMITTED=0
cleanup() {
local rc=$?
if [ "$DEPLOY_COMMITTED" -ne 1 ] && [ -n "${PRESERVED_PREVIOUS_DIR:-}" ] && [ -d "$PRESERVED_PREVIOUS_DIR" ] && [ ! -d "$Z2M_DIR" ]; then
mv "$PRESERVED_PREVIOUS_DIR" "$Z2M_DIR" 2>/dev/null || true
fi
if [ "$DEPLOY_COMMITTED" -ne 1 ] && [ -n "${PRESERVED_DATA_DIR:-}" ] && [ -d "$PRESERVED_DATA_DIR" ] && [ -d "$Z2M_DIR" ] && [ ! -d "$Z2M_DATA_DIR" ]; then
mkdir -p "$Z2M_DIR" 2>/dev/null || true
mv "$PRESERVED_DATA_DIR" "$Z2M_DATA_DIR" 2>/dev/null || true
fi
if [ -n "${TMPDIR_STAGE:-}" ] && [ -d "$TMPDIR_STAGE" ]; then
rm -rf "$TMPDIR_STAGE"
fi
exit "$rc"
}
archive_urls_for_ref() {
local ref="$1"
cat <<EOF
https://codeload.github.com/${Z2M_REPO_OWNER}/${Z2M_REPO_NAME}/tar.gz/refs/heads/${ref}
https://github.com/${Z2M_REPO_OWNER}/${Z2M_REPO_NAME}/archive/refs/heads/${ref}.tar.gz
https://codeload.github.com/${Z2M_REPO_OWNER}/${Z2M_REPO_NAME}/tar.gz/refs/tags/${ref}
https://github.com/${Z2M_REPO_OWNER}/${Z2M_REPO_NAME}/archive/refs/tags/${ref}.tar.gz
https://github.com/${Z2M_REPO_OWNER}/${Z2M_REPO_NAME}/archive/${ref}.tar.gz
EOF
}
download_archive_with_retry() {
local url attempt rc
while IFS= read -r url; do
[ -n "$url" ] || continue
for attempt in 1 2 3; do
log "Download attempt ${attempt}/3: ${url}"
set +e
curl -fL --connect-timeout 20 --retry 0 -o "$ARCHIVE_PATH" "$url"
rc=$?
set -e
if [ "$rc" -eq 0 ]; then
log "Download OK: ${url}"
return 0
fi
warn "Download failed rc=${rc}: ${url}"
sleep "$attempt"
done
done < <(archive_urls_for_ref "$Z2M_REF")
die "Failed to download Zigbee2MQTT archive for ref='${Z2M_REF}' from GitHub"
}
resolve_source_root() {
local candidate
if [ -f "${EXTRACT_DIR}/package.json" ]; then
SOURCE_ROOT="$EXTRACT_DIR"
return 0
fi
for candidate in "${EXTRACT_DIR}"/*; do
[ -d "$candidate" ] || continue
if [ -f "${candidate}/package.json" ]; then
SOURCE_ROOT="$candidate"
return 0
fi
done
die "Archive extracted but package.json was not found"
}
prepare_deploy_tree() {
DEPLOY_ROOT="${TMPDIR_STAGE}/deploy-root"
mkdir -p "$DEPLOY_ROOT"
tar -C "$SOURCE_ROOT" \
--exclude=.git \
--exclude=./.git \
--exclude=data \
--exclude=./data \
--exclude=node_modules \
--exclude=./node_modules \
-cf - . | tar -C "$DEPLOY_ROOT" -xf -
[ -f "${DEPLOY_ROOT}/package.json" ] || die "Prepared deploy tree is invalid: package.json missing"
}
commit_deploy() {
local previous_dir=""
mkdir -p "$(dirname "$Z2M_DIR")"
if [ -d "$Z2M_DATA_DIR" ]; then
PRESERVED_DATA_DIR="${TMPDIR_STAGE}/preserved-data"
mv "$Z2M_DATA_DIR" "$PRESERVED_DATA_DIR"
fi
if [ -d "$Z2M_DIR" ]; then
previous_dir="${TMPDIR_STAGE}/previous-z2m"
mv "$Z2M_DIR" "$previous_dir"
PRESERVED_PREVIOUS_DIR="$previous_dir"
fi
mv "$DEPLOY_ROOT" "$Z2M_DIR"
mkdir -p "$Z2M_DATA_DIR" "$Z2M_DIR/logs"
if [ -n "${PRESERVED_DATA_DIR:-}" ] && [ -d "$PRESERVED_DATA_DIR" ]; then
rm -rf "$Z2M_DATA_DIR"
mv "$PRESERVED_DATA_DIR" "$Z2M_DATA_DIR"
PRESERVED_DATA_DIR=""
fi
chown -R "$Z2M_USER:$Z2M_GROUP" "$Z2M_DIR"
DEPLOY_COMMITTED=1
}
main() {
require_root
stage_init "03" "code"
trap cleanup EXIT
require_cmd awk cmp curl hostname id install mktemp mv sed sudo tar tee
step "Prepare code sync workspace"
TMPDIR_STAGE="$(mktemp -d /tmp/iomatex-z2m-code.XXXXXX)"
ARCHIVE_PATH="${TMPDIR_STAGE}/zigbee2mqtt-${Z2M_REF}.tar.gz"
EXTRACT_DIR="${TMPDIR_STAGE}/extract"
mkdir -p "$EXTRACT_DIR"
log "Using Zigbee2MQTT ref: ${Z2M_REF}"
log "Temporary workspace: ${TMPDIR_STAGE}"
step "Download Zigbee2MQTT archive"
download_archive_with_retry
step "Extract and validate archive"
tar -xzf "$ARCHIVE_PATH" -C "$EXTRACT_DIR"
resolve_source_root
log "Resolved source root: ${SOURCE_ROOT}"
[ -f "${SOURCE_ROOT}/package.json" ] || die "package.json missing in ${SOURCE_ROOT}"
step "Prepare deploy tree"
prepare_deploy_tree
step "Deploy code into ${Z2M_DIR} (preserve data/)"
commit_deploy
log "Code deploy complete: ${Z2M_DIR}"
}
main "$@"

View File

@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
local detected_serial=""
require_root
stage_init "04" "config"
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"
}
main "$@"

20
stage_z2m/stage_z2m_05_deps.sh Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "05" "deps"
require_cmd sudo node npm pnpm
step "Dependency install preflight"
log "Detailed dependency log: ${PNPM_INSTALL_LOG}"
step "Install dependencies only"
install_dependencies
}
main "$@"

20
stage_z2m/stage_z2m_06_build.sh Executable file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "06" "build"
require_cmd sudo node npm pnpm
step "Build preflight"
log "Detailed build logs: ${TSC_LOG} and ${WRITEHASH_LOG}"
step "Run isolated build"
build_z2m
}
main "$@"

View File

@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "07" "runtime"
step "Install wrapper"
install_wrapper
step "Install systemd units"
install_systemd_units
step "Install web fallback/proxy on port ${WEB_PORT_PUBLIC}"
install_web_status_proxy
step "Install help command"
install_help_command
}
main "$@"

View File

@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./stage_z2m_lib.sh
source "${SCRIPT_DIR}/stage_z2m_lib.sh"
main() {
require_root
stage_init "08" "enable"
step "Enable and restart services"
enable_and_restart_services
step "Print summary"
print_summary
}
main "$@"

924
stage_z2m/stage_z2m_install Normal file → Executable file
View File

@ -1,926 +1,10 @@
#!/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
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
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
if [ "$#" -eq 0 ]; then
set -- all
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 "$@"
exec bash "${SCRIPT_DIR}/stage_z2m.sh" "$@"

1356
stage_z2m/stage_z2m_lib.sh Executable file

File diff suppressed because it is too large Load Diff