WIP: preserve IOMATEX OS state before consolidation

This commit is contained in:
Andrei Smaliak 2026-09-03 15:59:04 +02:00
parent e47dc20224
commit 4c9a2ec30c
25 changed files with 3053 additions and 309 deletions

View File

@ -310,9 +310,11 @@ install_iomatex_z2m.sh
## 11. Как запустить отдельную стадию вручную
Вручную можно запускать почти любую стадию, кроме `stage_env`.
Вручную можно запускать любую стадию. Повторный запуск `stage_env` автоматически
переходит в безопасный режим: сохраняет системные APT-репозитории, timezone,
NTP, swap и bootloader, обновляя только управляемые IOMATEX-настройки.
Почему `stage_env` нельзя считать обычной стадией:
Особенности первого запуска `stage_env`:
- она меняет базовое окружение;
- она меняет пользователей;
- после нее обязателен reboot;

View File

@ -196,7 +196,10 @@ avahi-resolve-host-name -4 023d.local
Короткое правило:
- безопаснее всего переустанавливать поверх: `stage_wifi`, `stage_mqtt`, `stage_z2m`, `stage_ui`, `stage_avahi`, `stage_itscreen`, `stage_dashboard_bridge`, `stage_dashboards`;
- `stage_cockpit` опциональный и может падать на нестабильном vendor kernel; его failure не должен ломать основной install;
- нежелательно без необходимости накатывать поверх: `stage_env`;
- `stage_env` можно накатывать поверх: он автоматически включает безопасный
повторный режим, сохраняет APT-репозитории, timezone, NTP, swap и bootloader,
не запускает автоматический `apt -f install`; полное обновление базовой
политики выполняется только при первичной установке;
- обязательно оставлять последней: `stage_reverse_tunnels`.
Рекомендуемый порядок для обычного Edge:

View File

@ -0,0 +1,59 @@
# IOMATEX storage health contract v1
`stage_env` installs the read-only command:
```bash
sudo /usr/local/sbin/iomatex-storage-health --json
```
The command always returns one JSON object. `schema_version` is `1`. Console
consumes this command and exposes the object unchanged as `storage` in
`GET /api/health/summary`.
The contract intentionally separates physical eMMC health from ext4 health:
- `emmc.health_score` is a 0–10 assessment based on the worst JEDEC lifetime
register, capped when `pre_eol_info` reports warning or urgent state;
- `emmc.wear_percent_min` and `wear_percent_max` are the coarse JEDEC wear
range. They are not exact write-cycle counters;
- exact power-on hours and exact eMMC write cycles are not available on the
target hardware and must not be inferred;
- `filesystem.lifetime_writes` is the ext4 lifetime-write counter for
`/userdata`, not the physical eMMC write total;
- `filesystem.status` reports filesystem errors and journal state separately
from the physical eMMC score.
Consumers must treat unknown or missing fields as unavailable. They must not
replace missing measurements with a healthy value. Additive fields may be
introduced within schema v1; incompatible semantic changes require a new
`schema_version`.
Example shape:
```json
{
"schema_version": 1,
"available": true,
"status": "ok",
"warnings": [],
"emmc": {
"available": true,
"device": "/dev/mmcblk0",
"health_score": 10,
"health_score_max": 10,
"health_label": "excellent",
"wear_percent_min": 0,
"wear_percent_max": 10,
"pre_eol_status": "normal"
},
"filesystem": {
"mount_point": "/userdata",
"source": "/dev/mmcblk0p8",
"journal_enabled": true,
"state": "clean",
"error_count": 0,
"lifetime_writes": "14 GB",
"status": "ok"
}
}
```

View File

@ -0,0 +1,53 @@
#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
MARKER="/var/lib/iomatex/storage/enable-userdata-journal"
DEVICE_LINK="/dev/disk/by-partlabel/userdata"
log() { echo "[iomatex-userdata-prepare] $*"; }
[ -e "$MARKER" ] || exit 0
for _ in $(seq 1 30); do
[ -b "$DEVICE_LINK" ] && break
sleep 1
done
[ -b "$DEVICE_LINK" ] || { log "ERROR: userdata block device did not appear"; exit 1; }
device="$(readlink -f "$DEVICE_LINK")"
[ -b "$device" ] || { log "ERROR: resolved userdata path is not a block device"; exit 1; }
if findmnt -rn -S "$device" >/dev/null 2>&1 || mountpoint -q /userdata; then
log "ERROR: refusing to change a mounted filesystem: $device"
exit 1
fi
fs_type="$(blkid -s TYPE -o value "$device" 2>/dev/null || true)"
[ "$fs_type" = "ext4" ] || { log "ERROR: expected ext4 on $device, found ${fs_type:-unknown}"; exit 1; }
if tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' | grep -qw has_journal; then
log "Journal already enabled"
else
set +e
e2fsck -pf "$device"
fsck_rc=$?
set -e
case "$fsck_rc" in
0|1) ;;
*) log "ERROR: preflight e2fsck failed with rc=$fsck_rc; filesystem was not modified"; exit "$fsck_rc" ;;
esac
tune2fs -j "$device"
sync
tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' | grep -qw has_journal \
|| { log "ERROR: journal verification failed"; exit 1; }
log "Ext4 journal enabled successfully"
fi
tmp="$(mktemp)"
awk '
$1 !~ /^#/ && $2 == "/userdata" { $6="2" }
{ print }
' /etc/fstab >"$tmp"
install -m 0644 -o root -g root "$tmp" /etc/fstab
rm -f "$tmp" "$MARKER"
log "Migration complete; automatic filesystem checks enabled for future boots"

View File

@ -0,0 +1,242 @@
#!/usr/bin/env python3
"""Read-only IOMATEX storage health contract.
The eMMC lifetime registers are coarse JEDEC estimates, not an exact write
counter. Filesystem statistics are reported separately so callers do not
mistake an ext4 fault for physical eMMC wear.
"""
import argparse
import json
import os
import re
import subprocess
from pathlib import Path
SCHEMA_VERSION = 1
USERDATA_MOUNT = "/userdata"
def read_text(path):
try:
return Path(path).read_text(encoding="utf-8", errors="replace").strip()
except OSError:
return ""
def run(command, timeout=5):
try:
command_env = os.environ.copy()
command_env["LC_ALL"] = "C"
completed = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout,
check=False,
env=command_env,
)
return completed.returncode, completed.stdout, completed.stderr
except (OSError, subprocess.TimeoutExpired) as error:
return 127, "", str(error)
def find_userdata_source():
rc, stdout, _ = run(["findmnt", "-n", "-o", "SOURCE", USERDATA_MOUNT])
if rc == 0 and stdout.strip():
return os.path.realpath(stdout.strip())
candidate = Path("/dev/disk/by-partlabel/userdata")
return os.path.realpath(candidate) if candidate.exists() else ""
def parent_mmc_device(source):
name = os.path.basename(source)
match = re.match(r"^(mmcblk\d+)(?:p\d+)?$", name)
if not match:
return ""
return match.group(1)
def parse_hex_byte(value):
try:
return int(str(value).strip(), 16)
except (TypeError, ValueError):
return None
def lifetime_range(raw):
value = parse_hex_byte(raw)
if value is None or value == 0:
return None, None
if 1 <= value <= 10:
return (value - 1) * 10, value * 10
if value == 11:
return 100, None
return None, None
def health_score(life_values, pre_eol):
known = [value for value in life_values if value is not None and value > 0]
if not known:
return None
worst = max(known)
score = max(0, 11 - worst) if worst <= 11 else 0
if pre_eol == 2:
score = min(score, 4)
elif pre_eol == 3:
score = min(score, 1)
return score
def score_label(score):
if score is None:
return "unknown"
if score >= 9:
return "excellent"
if score >= 7:
return "good"
if score >= 4:
return "attention"
return "critical"
def parse_tune2fs(source):
result = {}
if not source:
return result
rc, stdout, _ = run(["tune2fs", "-l", source], timeout=8)
if rc != 0:
return result
for line in stdout.splitlines():
if ":" not in line:
continue
key, value = line.split(":", 1)
result[key.strip()] = value.strip()
return result
def integer(value):
match = re.search(r"\d+", str(value or ""))
return int(match.group(0)) if match else None
def main_contract():
source = find_userdata_source()
mmc_name = parent_mmc_device(source)
mmc_root = Path("/sys/class/block") / mmc_name / "device" if mmc_name else None
life_tokens = read_text(mmc_root / "life_time").split() if mmc_root else []
life_a_raw = life_tokens[0] if life_tokens else ""
life_b_raw = life_tokens[1] if len(life_tokens) > 1 else ""
life_a = parse_hex_byte(life_a_raw)
life_b = parse_hex_byte(life_b_raw)
pre_eol_raw = read_text(mmc_root / "pre_eol_info") if mmc_root else ""
pre_eol = parse_hex_byte(pre_eol_raw)
wear_ranges = [lifetime_range(life_a_raw), lifetime_range(life_b_raw)]
known_min = [item[0] for item in wear_ranges if item[0] is not None]
known_max = [item[1] for item in wear_ranges if item[1] is not None]
score = health_score([life_a, life_b], pre_eol)
fs = parse_tune2fs(source)
features = fs.get("Filesystem features", "").split()
fs_state = fs.get("Filesystem state", "")
error_count = integer(fs.get("FS Error count"))
mounted = bool(source and os.path.ismount(USERDATA_MOUNT))
mount_options = ""
rc, stdout, _ = run(["findmnt", "-n", "-o", "OPTIONS", USERDATA_MOUNT])
if rc == 0:
mount_options = stdout.strip()
journal_enabled = "has_journal" in features if features else None
fs_has_errors = "error" in fs_state.lower() or bool(error_count)
if not source:
fs_status = "unavailable"
elif fs_has_errors:
fs_status = "critical"
elif journal_enabled is False:
fs_status = "attention"
else:
fs_status = "ok"
pre_eol_status = {1: "normal", 2: "warning", 3: "urgent"}.get(pre_eol, "unknown")
warnings = []
if journal_enabled is False:
warnings.append("userdata_journal_disabled")
if fs_has_errors:
warnings.append("userdata_filesystem_errors")
if pre_eol in (2, 3):
warnings.append("emmc_pre_eol_%s" % pre_eol_status)
available = bool(mmc_root and mmc_root.exists())
overall = "unavailable" if not available else ("critical" if fs_status == "critical" else "attention" if warnings else "ok")
return {
"schema_version": SCHEMA_VERSION,
"available": available,
"status": overall,
"warnings": warnings,
"emmc": {
"available": available,
"device": "/dev/%s" % mmc_name if mmc_name else "",
"model": read_text(mmc_root / "name") if mmc_root else "",
"serial": read_text(mmc_root / "serial") if mmc_root else "",
"manufactured_at": read_text(mmc_root / "date") if mmc_root else "",
"life_time_a_raw": life_a_raw,
"life_time_b_raw": life_b_raw,
"wear_percent_min": max(known_min) if known_min else None,
"wear_percent_max": max(known_max) if known_max else None,
"pre_eol_raw": pre_eol_raw,
"pre_eol_status": pre_eol_status,
"health_score": score,
"health_score_max": 10,
"health_label": score_label(score),
"estimate_note": "JEDEC lifetime estimate; exact power-on hours and write cycles are not exposed by this eMMC",
},
"filesystem": {
"mount_point": USERDATA_MOUNT,
"source": source,
"mounted": mounted,
"read_only": "ro" in mount_options.split(","),
"type": "ext4" if source else "",
"journal_enabled": journal_enabled,
"state": fs_state,
"errors_behavior": fs.get("Errors behavior", ""),
"error_count": error_count,
"first_error_at": fs.get("First error time", ""),
"last_error_at": fs.get("Last error time", ""),
"last_checked_at": fs.get("Last checked", ""),
"lifetime_writes": fs.get("Lifetime writes", ""),
"status": fs_status,
},
}
def main():
parser = argparse.ArgumentParser(description="Read IOMATEX eMMC and /userdata health")
parser.add_argument("--json", action="store_true", help="emit the stable JSON contract")
args = parser.parse_args()
contract = main_contract()
if args.json:
print(json.dumps(contract, ensure_ascii=False, separators=(",", ":")))
return
emmc = contract["emmc"]
filesystem = contract["filesystem"]
score = emmc["health_score"]
print("eMMC health: %s" % ("unknown" if score is None else "%s/10" % score))
wear_min = emmc["wear_percent_min"]
wear_max = emmc["wear_percent_max"]
if wear_min is None:
wear_text = "unknown"
elif wear_max is None:
wear_text = "%s%%+" % wear_min
else:
wear_text = "%s-%s%%" % (wear_min, wear_max)
print("Estimated wear: %s" % wear_text)
print("/userdata: %s; journal=%s; lifetime writes=%s" % (
filesystem["state"] or "unknown",
filesystem["journal_enabled"],
filesystem["lifetime_writes"] or "unknown",
))
if __name__ == "__main__":
main()

View File

@ -3,11 +3,16 @@ set -euo pipefail
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export DEBIAN_FRONTEND=noninteractive
export LC_ALL=C
LOG="/var/log/iomatex-stage0_1.log"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
STAGE_ENV_STATE_DIR="/var/lib/iomatex/stage-env"
STAGE_ENV_STATE_FILE="${STAGE_ENV_STATE_DIR}/installed"
mkdir -p /var/log >/dev/null 2>&1 || true
APT_UPDATED=0
WRITE_CHANGED=0
STAGE_ENV_REINSTALL=0
DEVICE_ID_FILE="/userdata/device-id"
DEVICE_ID_RE='^g-box-[a-f0-9]{8}$'
@ -149,6 +154,28 @@ apt_repair_state() {
return "$rc"
}
apt_prepare_state() {
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
apt_repair_state
return $?
fi
log "APT/DPKG read-only preflight for an existing Edge"
if [ -n "$(dpkg --audit 2>/dev/null || true)" ]; then
log "ERROR: dpkg reports pending work; repeat install will not repair it automatically"
return 1
fi
run_long "APT check (existing Edge; no automatic repair)" 900 /usr/bin/apt-get check
}
apt_verify_after_install() {
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
apt_repair_state
else
run_long "APT check after package install" 900 /usr/bin/apt-get check
fi
}
apt_install_missing() {
local pkgs=("$@")
local missing=()
@ -169,7 +196,7 @@ apt_install_missing() {
log "Missing packages: ${missing[*]}"
if ! apt_repair_state; then
if ! apt_prepare_state; then
log "APT/DPKG repair preflight failed; refusing to install packages on an unsafe dpkg state"
echo "[!] APT/DPKG repair preflight failed; refusing to continue package install (see $LOG)"
return 1
@ -191,7 +218,7 @@ apt_install_missing() {
install "$pkg"; then
installed_any=1
sync || true
if ! apt_repair_state; then
if ! apt_verify_after_install; then
log "APT/DPKG repair failed after installing package: $pkg"
echo "[!] APT/DPKG repair failed after installing package: $pkg (see $LOG)"
return 1
@ -200,7 +227,7 @@ apt_install_missing() {
fi
failed+=("$pkg")
if ! apt_repair_state; then
if ! apt_verify_after_install; then
log "APT/DPKG repair failed after package failure: $pkg"
echo "[!] APT/DPKG repair failed after package failure: $pkg (see $LOG)"
return 1
@ -291,8 +318,22 @@ disable_userdata_swap() {
fi
}
ensure_userdata_fstab_nonblocking() {
userdata_has_journal() {
local device
device="$(readlink -f /dev/disk/by-partlabel/userdata 2>/dev/null || true)"
[ -b "$device" ] || return 1
tune2fs -l "$device" 2>/dev/null \
| awk -F: '/^Filesystem features:/{print $2}' \
| grep -qw has_journal
}
ensure_userdata_fstab_policy() {
local tmp
local fsck_pass="0"
if userdata_has_journal; then
fsck_pass="2"
fi
[ -f /etc/fstab ] || return 0
if ! awk '$1 !~ /^#/ && $2 == "/userdata" { found=1 } END { exit found ? 0 : 1 }' /etc/fstab; then
@ -309,9 +350,11 @@ ensure_userdata_fstab_nonblocking() {
split($4, opts, ",")
has_nofail=0
has_timeout=0
has_errors_policy=0
for (i in opts) {
if (opts[i] == "nofail") has_nofail=1
if (opts[i] ~ /^x-systemd.device-timeout=/) has_timeout=1
if (opts[i] ~ /^errors=/) has_errors_policy=1
}
if (!has_nofail) {
$4 = ($4 == "defaults" ? "defaults,nofail" : $4 ",nofail")
@ -321,14 +364,21 @@ ensure_userdata_fstab_nonblocking() {
$4 = $4 ",x-systemd.device-timeout=5s"
changed=1
}
if ($6 != "0") {
$6 = "0"
if (!has_errors_policy) {
$4 = $4 ",errors=remount-ro"
changed=1
} else if ($4 !~ /(^|,)errors=remount-ro(,|$)/) {
gsub(/errors=[^,]*/, "errors=remount-ro", $4)
changed=1
}
if ($6 != fsck_pass) {
$6 = fsck_pass
changed=1
}
print
}
END { if (changed) exit 2 }
' /etc/fstab >"$tmp"
' fsck_pass="$fsck_pass" /etc/fstab >"$tmp"
local awk_rc=$?
set -e
case "$awk_rc" in
@ -338,7 +388,7 @@ ensure_userdata_fstab_nonblocking() {
2)
install -m 0644 -o root -g root "$tmp" /etc/fstab
rm -f "$tmp"
log "Updated /etc/fstab: /userdata is non-blocking for cold boot"
log "Updated /etc/fstab: /userdata is non-blocking, errors remount read-only, fsck pass=${fsck_pass}"
;;
*)
rm -f "$tmp"
@ -348,6 +398,74 @@ ensure_userdata_fstab_nonblocking() {
esac
}
configure_userdata_storage_contract() {
local device features state error_count
local marker="/var/lib/iomatex/storage/enable-userdata-journal"
install -D -m 0755 -o root -g root \
"$SCRIPT_DIR/iomatex_storage_health.py" /usr/local/sbin/iomatex-storage-health
install -D -m 0755 -o root -g root \
"$SCRIPT_DIR/iomatex-userdata-prepare" /usr/local/sbin/iomatex-userdata-prepare
write_if_changed /etc/systemd/system/iomatex-userdata-prepare.service 0644 <<'EOF'
[Unit]
Description=Prepare IOMATEX userdata filesystem before first journaled mount
DefaultDependencies=no
After=systemd-udev-settle.service
Before=userdata.mount local-fs-pre.target
ConditionPathExists=/var/lib/iomatex/storage/enable-userdata-journal
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/iomatex-userdata-prepare
TimeoutStartSec=15min
[Install]
WantedBy=local-fs-pre.target
EOF
mkdir -p /etc/systemd/system/userdata.mount.d
write_if_changed /etc/systemd/system/userdata.mount.d/10-iomatex-prepare.conf 0644 <<'EOF'
[Unit]
Requires=iomatex-userdata-prepare.service
After=iomatex-userdata-prepare.service
EOF
mkdir -p /etc/systemd/system/itscreen-x11.service.d
write_if_changed /etc/systemd/system/itscreen-x11.service.d/10-userdata-ordering.conf 0644 <<'EOF'
[Unit]
RequiresMountsFor=/userdata
After=userdata.mount
EOF
mkdir -p "$(dirname "$marker")"
device="$(readlink -f /dev/disk/by-partlabel/userdata 2>/dev/null || true)"
if [ ! -b "$device" ]; then
rm -f "$marker"
log "WARN: userdata block device not found; journal migration was not armed"
return 0
fi
features="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' || true)"
if printf '%s\n' "$features" | grep -qw has_journal; then
rm -f "$marker"
log "Userdata ext4 journal already enabled"
return 0
fi
state="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem state:/{sub(/^[[:space:]]+/, "", $2); print $2}' || true)"
error_count="$(tune2fs -l "$device" 2>/dev/null | awk -F: '/^FS Error count:/{gsub(/[[:space:]]/, "", $2); print $2}' || true)"
if [ "$state" = "clean" ] && [ "${error_count:-0}" = "0" ]; then
: >"$marker"
chmod 0600 "$marker"
log "Clean unjournaled /userdata detected; safe offline journal migration armed for next boot"
else
rm -f "$marker"
log "ERROR: /userdata is unjournaled and not clean (state=${state:-unknown}, errors=${error_count:-unknown}); automatic mutation refused"
echo "[!] /userdata requires an offline backup and e2fsck; automatic journal migration was NOT armed"
fi
}
append_kernel_args_to_file() {
local path="$1"
local tmp
@ -710,6 +828,11 @@ if [ "${EUID:-$(id -u)}" -ne 0 ]; then
exit 1
fi
if [ -f "$STAGE_ENV_STATE_FILE" ] \
|| { [ -f /etc/profile.d/99-iomatex-path.sh ] && id iomatex >/dev/null 2>&1; }; then
STAGE_ENV_REINSTALL=1
fi
# --- CRLF guard ---
if grep -q $'\r' "$0"; then
echo "[!] ERROR: Script has Windows CRLF line endings."
@ -728,6 +851,11 @@ trap flush_filesystems EXIT
log "=== IOMATEX EDGE :: STAGE_ENV START (Debian 11) ==="
log "LOG: $LOG"
if [ "$STAGE_ENV_REINSTALL" -eq 1 ]; then
log "MODE: safe repeat install; preserve APT sources and refuse automatic dpkg repair"
else
log "MODE: first installation"
fi
# -------------------------
# Step 1: PATH fix
@ -740,8 +868,7 @@ EOF
# -------------------------
# Step 2: APT sources normalize (official Debian 11 stable only)
# -------------------------
step "APT sources normalize (official Debian 11 bullseye + non-free; remove vendor lists)"
backup_if_exists /etc/apt/sources.list
step "APT sources policy"
backup_if_exists /etc/apt/apt.conf.d/99no-translations
write_if_changed /etc/apt/apt.conf.d/99no-translations 0644 <<'EOF'
@ -749,31 +876,43 @@ Acquire::Languages "none";
EOF
log "APT translations policy ensured: Acquire::Languages none"
write_if_changed /etc/apt/sources.list 0644 <<'EOF'
if [ "$STAGE_ENV_REINSTALL" -eq 0 ] || [ "${IOMATEX_STAGE_ENV_REFRESH_APT_SOURCES:-0}" = "1" ]; then
backup_if_exists /etc/apt/sources.list
write_if_changed /etc/apt/sources.list 0644 <<'EOF'
deb http://deb.debian.org/debian bullseye main contrib non-free
deb http://deb.debian.org/debian bullseye-updates main contrib non-free
deb http://deb.debian.org/debian-security bullseye-security main contrib non-free
EOF
rm -f /etc/apt/sources.list.d/*.list 2>/dev/null || true
rm -f /etc/apt/sources.list.d/*.sources 2>/dev/null || true
log "APT sources normalized to official Debian 11 policy"
log "APT policy: deb-src disabled by omission"
log "APT policy: bullseye-backports disabled by omission"
log "APT policy: vendor list and deb822 sources removed"
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
rm -f /etc/apt/sources.list.d/*.list 2>/dev/null || true
rm -f /etc/apt/sources.list.d/*.sources 2>/dev/null || true
fi
log "APT sources normalized to official Debian 11 policy"
else
log "Existing Edge detected: preserving /etc/apt/sources.list and all additional repositories"
fi
# -------------------------
# Step 3: APT repair + update
# -------------------------
step "APT/DPKG repair preflight"
if ! apt_repair_state; then
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
if ! apt_repair_state; then
log "ERROR: APT/DPKG repair preflight failed before update; stop to avoid unsafe package state"
echo "[!] ERROR: APT/DPKG repair preflight failed before update. Stop and inspect $LOG"
exit 1
fi
else
log "Existing Edge detected: skipped mutating dpkg --configure and apt -f repair"
fi
step "APT update"
apt_update_if_needed
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
apt_update_if_needed
else
log "Existing Edge detected: skipped unconditional apt update"
fi
# -------------------------
# Step 4: Base tools (nano mandatory early)
@ -805,28 +944,36 @@ install_mbpoll
# Step 5: Timezone Asia/Dubai
# -------------------------
step "Timezone Asia/Dubai"
ln -sf /usr/share/zoneinfo/Asia/Dubai /etc/localtime
soft_run "dpkg-reconfigure tzdata" 120 /usr/sbin/dpkg-reconfigure -f noninteractive tzdata
if [ "$STAGE_ENV_REINSTALL" -eq 0 ] || [ "${IOMATEX_STAGE_ENV_REFRESH_BASELINE:-0}" = "1" ]; then
ln -sf /usr/share/zoneinfo/Asia/Dubai /etc/localtime
soft_run "dpkg-reconfigure tzdata" 120 /usr/sbin/dpkg-reconfigure -f noninteractive tzdata
else
log "Existing Edge detected: preserving configured timezone"
fi
# -------------------------
# Step 6: NTP (use systemd-timesyncd, remove ntp/ntpd)
# -------------------------
step "Time sync: install+enable systemd-timesyncd; remove ntp/ntpd if present"
if apt_install_missing systemd-timesyncd; then
log "systemd-timesyncd package ensured"
if [ "$STAGE_ENV_REINSTALL" -eq 1 ] && [ "${IOMATEX_STAGE_ENV_REFRESH_BASELINE:-0}" != "1" ]; then
log "Existing Edge detected: preserving the configured NTP implementation"
else
if apt_install_missing systemd-timesyncd; then
log "systemd-timesyncd package ensured"
else
log "WARN: systemd-timesyncd install failed; continuing without blocking stage_env"
echo "[!] WARN: systemd-timesyncd install failed; continuing without it (see $LOG)"
fi
systemctl_disable_now_safe ntp
systemctl_disable_now_safe ntpd
systemctl_mask_safe ntp.service
apt_remove_if_installed ntp
if package_installed systemd-timesyncd; then
fi
systemctl_disable_now_safe ntp
systemctl_disable_now_safe ntpd
systemctl_mask_safe ntp.service
apt_remove_if_installed ntp
if package_installed systemd-timesyncd; then
systemctl_enable_now_safe systemd-timesyncd
soft_run "timedatectl set-ntp true" 10 /bin/bash -lc 'timedatectl set-ntp true 2>/dev/null || true'
else
else
log "WARN: systemd-timesyncd is not installed; skipped timedatectl NTP enable"
fi
fi
# -------------------------
@ -1075,9 +1222,21 @@ EOF
step "Userdata SAFE: non-blocking mount + generic logs + log overflow protection"
mkdir -p /etc/systemd/system /usr/local/sbin
configure_cold_boot_fsck_repair
ensure_userdata_fstab_nonblocking
disable_userdata_swap
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
configure_cold_boot_fsck_repair
else
log "Existing Edge detected: preserving bootloader configuration"
fi
configure_userdata_storage_contract
ensure_userdata_fstab_policy
if [ "$STAGE_ENV_REINSTALL" -eq 0 ]; then
disable_userdata_swap
else
log "Existing Edge detected: leaving swap configuration untouched"
fi
soft_run "systemd daemon-reload (storage contract)" 20 /bin/systemctl daemon-reload
soft_run "Enable iomatex-userdata-prepare.service" 20 /bin/systemctl enable iomatex-userdata-prepare.service
write_if_changed /usr/local/sbin/iomatex-userdata-bootstrap 0755 <<'EOF'
#!/usr/bin/env bash
@ -1199,7 +1358,14 @@ if [ "$WRITE_CHANGED" -eq 1 ]; then
fi
MOSQ_ROTATE_CHANGED=0
write_if_changed /etc/logrotate.d/mosquitto-iomatex 0644 <<'EOF'
if [ -s /etc/logrotate.d/mosquitto ]; then
if [ -e /etc/logrotate.d/mosquitto-iomatex ]; then
rm -f /etc/logrotate.d/mosquitto-iomatex
MOSQ_ROTATE_CHANGED=1
log "Removed duplicate IOMATEX Mosquitto logrotate policy; package policy is authoritative"
fi
else
write_if_changed /etc/logrotate.d/mosquitto-iomatex 0644 <<'EOF'
/var/log/mosquitto/mosquitto.log
{
size 10M
@ -1211,8 +1377,9 @@ write_if_changed /etc/logrotate.d/mosquitto-iomatex 0644 <<'EOF'
create 0640 mosquitto mosquitto
}
EOF
if [ "$WRITE_CHANGED" -eq 1 ]; then
if [ "$WRITE_CHANGED" -eq 1 ]; then
MOSQ_ROTATE_CHANGED=1
fi
fi
write_if_changed /usr/local/sbin/iomatex-log-watchdog 0755 <<'EOF'
@ -1394,6 +1561,11 @@ log "Hostname preserved: $(hostname)"
log "User: iomatex (password MUST be changed on first login)"
log "Cockpit: https://${IP_MAIN}:9090"
log "Log file: $LOG"
mkdir -p "$STAGE_ENV_STATE_DIR"
write_if_changed "$STAGE_ENV_STATE_FILE" 0644 <<EOF
installed_at=$(date -u +'%FT%TZ')
storage_contract_version=1
EOF
REG_NOW="$(iw reg get 2>/dev/null | awk '/^country /{print $2; exit}' | sed 's/:.*//' || true)"
@ -1420,6 +1592,9 @@ echo " Password policy : minlen=8 (NO dictionary), pam_unix obscure OFF"
echo
echo " Userdata usage (cold-boot safe):"
echo " - /userdata fstab entry is non-blocking when present"
echo " - ext4 errors remount /userdata read-only instead of continuing writes"
echo " - clean legacy filesystems receive a journal offline before a future mount"
echo " - damaged filesystems are never modified automatically"
echo " - no swap on /userdata"
echo " - generic userdata log root at /userdata/logs/iomatex when mounted"
echo

View File

@ -0,0 +1,29 @@
#!/usr/bin/env python3
import importlib.util
import pathlib
import unittest
MODULE_PATH = pathlib.Path(__file__).with_name("iomatex_storage_health.py")
SPEC = importlib.util.spec_from_file_location("iomatex_storage_health", MODULE_PATH)
storage_health = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(storage_health)
class EmmcEstimateTest(unittest.TestCase):
def test_first_lifetime_bucket_means_zero_to_ten_percent(self):
self.assertEqual((0, 10), storage_health.lifetime_range("0x01"))
def test_worst_lifetime_register_controls_score(self):
self.assertEqual(7, storage_health.health_score([1, 4], 1))
def test_pre_eol_warning_caps_score(self):
self.assertEqual(4, storage_health.health_score([1, 1], 2))
def test_unknown_register_is_not_presented_as_healthy(self):
self.assertIsNone(storage_health.health_score([None, 0], None))
self.assertEqual("unknown", storage_health.score_label(None))
if __name__ == "__main__":
unittest.main()

Binary file not shown.

View File

@ -0,0 +1,12 @@
/var/lib/itscreen/logs/*.log
/var/lib/itscreen/data/it-screen/it-screen/log_playbacks/*.log
/var/lib/itscreen/data/it-screen/it-screen/log_periphery/*.log
{
size 20M
rotate 5
compress
missingok
notifempty
copytruncate
su itscreen itscreen
}

View File

@ -408,19 +408,7 @@ ensure_runtime_directories() {
install_itscreen_logrotate() {
step "Install IT-Screen logrotate policy"
write_file /etc/logrotate.d/itscreen 0644 root root <<'EOF'
/var/lib/itscreen/logs/*.log
/var/lib/itscreen/data/it-screen/it-screen/log_playbacks/*.log
/var/lib/itscreen/data/it-screen/it-screen/log_periphery/*.log
{
size 20M
rotate 5
compress
missingok
notifempty
copytruncate
}
EOF
write_file /etc/logrotate.d/itscreen 0644 root root <"${SCRIPT_DIR}/itscreen.logrotate"
}
install_itscreen_config() {
@ -1252,7 +1240,8 @@ install_systemd_unit() {
Description=ITSCREEN dedicated X11 session
Wants=network-online.target
Wants=iomatex-pulseaudio.service
After=NetworkManager.service network-online.target systemd-user-sessions.service iomatex-pulseaudio.service sound.target
RequiresMountsFor=/userdata
After=userdata.mount NetworkManager.service network-online.target systemd-user-sessions.service iomatex-pulseaudio.service sound.target
Conflicts=lightdm.service display-manager.service
Before=lightdm.service display-manager.service
StartLimitIntervalSec=300

View File

@ -230,7 +230,9 @@ fi
cat >"$MAIN_SNIPPET" <<'__IOMATEX_LISTENER__'
# IOMATEX managed main listener (single source of truth)
per_listener_settings true
listener 1883 0.0.0.0
# Local message bus only. Remote/LAN clients must never bypass the Edge
# services and publish into the cloud bridge through this listener.
listener 1883 127.0.0.1
protocol mqtt
allow_anonymous true
__IOMATEX_LISTENER__
@ -446,7 +448,8 @@ topic iomatex/# out 0 "" ""
topic iomatex/# in 0 "" ""
__LEGACY_IOMATEX__
chmod 644 "$BRIDGE_CONF" || true
chown root:mosquitto "$BRIDGE_CONF" || true
chmod 640 "$BRIDGE_CONF" || true
}
restart_broker_if_changed(){

View File

@ -5,6 +5,13 @@
- Expose one normalized status endpoint: `/api/status`.
- Expose focused lightweight detail endpoints when a core card needs richer data, for example `/api/display`.
- Expose focused operational endpoints for top-level tabs, for example `/api/health/summary`, `/api/network/summary`, `/api/network/scan`.
- Regional settings use the authenticated `/api/system/timezone` GET/POST
contract. The backend accepts only a value from the operating system's
validated zoneinfo list and applies it through `timedatectl`.
- Keep storage probing owned by `stage_env`: Console reads the versioned
`/usr/local/sbin/iomatex-storage-health --json` contract and exposes it as
`storage` in `/api/health/summary`. Do not duplicate eMMC register or ext4
parsing in the Console backend.
- Load provider modules from `providers.d`.
- Cache recent status briefly to avoid repeated shell work on every page render.

View File

@ -23,6 +23,7 @@ from datetime import datetime
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from itscreen_registration import get_registration_status, register_device, reset_registration
from modbus_backend import (
ApiError as ModbusApiError,
@ -45,7 +46,9 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 2.2.46"
UI_VERSION = "V 2.2.78"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo"
DEFAULT_CONFIG = {
"bind": "0.0.0.0",
@ -409,6 +412,76 @@ def change_system_password(username, new_password):
return True, output or "Password changed successfully"
def list_system_timezones():
rc, stdout, _ = run(["timedatectl", "list-timezones"], timeout=10)
candidates = stdout.splitlines() if rc == 0 else []
if not candidates:
for table_name in ("zone1970.tab", "zone.tab"):
table_path = os.path.join(ZONEINFO_ROOT, table_name)
for raw_line in read_text(table_path).splitlines():
if not raw_line or raw_line.startswith("#"):
continue
parts = raw_line.split("\t")
if len(parts) >= 3:
candidates.append(parts[2].strip())
zones = []
zoneinfo_prefix = os.path.realpath(ZONEINFO_ROOT) + os.sep
for candidate in candidates:
zone = str(candidate).strip()
if not zone or zone.startswith("/") or ".." in zone.split("/"):
continue
zone_path = os.path.realpath(os.path.join(ZONEINFO_ROOT, zone))
if not zone_path.startswith(zoneinfo_prefix):
continue
if os.path.isfile(zone_path):
zones.append(zone)
return sorted(set(zones))
def get_system_timezone():
rc, stdout, _ = run(["timedatectl", "show", "--property=Timezone", "--value"], timeout=5)
if rc == 0 and stdout.strip():
return stdout.strip()
configured = read_text("/etc/timezone")
if configured:
return configured.splitlines()[0].strip()
target = os.path.realpath("/etc/localtime")
zoneinfo_prefix = os.path.realpath(ZONEINFO_ROOT) + os.sep
return target[len(zoneinfo_prefix):] if target.startswith(zoneinfo_prefix) else ""
def get_timezone_payload(include_available=True):
timezone_name = get_system_timezone()
try:
now = datetime.now(ZoneInfo(timezone_name))
except (ZoneInfoNotFoundError, ValueError):
if hasattr(time, "tzset"):
time.tzset()
now = datetime.now().astimezone()
payload = {
"ok": True,
"timezone": timezone_name,
"local_time": now.isoformat(timespec="seconds"),
"utc_offset": now.strftime("%z"),
}
if include_available:
payload["available_timezones"] = list_system_timezones()
return payload
def set_system_timezone(timezone):
requested = str(timezone or "").strip()
available = list_system_timezones()
if not requested or requested not in available:
raise ValueError("Invalid or unavailable time zone")
rc, _, stderr = run(["timedatectl", "set-timezone", requested], timeout=15)
if rc != 0:
raise RuntimeError(stderr or "Failed to set system time zone")
if get_system_timezone() != requested:
raise RuntimeError("System did not confirm the selected time zone")
return get_timezone_payload(include_available=True)
def utc_now_iso():
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
@ -1461,6 +1534,29 @@ def get_runtime_status():
}
def get_storage_health():
unavailable = {
"schema_version": 1,
"available": False,
"status": "unavailable",
"warnings": ["storage_health_contract_unavailable"],
"emmc": {"available": False},
"filesystem": {"mount_point": "/userdata", "status": "unavailable"},
}
if not os.path.isfile(STORAGE_HEALTH_COMMAND) or not os.access(STORAGE_HEALTH_COMMAND, os.X_OK):
return unavailable
rc, stdout, _ = run([STORAGE_HEALTH_COMMAND, "--json"], timeout=10)
if rc != 0 or not stdout:
return unavailable
try:
payload = json.loads(stdout)
except (TypeError, ValueError):
return unavailable
if not isinstance(payload, dict) or payload.get("schema_version") != 1:
return unavailable
return payload
def get_health_summary():
sensors = read_thermal_sensors()
disk = get_disk_usage()
@ -1472,6 +1568,7 @@ def get_health_summary():
"load_average": get_load_average(),
"disk": disk,
"temperatures": sensors,
"storage": get_storage_health(),
**get_runtime_status(),
}
@ -2039,6 +2136,110 @@ def mqtt_self_test_payload():
}
def _mqtt_wait_for_message(sub_cmd, pub_cmd, expected, timeout=7, timeout_error="MQTT response was not received in time"):
started = time.time()
sub_proc = subprocess.Popen(sub_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
try:
time.sleep(0.2)
pub_rc, _, pub_stderr = run(pub_cmd, timeout=4)
if pub_rc != 0:
sub_proc.terminate()
sub_proc.communicate(timeout=1)
return False, None, pub_stderr or "MQTT publish failed"
stdout, stderr = sub_proc.communicate(timeout=timeout)
received = (stdout or "").strip()
if sub_proc.returncode == 0 and received == expected:
return True, int((time.time() - started) * 1000), ""
return False, None, stderr or "Expected MQTT message was not received"
except subprocess.TimeoutExpired:
try:
sub_proc.kill()
except Exception:
pass
return False, None, timeout_error
except Exception:
try:
sub_proc.kill()
except Exception:
pass
# Never serialize subprocess exceptions here: TimeoutExpired and
# OSError may include the full argv, including the MQTT -P secret.
return False, None, "MQTT diagnostic command failed"
def mqtt_bridge_self_test_payload():
env = read_env_file("/etc/iomatex/mqtt_bridge.env")
remote_host = str(env.get("REMOTE_HOST", "")).strip()
remote_port = str(env.get("REMOTE_PORT", "1883")).strip() or "1883"
remote_username = str(env.get("REMOTE_USERNAME", "")).strip()
remote_password = str(env.get("REMOTE_PASSWORD", ""))
remote_tls = str(env.get("REMOTE_TLS", "0")).strip() == "1"
tested_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
if not shutil.which("mosquitto_pub") or not shutil.which("mosquitto_sub"):
return {"ok": False, "status": "error", "status_text": "Mosquitto client tools are not installed", "tested_at": tested_at}
if not remote_host:
return {"ok": False, "status": "error", "status_text": "Remote MQTT broker is not configured", "tested_at": tested_at}
remote_common = ["-h", remote_host, "-p", remote_port]
if remote_username:
remote_common.extend(["-u", remote_username])
if remote_password:
remote_common.extend(["-P", remote_password])
if remote_tls:
remote_common.extend(["--cafile", "/etc/ssl/certs/ca-certificates.crt"])
token = secrets.token_hex(8)
topic_root = f"iomatex/diagnostics/bridge-self-test/{token}"
outbound_topic = f"{topic_root}/outbound"
inbound_topic = f"{topic_root}/inbound"
outbound_message = f"BRIDGE_REQUEST token={token}"
inbound_message = f"BRIDGE_RESPONSE request_token={token}"
round_trip_started = time.time()
outbound_ok, outbound_latency, outbound_error = _mqtt_wait_for_message(
["mosquitto_sub", *remote_common, "-t", outbound_topic, "-C", "1", "-W", "6"],
["mosquitto_pub", "-h", "127.0.0.1", "-p", "1883", "-t", outbound_topic, "-m", outbound_message],
outbound_message,
timeout_error="Remote MQTT broker did not receive the request in time",
)
if outbound_ok:
inbound_ok, inbound_latency, inbound_error = _mqtt_wait_for_message(
["mosquitto_sub", "-h", "127.0.0.1", "-p", "1883", "-t", inbound_topic, "-C", "1", "-W", "6"],
["mosquitto_pub", *remote_common, "-t", inbound_topic, "-m", inbound_message],
inbound_message,
timeout_error="Local MQTT broker did not receive the response in time",
)
else:
inbound_ok, inbound_latency, inbound_error = False, None, "Response was not sent because the server did not receive the request"
ok = outbound_ok and inbound_ok
return {
"ok": ok,
"status": "ok" if ok else "error",
"status_text": "MQTT bridge works in both directions" if ok else "MQTT bridge round-trip failed",
"tested_at": tested_at,
"remote_host": remote_host,
"remote_port": remote_port,
"correlation_token": token,
"round_trip_latency_ms": int((time.time() - round_trip_started) * 1000) if ok else None,
"outbound": {"ok": outbound_ok, "topic": outbound_topic, "latency_ms": outbound_latency, "error": outbound_error},
"inbound": {"ok": inbound_ok, "topic": inbound_topic, "latency_ms": inbound_latency, "error": inbound_error},
}
def mqtt_path_self_test_payload():
local_result = mqtt_self_test_payload()
if not local_result.get("ok"):
return {"ok": False, "status": "error", "status_text": "Local MQTT test failed", "local": local_result, "bridge": {}}
bridge_result = mqtt_bridge_self_test_payload()
return {
"ok": bool(bridge_result.get("ok")),
"status": "ok" if bridge_result.get("ok") else "error",
"status_text": "Full MQTT round-trip completed" if bridge_result.get("ok") else "Full MQTT round-trip failed",
"local": local_result,
"bridge": bridge_result,
}
def normalize_card(card):
item = dict(card)
item.setdefault("id", "unknown")
@ -3034,7 +3235,10 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": str(exc), "services": []}, code=500)
return
if parsed.path == "/api/mqtt/self-test":
self.send_json(mqtt_self_test_payload())
self.send_json(mqtt_path_self_test_payload())
return
if parsed.path == "/api/mqtt/bridge-self-test":
self.send_json(mqtt_bridge_self_test_payload())
return
if parsed.path == "/api/ap/status":
try:
@ -3051,6 +3255,12 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/system/timezone":
try:
self.send_json(get_timezone_payload(include_available=True))
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=500)
return
if parsed.path == "/api/network/summary":
try:
self.send_json({
@ -3234,6 +3444,21 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": True, "message": "System password changed successfully"})
return
if parsed.path == "/api/system/timezone":
payload = self.read_json_body()
if payload is None:
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
response = set_system_timezone(payload.get("timezone"))
response["message"] = "System time zone changed successfully"
self.send_json(response)
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
if parsed.path == "/api/ap/password/change":
payload = self.read_json_body()
if payload is None:

View File

@ -1,5 +1,6 @@
#!/usr/bin/env python3
import json
import ipaddress
import os
import queue
import re
@ -7,7 +8,8 @@ import sys
import tempfile
import threading
import time
from urllib.parse import urlparse
import uuid
from urllib.parse import urlparse, urlunparse
try:
import paho.mqtt.client as mqtt
@ -17,33 +19,23 @@ except Exception:
STATE_PATH = "/etc/iomatex/itscreen_registration.json"
MQTT_URL = os.environ.get("ITSCREEN_MQTT_URL", "mqtt://127.0.0.1:1883").strip() or "mqtt://127.0.0.1:1883"
MQTT_ENVIRONMENT = os.environ.get("MQTT_ENVIRONMENT", "it-screen/its-docker").strip().strip("/") or "it-screen/its-docker"
LOGIN_PASSWORD = os.environ.get("ITSCREEN_DEVICE_PASSWORD", "eXXI0wkHBmNBnVbE").strip() or "eXXI0wkHBmNBnVbE"
REGISTER_TIMEOUT_SEC = 25
REGISTER_RECOVERY_TIMEOUT_SEC = 35
REPLY_TIMEOUT_SEC = 6
PUBLISH_TIMEOUT_SEC = 2
REGISTRATION_LOCK_TIMEOUT_SEC = REGISTER_TIMEOUT_SEC + REGISTER_RECOVERY_TIMEOUT_SEC + REPLY_TIMEOUT_SEC
NOT_SPECIFIED = "Not specified"
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}$")
SETTINGS_CATEGORY = "server"
ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf"
SETTINGS_CONTRACTS = (
{"contract_prefix": "it-screen", "base_prefix": "it-screen/$devices/settings"},
{"contract_prefix": "iomatex", "base_prefix": "iomatex/$devices/settings"},
{"contract_prefix": "universal", "base_prefix": "$devices/settings"},
)
DEFAULT_CONTRACT_PREFIX = SETTINGS_CONTRACTS[0]["contract_prefix"]
REGISTRATION_STORE_PATH = "/var/lib/itscreen/data/it-screen/it-screen/registration.ini"
MQTT_TOPIC_SEGMENT_RE = re.compile(r"^[A-Za-z0-9._-]+$")
DEVICE_TOPIC_PREFIXES = ("it-screen/devices", "iomatex/devices", "devices")
ITSCREEN_HOSTS = {
"dev.it-screen.com",
"rest.dev.it-screen.com",
}
IOMATEX_HOSTS = {
"uae.iomatex.com",
"ae.iomatex.com",
"rest.uae.iomatex.com",
"rest.ae.iomatex.com",
}
_REGISTRATION_LOCK = threading.Lock()
def _debug(message):
@ -80,23 +72,12 @@ def _device_identity():
}
def _contract_catalog():
return {item["contract_prefix"]: dict(item) for item in SETTINGS_CONTRACTS}
def _contract_by_prefix(contract_prefix):
return _contract_catalog().get(str(contract_prefix or "").strip())
def _host_contract_hint(host):
value = str(host or "").strip().lower()
if not value:
return ""
if value in ITSCREEN_HOSTS:
return "it-screen"
if value in IOMATEX_HOSTS:
return "iomatex"
return "universal"
def _mqtt_head_namespace(environment=None):
value = str(environment if environment is not None else MQTT_ENVIRONMENT).strip().strip("/")
head = value.split("/", 1)[0] if value else ""
if not head or not MQTT_TOPIC_SEGMENT_RE.fullmatch(head):
raise RuntimeError("MQTT_ENVIRONMENT has an invalid head namespace")
return head
def get_candidate_device_topics(device_id, server_host_hint=None):
@ -119,14 +100,34 @@ def get_candidate_device_topics(device_id, server_host_hint=None):
return topics
def _build_contract_topics(device_id, contract_prefix):
contract = _contract_by_prefix(contract_prefix)
if not contract:
raise ValueError("Unknown settings contract")
base = f"{contract['base_prefix']}/{device_id}"
def _build_contract_topics(device_id):
contract_prefix = _mqtt_head_namespace()
base_prefix = f"{contract_prefix}/$devices/settings"
base = f"{base_prefix}/{device_id}"
return {
"contract_prefix": contract["contract_prefix"],
"base_prefix": contract["base_prefix"],
"contract_prefix": contract_prefix,
"base_prefix": base_prefix,
"request_topic": f"{base}/sub",
"response_topic": f"{base}/pub",
"category": SETTINGS_CATEGORY,
}
def _build_server_contract_topics(device_id, mqtt_config):
mqtt_config = mqtt_config if isinstance(mqtt_config, dict) else {}
prefix = str(mqtt_config.get("prefix") or "").strip().strip("/")
try:
contract_version = max(1, int(mqtt_config.get("contract_version") or 1))
except (TypeError, ValueError):
contract_version = 1
if not prefix or any(not MQTT_TOPIC_SEGMENT_RE.fullmatch(part) for part in prefix.split("/")):
raise RuntimeError("Registration server returned an invalid MQTT prefix")
control_prefix = prefix if contract_version >= 2 else prefix.split("/", 1)[0]
base = f"{control_prefix}/$devices/settings/{device_id}"
return {
"contract_prefix": control_prefix,
"mqtt_prefix": prefix,
"contract_version": contract_version,
"request_topic": f"{base}/sub",
"response_topic": f"{base}/pub",
"category": SETTINGS_CATEGORY,
@ -134,51 +135,52 @@ def _build_contract_topics(device_id, contract_prefix):
def get_candidate_settings_topics(device_id, preferred_contract=None, server_host_hint=None):
ordered = []
seen = set()
host_contract = _host_contract_hint(server_host_hint)
for candidate in (preferred_contract, host_contract):
if candidate and candidate not in seen and _contract_by_prefix(candidate):
ordered.append(candidate)
seen.add(candidate)
if host_contract == "it-screen":
fallback_order = ("universal", "iomatex")
elif host_contract == "iomatex":
fallback_order = ("universal", "it-screen")
elif host_contract == "universal":
fallback_order = (DEFAULT_CONTRACT_PREFIX, "iomatex")
else:
fallback_order = (DEFAULT_CONTRACT_PREFIX, "iomatex", "universal")
for candidate in fallback_order:
if candidate and candidate not in seen and _contract_by_prefix(candidate):
ordered.append(candidate)
seen.add(candidate)
for contract in SETTINGS_CONTRACTS:
candidate = contract["contract_prefix"]
if candidate in seen:
continue
ordered.append(candidate)
seen.add(candidate)
return [_build_contract_topics(device_id, contract_prefix) for contract_prefix in ordered]
# Compatibility is configured explicitly through MQTT_ENVIRONMENT. Never
# probe alternate topic trees: a timeout there can hide the real response
# from the authoritative server contract.
return [_build_contract_topics(device_id)]
def validate_host(host):
value = str(host or "").strip().lower()
value = str(host or "").strip()
if not value:
raise ValueError("Invalid server host")
if any(ch.isspace() for ch in value):
raise ValueError("Invalid server host")
if "://" in value:
parsed = urlparse(value if "://" in value else f"//{value}")
if parsed.scheme and parsed.scheme.lower() not in ("http", "https"):
raise ValueError("Invalid server host")
if "/" in value:
if parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError("Invalid server host")
if value.endswith("."):
value = value[:-1]
if value and not value.startswith("rest."):
value = f"rest.{value}"
if not HOST_RE.fullmatch(value):
hostname = str(parsed.hostname or "").rstrip(".").lower()
if not hostname:
raise ValueError("Invalid server host")
try:
parsed.port
except ValueError as exc:
raise ValueError("Invalid server host") from exc
try:
ipaddress.ip_address(hostname)
except ValueError:
if not HOST_RE.fullmatch(hostname):
raise ValueError("Invalid server host")
value = value.rstrip("/")
if hostname == "localhost":
return value
try:
ipaddress.ip_address(hostname)
return value
except ValueError:
pass
if hostname.startswith("rest."):
return value
normalized_hostname = f"rest.{hostname}"
port_suffix = f":{parsed.port}" if parsed.port is not None else ""
if "://" not in value:
return f"{normalized_hostname}{port_suffix}{parsed.path}"
return urlunparse(parsed._replace(netloc=f"{normalized_hostname}{port_suffix}"))
def _default_state():
@ -194,9 +196,12 @@ def _default_state():
"device_name": "",
"device_id": identity["device_id"],
"contract_prefix": "",
"mqtt_prefix": "",
"contract_version": 1,
"request_topic": "",
"response_topic": "",
"registered": False,
"local_registered": False,
"logged": False,
"status": "idle",
"last_event": {
@ -230,19 +235,24 @@ def save_state(state):
os.makedirs(directory, exist_ok=True)
safe = _default_state()
safe.update({
"host": str(state.get("host", "") or ""),
"username": str(state.get("username", "") or ""),
"password": str(state.get("password", "") or ""),
"app_version": str(state.get("app_version", "") or ""),
"host": _truncate_empty(state.get("host")),
"username": _truncate_empty(state.get("username")),
# Password and registration token are live contract data, not console
# state. Persisting them here creates unnecessary additional copies.
"password": "",
"app_version": _truncate_empty(state.get("app_version")),
"app_version_code": int(state.get("app_version_code", 0) or 0),
"token": str(state.get("token", "") or ""),
"organization": str(state.get("organization", "") or ""),
"device_name": str(state.get("device_name", "") or ""),
"device_id": str(state.get("device_id", "") or _device_identity()["device_id"]),
"contract_prefix": str(state.get("contract_prefix", "") or ""),
"request_topic": str(state.get("request_topic", "") or ""),
"response_topic": str(state.get("response_topic", "") or ""),
"token": "",
"organization": _truncate_empty(state.get("organization")),
"device_name": _truncate_empty(state.get("device_name")),
"device_id": _truncate_empty(state.get("device_id")) or _device_identity()["device_id"],
"contract_prefix": _truncate_empty(state.get("contract_prefix")),
"mqtt_prefix": _truncate_empty(state.get("mqtt_prefix")),
"contract_version": max(1, int(state.get("contract_version", 1) or 1)),
"request_topic": _truncate_empty(state.get("request_topic")),
"response_topic": _truncate_empty(state.get("response_topic")),
"registered": bool(state.get("registered", False)),
"local_registered": bool(state.get("local_registered", state.get("registered", False))),
"logged": bool(state.get("logged", False)),
"status": str(state.get("status", "idle") or "idle"),
})
@ -276,7 +286,10 @@ def _parse_mqtt_url(raw_url):
def _truncate_empty(value):
text = str(value or "").strip()
return text
# Presentation fallbacks must never become registration contract data.
# Older console builds could persist this UI label into mqtt_prefix and
# subsequently reject it as an invalid MQTT topic.
return "" if text == NOT_SPECIFIED else text
def _normalize_registration_token(value):
@ -326,30 +339,106 @@ def _read_simple_key_value_file(path):
def _load_registration_from_itscreen_config(device_id, persisted=None):
if not os.path.exists(ITSCREEN_CONFIG_PATH):
if not os.path.exists(ITSCREEN_CONFIG_PATH) and not os.path.exists(REGISTRATION_STORE_PATH):
return {}
raw = _read_simple_key_value_file(ITSCREEN_CONFIG_PATH)
if not raw:
registration_store = _read_simple_key_value_file(REGISTRATION_STORE_PATH)
if not raw and not registration_store:
return {}
host = _truncate_empty(raw.get("server"))
contract_hint = _host_contract_hint(host) or DEFAULT_CONTRACT_PREFIX
contract_meta = _build_contract_topics(device_id, contract_hint)
host = _truncate_empty(registration_store.get("server")) or _truncate_empty(raw.get("server"))
mqtt_config = {
"prefix": _truncate_empty(raw.get("mqttPrefix")),
"contract_version": raw.get("mqttContractVersion") or 1,
}
try:
contract_meta = _build_server_contract_topics(device_id, mqtt_config)
except RuntimeError:
contract_meta = _build_contract_topics(device_id)
payload = {
"host": host,
"server": host,
"username": _truncate_empty(raw.get("deviceName")) or _truncate_empty(raw.get("devTitle")) or device_id,
"password": _truncate_empty(raw.get("password")),
"device_name": _truncate_empty(raw.get("deviceName")) or _truncate_empty(raw.get("devTitle")) or device_id,
"registered": _bool_value(raw.get("isRegistered"), default=False),
"logged": _bool_value(raw.get("isLogged"), default=False),
"username": _truncate_empty(registration_store.get("device_name")) or _truncate_empty(raw.get("deviceName")) or _truncate_empty(raw.get("devTitle")) or device_id,
"password": _truncate_empty(registration_store.get("password")) or _truncate_empty(raw.get("password")),
"device_name": _truncate_empty(registration_store.get("device_name")) or _truncate_empty(raw.get("deviceName")) or _truncate_empty(raw.get("devTitle")) or device_id,
"registered": _bool_value(
registration_store.get("is_registered")
if "is_registered" in registration_store
else raw.get("isRegistered"),
default=False,
),
"logged": _bool_value(
registration_store.get("is_logged")
if "is_logged" in registration_store
else raw.get("isLogged"),
default=False,
),
}
return _normalize_registration_payload(payload, persisted=persisted, source="config", contract_meta=contract_meta)
def _active_contract_meta(device_id, persisted=None):
persisted = persisted or {}
raw = _read_simple_key_value_file(ITSCREEN_CONFIG_PATH)
mqtt_config = {
"prefix": _truncate_empty(raw.get("mqttPrefix")) or _truncate_empty(persisted.get("mqtt_prefix")),
"contract_version": raw.get("mqttContractVersion") or persisted.get("contract_version") or 1,
}
if mqtt_config["prefix"]:
return _build_server_contract_topics(device_id, mqtt_config)
return _build_contract_topics(device_id)
def _candidate_login_passwords(device_id, persisted=None):
return [LOGIN_PASSWORD]
def _same_registration_host(left, right):
try:
return validate_host(left) == validate_host(right)
except (TypeError, ValueError):
return _truncate_empty(left).lower().rstrip("/") == _truncate_empty(right).lower().rstrip("/")
def _registration_transport_interrupted(exc):
text = str(exc or "").lower()
return isinstance(exc, TimeoutError) or any(marker in text for marker in (
"device settings service is unavailable",
"mqtt response timeout",
"mqtt subscribe timeout",
"mqtt publish failed",
"no response from device",
"login response timeout",
))
def _recover_dispatched_registration(device_id, persisted, target_host, timeout=REGISTER_RECOVERY_TIMEOUT_SEC):
"""Observe a dispatched registration after the Client restarts its MQTT bridge.
Never republish the registration command here: legacy servers do not
guarantee idempotency for concurrent requests with the same device ID.
"""
deadline = time.time() + timeout
last_error = None
while time.time() < deadline:
contract_meta = _active_contract_meta(device_id, persisted)
try:
with MqttSettingsSession(device_id, contract_meta) as session:
session.login(_candidate_login_passwords(device_id, persisted))
server_state = session.get_server_state()
current_host = _truncate_empty((server_state or {}).get("host")) or _truncate_empty((server_state or {}).get("server"))
ready = (
_same_registration_host(current_host, target_host)
and _bool_value((server_state or {}).get("registered"), default=False)
and _bool_value((server_state or {}).get("logged"), default=False)
)
if ready:
return contract_meta, server_state
except Exception as exc:
last_error = exc
time.sleep(1)
raise RuntimeError("Registration result is unavailable after MQTT reconnect") from last_error
def _extract_response_payload(response_text):
raw = str(response_text or "").strip()
if not raw:
@ -503,9 +592,17 @@ def _normalize_registration_payload(server_state, persisted=None, source="mqtt",
app_version_code = 0
meta = dict(contract_meta or {})
contract_prefix = _truncate_empty(meta.get("contract_prefix")) or _truncate_empty(persisted.get("contract_prefix"))
mqtt_prefix = _truncate_empty(meta.get("mqtt_prefix")) or _truncate_empty(persisted.get("mqtt_prefix"))
try:
contract_version = max(1, int(meta.get("contract_version") or persisted.get("contract_version") or 1))
except (TypeError, ValueError):
contract_version = 1
request_topic = _truncate_empty(meta.get("request_topic")) or _truncate_empty(persisted.get("request_topic"))
response_topic = _truncate_empty(meta.get("response_topic")) or _truncate_empty(persisted.get("response_topic"))
category = _truncate_empty(meta.get("category")) or SETTINGS_CATEGORY
local_registered = _bool_value(payload.get("registered"), default=False) or _bool_value(payload.get("local_registered"), default=False)
logged = _bool_value(payload.get("logged"), default=False)
verified_registered = local_registered and logged
return {
"ok": True,
"source": source,
@ -519,22 +616,24 @@ def _normalize_registration_payload(server_state, persisted=None, source="mqtt",
"organization": _text_or_default(payload.get("organization")),
"token": _text_or_default(payload.get("token")),
"contract_prefix": _text_or_default(contract_prefix),
"mqtt_prefix": _text_or_default(mqtt_prefix),
"contract_version": contract_version,
"request_topic": _text_or_default(request_topic),
"response_topic": _text_or_default(response_topic),
"category": _text_or_default(category),
"password_present": bool(password),
"registered": _bool_value(payload.get("registered"), default=False),
"logged": _bool_value(payload.get("logged"), default=False),
"registered": verified_registered,
"local_registered": local_registered,
"logged": logged,
"password_state": "Password set" if password else NOT_SPECIFIED,
"username": username,
"status": "ready" if _bool_value(payload.get("registered"), default=False) else "not_registered",
"status": "ready" if verified_registered else ("incomplete" if local_registered else "not_registered"),
"last_event": persisted.get("last_event", {
"action": "",
"operation": "",
"status": "",
"timestamp": "",
}),
"raw_payload": dict(payload),
}
@ -712,9 +811,13 @@ class MqttSettingsSession:
)
def clear_server_registration(self):
request_id = uuid.uuid4().hex
return self.publish_and_wait(
{"action": "clear", "category": SETTINGS_CATEGORY},
lambda item: isinstance(item, dict) and item.get("action") == "clear" and item.get("category") == SETTINGS_CATEGORY,
{"action": "clear", "category": SETTINGS_CATEGORY, "request_id": request_id},
lambda item: isinstance(item, dict)
and item.get("action") == "clear"
and item.get("category") == SETTINGS_CATEGORY
and item.get("request_id") == request_id,
timeout=REPLY_TIMEOUT_SEC,
)
@ -756,7 +859,7 @@ class MqttSettingsSession:
payload["token"] = token_value
self.publish(payload)
def wait_registered_event(self, timeout=REGISTER_TIMEOUT_SEC):
def wait_registered_event(self, expected_operation=None, timeout=REGISTER_TIMEOUT_SEC):
deadline = time.time() + timeout
seen = set()
while time.time() < deadline:
@ -770,6 +873,8 @@ class MqttSettingsSession:
continue
if candidate.get("action") != "registered":
continue
if expected_operation and _truncate_empty(candidate.get("operation")) != expected_operation:
continue
fingerprint = (
candidate.get("action"),
candidate.get("operation"),
@ -805,6 +910,8 @@ def _registration_error_message(event):
if response_text == "ERR_CONNECTION_TIMED_OUT":
return "Connection timed out while contacting registration server"
status_code = _event_status_code(event)
if status_code == 0:
return "Registration server did not respond"
if status_code == 422:
return "Device with current ID is already registered"
if status_code is not None and status_code >= 300:
@ -820,11 +927,47 @@ def _build_public_status(state, error_text=""):
normalized = _normalize_registration_payload(state, persisted=state)
normalized["status"] = _truncate_empty(state.get("status")) or normalized.get("status") or "idle"
output = dict(normalized)
output.pop("password", None)
if error_text:
output["error"] = error_text
return output
def _registration_is_absent(state):
return (
not _bool_value((state or {}).get("registered"), default=False)
and not _bool_value((state or {}).get("local_registered"), default=False)
and not _bool_value((state or {}).get("logged"), default=False)
)
def _cleared_registration_state(previous=None):
previous = previous or {}
identity = _device_identity()
contract_meta = _build_contract_topics(identity["device_id"])
cleared = _default_state()
cleared.update({
"app_version": _truncate_empty(previous.get("app_version")),
"app_version_code": int(previous.get("app_version_code") or 0),
"device_id": identity["device_id"],
"device_name": identity["device_name"],
"contract_prefix": contract_meta["contract_prefix"],
"request_topic": contract_meta["request_topic"],
"response_topic": contract_meta["response_topic"],
"registered": False,
"local_registered": False,
"logged": False,
"status": "not_registered",
"last_event": {
"action": "clear",
"operation": "device",
"status": "success",
"timestamp": _event_timestamp(),
},
})
return cleared
def publish_settings_request(session, payload):
session.publish(payload)
@ -854,28 +997,21 @@ def _read_device_registration_snapshot(session, device_id, server_host_hint=""):
def _with_settings_contract(device_id, persisted, operation_name, callback, server_host_hint=""):
preferred = _truncate_empty((persisted or {}).get("contract_prefix"))
candidates = get_candidate_settings_topics(device_id, preferred_contract=preferred, server_host_hint=server_host_hint)
last_error = None
for contract_meta in candidates:
contract_meta = _active_contract_meta(device_id, persisted)
_debug(
f"{operation_name}: trying contract={contract_meta['contract_prefix']} "
f"{operation_name}: using configured contract={contract_meta['contract_prefix']} "
f"request={contract_meta['request_topic']} response={contract_meta['response_topic']}"
)
try:
with MqttSettingsSession(device_id, contract_meta) as session:
result = callback(session, contract_meta)
_debug(f"{operation_name}: selected contract={contract_meta['contract_prefix']}")
return contract_meta, result
except Exception as exc:
last_error = exc
_debug(
f"{operation_name}: contract={contract_meta['contract_prefix']} failed: "
f"{_truncate_empty(str(exc)) or exc.__class__.__name__}"
)
if last_error is not None:
raise last_error
raise RuntimeError("Device settings service is unavailable")
raise
def get_registration_status():
@ -905,11 +1041,14 @@ def get_registration_status():
"device_name": _device_name_from_payload(merged_state),
"device_id": _device_identity()["device_id"],
"contract_prefix": _truncate_empty(contract_meta.get("contract_prefix")),
"mqtt_prefix": _truncate_empty(contract_meta.get("mqtt_prefix")) or _truncate_empty(contract_meta.get("contract_prefix")),
"contract_version": max(1, int(contract_meta.get("contract_version") or 1)),
"request_topic": _truncate_empty(contract_meta.get("request_topic")),
"response_topic": _truncate_empty(contract_meta.get("response_topic")),
"registered": _bool_value(merged_state.get("registered"), default=False),
"registered": _bool_value(merged_state.get("registered"), default=False) and _bool_value(merged_state.get("logged"), default=False),
"local_registered": _bool_value(merged_state.get("registered"), default=False),
"logged": _bool_value(merged_state.get("logged"), default=False),
"status": "ready" if _bool_value(merged_state.get("registered"), default=False) else "not_registered",
"status": "ready" if _bool_value(merged_state.get("registered"), default=False) and _bool_value(merged_state.get("logged"), default=False) else ("incomplete" if _bool_value(merged_state.get("registered"), default=False) else "not_registered"),
"last_event": persisted.get("last_event", {
"action": "",
"operation": "",
@ -935,11 +1074,14 @@ def get_registration_status():
"app_version_code": int(config_fallback.get("app_version_code") or 0),
"device_name": _truncate_empty(config_fallback.get("device_name")),
"contract_prefix": _truncate_empty(config_fallback.get("contract_prefix")),
"mqtt_prefix": _truncate_empty(config_fallback.get("mqtt_prefix")),
"contract_version": max(1, int(config_fallback.get("contract_version") or 1)),
"request_topic": _truncate_empty(config_fallback.get("request_topic")),
"response_topic": _truncate_empty(config_fallback.get("response_topic")),
"registered": _bool_value(config_fallback.get("registered"), default=False),
"registered": _bool_value(config_fallback.get("registered"), default=False) and _bool_value(config_fallback.get("logged"), default=False),
"local_registered": _bool_value(config_fallback.get("local_registered", config_fallback.get("registered")), default=False),
"logged": _bool_value(config_fallback.get("logged"), default=False),
"status": "ready" if _bool_value(config_fallback.get("registered"), default=False) else "not_registered",
"status": "ready" if _bool_value(config_fallback.get("registered"), default=False) and _bool_value(config_fallback.get("logged"), default=False) else ("incomplete" if _bool_value(config_fallback.get("local_registered", config_fallback.get("registered")), default=False) else "not_registered"),
})
save_state(merged)
fallback = _build_public_status(merged, error_text=error_text)
@ -958,29 +1100,60 @@ def get_registration_status():
def register_device(host, token=""):
lock_acquired = _REGISTRATION_LOCK.acquire(timeout=REGISTRATION_LOCK_TIMEOUT_SEC)
if not lock_acquired:
raise RuntimeError("Another cloud registration is still in progress")
try:
return _register_device_once(host, token)
finally:
_REGISTRATION_LOCK.release()
def _register_device_once(host, token=""):
validated_host = validate_host(host)
validated_token = _normalize_registration_token(token)
persisted = load_state()
working = dict(persisted)
working["host"] = validated_host
working["token"] = validated_token
working["registered"] = False
working["logged"] = False
working["status"] = "registering"
save_state(working)
registration_dispatched = False
try:
def _register_flow(session, contract_meta):
nonlocal registration_dispatched
session.login(_candidate_login_passwords(working["device_id"], persisted))
current_server_state = session.get_server_state()
if _bool_value((current_server_state or {}).get("registered"), default=False):
raise RuntimeError("Device is already registered")
current_host = _truncate_empty((current_server_state or {}).get("host")) or _truncate_empty((current_server_state or {}).get("server"))
if (
_bool_value((current_server_state or {}).get("registered"), default=False)
and _same_registration_host(current_host, validated_host)
):
return {
"event": {"action": "registered", "operation": "existing", "status": 200},
"event_payload": {"result": True},
"server_state": current_server_state,
"contract_meta": contract_meta,
"already_active": True,
}
session.register_device(validated_host, validated_token)
event = session.wait_registered_event()
registration_dispatched = True
event = session.wait_registered_event(expected_operation="register")
event_payload = _extract_response_payload_safe(event.get("responseText"))
status_code = _event_status_code(event)
operation = _truncate_empty(event.get("operation"))
register_ok = operation == "register" and status_code is not None and status_code < 300 and bool(event_payload.get("password"))
sanitized_register_ok = operation == "register" and status_code is not None and status_code < 300 and bool(event_payload.get("result"))
if operation == "register" and (register_ok or sanitized_register_ok):
event = session.wait_registered_event(expected_operation="confirm")
event_payload = _extract_response_payload_safe(event.get("responseText"))
status_code = _event_status_code(event)
operation = _truncate_empty(event.get("operation"))
confirm_ok = operation == "confirm" and status_code is not None and status_code < 300 and bool(event_payload.get("result"))
register_ok = operation == "register" and status_code is not None and status_code < 300 and bool(event_payload.get("password"))
if not confirm_ok and not register_ok:
if not confirm_ok:
raise RuntimeError(_registration_error_message(event))
server_state = session.get_server_state()
return {
@ -990,6 +1163,7 @@ def register_device(host, token=""):
"contract_meta": contract_meta,
}
try:
contract_meta, flow = _with_settings_contract(
working["device_id"],
persisted,
@ -997,16 +1171,29 @@ def register_device(host, token=""):
_register_flow,
server_host_hint=validated_host,
)
except Exception as exc:
if not registration_dispatched or not _registration_transport_interrupted(exc):
raise
contract_meta, recovered_state = _recover_dispatched_registration(
working["device_id"], persisted, validated_host
)
flow = {
"event": {"action": "registered", "operation": "recovered", "status": 200},
"event_payload": {"result": True},
"server_state": recovered_state,
"contract_meta": contract_meta,
"recovered_after_reconnect": True,
}
event = flow["event"]
event_payload = flow["event_payload"]
server_state = flow["server_state"]
merged = _extract_registration_fields(server_state, event_payload, working)
merged["host"] = validated_host
merged["token"] = validated_token or _truncate_empty(merged.get("token"))
merged["contract_prefix"] = _truncate_empty(contract_meta.get("contract_prefix"))
merged["request_topic"] = _truncate_empty(contract_meta.get("request_topic"))
merged["response_topic"] = _truncate_empty(contract_meta.get("response_topic"))
merged["status"] = "ready" if merged.get("registered") else "error"
merged.update(contract_meta)
merged["local_registered"] = _bool_value(merged.get("registered"), default=False)
merged["registered"] = _bool_value(merged.get("registered"), default=False) and _bool_value(merged.get("logged"), default=False)
merged["status"] = "ready" if merged.get("registered") else "incomplete"
merged["last_event"] = {
"action": str(event.get("action", "") or ""),
"operation": str(event.get("operation", "") or ""),
@ -1016,8 +1203,12 @@ def register_device(host, token=""):
save_state(merged)
return {
"ok": True,
"status": "registered" if merged.get("registered") else "error",
"message": "Device successfully registered in cloud." if merged.get("registered") else "Cloud registration failed",
"status": "already_active" if flow.get("already_active") else ("registered" if merged.get("registered") else "error"),
"message": (
"Device is already connected to the selected server."
if flow.get("already_active")
else ("Device successfully registered in cloud." if merged.get("registered") else "Cloud registration failed")
),
"data": _build_public_status(merged),
}
except TimeoutError as exc:
@ -1032,6 +1223,14 @@ def register_device(host, token=""):
def reset_registration():
persisted = load_state()
if _registration_is_absent(persisted):
cleared = _cleared_registration_state(persisted)
save_state(cleared)
return {
"ok": True,
"message": "Cloud registration has been reset on device.",
"data": _build_public_status(cleared),
}
working = dict(persisted)
working["status"] = "resetting"
save_state(working)
@ -1042,38 +1241,27 @@ def reset_registration():
cleared = session.clear_server_registration()
if not _bool_value((cleared or {}).get("result"), default=False):
raise RuntimeError(_truncate_empty((cleared or {}).get("error")) or "Device reset rejected")
return session.get_server_state()
return cleared
contract_meta, server_state = _with_settings_contract(
contract_meta, _clear_response = _with_settings_contract(
working["device_id"],
persisted,
"reset",
_reset_flow,
server_host_hint=working.get("host", ""),
)
merged = _default_state()
merged = _cleared_registration_state(persisted)
merged.update({
"host": _truncate_empty((server_state or {}).get("host")) or _truncate_empty((server_state or {}).get("server")),
"username": _truncate_empty((server_state or {}).get("username")),
"password": _truncate_empty((server_state or {}).get("password")),
"app_version": _truncate_empty((server_state or {}).get("app_version")) or _truncate_empty((server_state or {}).get("client_version")),
"app_version_code": int((server_state or {}).get("app_version_code") or (server_state or {}).get("version_code") or 0),
"token": _truncate_empty((server_state or {}).get("token")),
"organization": _truncate_empty((server_state or {}).get("organization")),
"device_name": _device_name_from_payload(server_state),
"app_version": _truncate_empty(persisted.get("app_version")),
"app_version_code": int(persisted.get("app_version_code") or 0),
"device_id": _device_identity()["device_id"],
"contract_prefix": _truncate_empty(contract_meta.get("contract_prefix")),
"request_topic": _truncate_empty(contract_meta.get("request_topic")),
"response_topic": _truncate_empty(contract_meta.get("response_topic")),
"registered": _bool_value((server_state or {}).get("registered"), default=False),
"logged": _bool_value((server_state or {}).get("logged"), default=False),
"status": "idle",
"last_event": {
"action": "clear",
"operation": "device",
"status": "success",
"timestamp": _event_timestamp(),
},
"registered": False,
"local_registered": False,
"logged": False,
"status": "not_registered",
})
save_state(merged)
return {

View File

@ -0,0 +1,619 @@
#!/usr/bin/env python3
import json
import os
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
import itscreen_registration
from itscreen_registration import validate_host
class ServerAddressValidationTest(unittest.TestCase):
def test_settings_contract_uses_only_environment_head_namespace(self):
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "it-screen/its-docker"):
contracts = itscreen_registration.get_candidate_settings_topics(
"g-box-deadbeef",
preferred_contract="iomatex",
server_host_hint="uae.iomatex.com",
)
self.assertEqual(1, len(contracts))
self.assertEqual("it-screen", contracts[0]["contract_prefix"])
self.assertEqual(
"it-screen/$devices/settings/g-box-deadbeef/sub",
contracts[0]["request_topic"],
)
self.assertEqual(
"it-screen/$devices/settings/g-box-deadbeef/pub",
contracts[0]["response_topic"],
)
def test_server_contract_v1_keeps_legacy_control_root(self):
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "iomatex/ae", "contract_version": 1}
)
self.assertEqual("iomatex/ae", contract["mqtt_prefix"])
self.assertEqual("iomatex/$devices/settings/g-box-deadbeef/sub", contract["request_topic"])
def test_server_contract_v2_uses_full_prefix_everywhere(self):
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "iomatex/eva", "contract_version": 2}
)
self.assertEqual("iomatex/eva", contract["contract_prefix"])
self.assertEqual("iomatex/eva/$devices/settings/g-box-deadbeef/sub", contract["request_topic"])
def test_invalid_environment_head_namespace_is_rejected(self):
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "$invalid/root"):
with self.assertRaisesRegex(RuntimeError, "invalid head namespace"):
itscreen_registration.get_candidate_settings_topics("g-box-deadbeef")
def test_installer_passes_mqtt_environment_to_console_service(self):
installer_path = os.path.join(os.path.dirname(__file__), "..", "..", "ui_installer.sh")
with open(installer_path, "r", encoding="utf-8") as installer_file:
installer = installer_file.read()
self.assertIn('MQTT_ENVIRONMENT="${MQTT_ENVIRONMENT:-it-screen/its-docker}"', installer)
self.assertIn('Environment="MQTT_ENVIRONMENT=${MQTT_ENVIRONMENT}"', installer)
def test_contract_error_is_returned_without_fallback_probe(self):
opened_contracts = []
class Session:
def __init__(self, _device_id, contract_meta):
opened_contracts.append(contract_meta["contract_prefix"])
def __enter__(self):
return self
def __exit__(self, _exc_type, _exc, _traceback):
return False
def fail_with_server_response(_session, _contract_meta):
raise RuntimeError("Registration failed (401)")
with patch.object(itscreen_registration, "MQTT_ENVIRONMENT", "it-screen/its-docker"), \
patch.object(itscreen_registration, "MqttSettingsSession", Session):
with self.assertRaisesRegex(RuntimeError, r"Registration failed \(401\)"):
itscreen_registration._with_settings_contract(
"g-box-deadbeef", {}, "register", fail_with_server_response
)
self.assertEqual(["it-screen"], opened_contracts)
def test_console_state_does_not_persist_registration_secrets(self):
state = itscreen_registration._default_state()
state.update({"password": "mqtt-secret", "token": "registration-secret"})
with tempfile.TemporaryDirectory() as directory, \
patch.object(itscreen_registration, "STATE_PATH", os.path.join(directory, "state.json")):
itscreen_registration.save_state(state)
with open(itscreen_registration.STATE_PATH, "r", encoding="utf-8") as state_file:
persisted = json.load(state_file)
self.assertEqual("", persisted["password"])
self.assertEqual("", persisted["token"])
self.assertNotIn("mqtt-secret", json.dumps(persisted))
self.assertNotIn("registration-secret", json.dumps(persisted))
def test_console_state_does_not_persist_presentation_fallbacks(self):
state = itscreen_registration._default_state()
state.update({
"host": itscreen_registration.NOT_SPECIFIED,
"mqtt_prefix": itscreen_registration.NOT_SPECIFIED,
"contract_prefix": itscreen_registration.NOT_SPECIFIED,
})
with tempfile.TemporaryDirectory() as directory, \
patch.object(itscreen_registration, "STATE_PATH", os.path.join(directory, "state.json")):
itscreen_registration.save_state(state)
persisted = itscreen_registration.load_state()
self.assertEqual("", persisted["host"])
self.assertEqual("", persisted["mqtt_prefix"])
self.assertEqual("", persisted["contract_prefix"])
def test_legacy_presentation_fallback_is_not_a_mqtt_contract(self):
contract = itscreen_registration._active_contract_meta(
"g-box-deadbeef",
{"mqtt_prefix": itscreen_registration.NOT_SPECIFIED},
)
self.assertEqual("it-screen", contract["contract_prefix"])
def test_public_status_does_not_expose_raw_server_payload(self):
state = itscreen_registration._default_state()
state.update({"registered": True, "logged": True, "password": "device-secret"})
public = itscreen_registration._build_public_status(state)
self.assertNotIn("raw_payload", public)
self.assertNotIn("password", public)
self.assertTrue(public["password_present"])
def test_mqtt_status_requires_registered_and_logged_for_verified_registration(self):
incomplete = itscreen_registration.normalize_settings_response({
"registered": True,
"logged": False,
"host": "rest.local.iomatex:8000",
})
self.assertFalse(incomplete["registered"])
self.assertTrue(incomplete["local_registered"])
self.assertFalse(incomplete["logged"])
self.assertEqual(incomplete["status"], "incomplete")
verified = itscreen_registration.normalize_settings_response({
"registered": True,
"logged": True,
"host": "rest.local.iomatex:8000",
})
self.assertTrue(verified["registered"])
self.assertTrue(verified["local_registered"])
self.assertTrue(verified["logged"])
self.assertEqual(verified["status"], "ready")
def test_accepts_existing_server_hostnames_unchanged(self):
self.assertEqual(validate_host("rest.dev.it-screen.com"), "rest.dev.it-screen.com")
self.assertEqual(validate_host("rest.uae.iomatex.com"), "rest.uae.iomatex.com")
def test_adds_rest_prefix_to_custom_domain_names(self):
self.assertEqual(validate_host("dev.it-screen.com"), "rest.dev.it-screen.com")
self.assertEqual(validate_host("uae.iomatex.com"), "rest.uae.iomatex.com")
self.assertEqual(
validate_host("https://dev.it-screen.com:8443/custom/base"),
"https://rest.dev.it-screen.com:8443/custom/base",
)
def test_accepts_custom_hosts_ips_ports_and_urls(self):
accepted = (
"localhost",
"localhost:8000",
"127.0.0.1",
"127.0.0.1:8000",
"http://127.0.0.1:8000/api",
"http://localhost:8000/api",
"https://[::1]:8000/api",
)
for address in accepted:
with self.subTest(address=address):
self.assertEqual(validate_host(address), address)
def test_rejects_unsafe_or_ambiguous_addresses(self):
rejected = (
"",
"host name",
"ftp://example.net",
"https://user:password@example.net",
"https://example.net/api?token=value",
"https://example.net/api#fragment",
"localhost:not-a-port",
)
for address in rejected:
with self.subTest(address=address):
with self.assertRaises(ValueError):
validate_host(address)
def test_status_zero_is_reported_as_unavailable_server(self):
self.assertEqual(
itscreen_registration._registration_error_message({"status": 0, "operation": "register"}),
"Registration server did not respond",
)
def test_registration_uses_client_owned_mqtt_flow(self):
address = "http://127.0.0.1:8000/api"
calls = []
persisted = itscreen_registration._default_state()
class Session:
def __init__(self):
self.events = iter((
{"action": "registered", "operation": "register", "status": 200, "responseText": '{"result":true}'},
{"action": "registered", "operation": "confirm", "status": 200, "responseText": '{"result":true}'},
))
def login(self, _passwords):
calls.append("login")
def get_server_state(self):
calls.append("get")
return {"registered": calls.count("get") > 1, "logged": calls.count("get") > 1}
def register_device(self, host, token):
calls.append(("register", host, token))
def wait_registered_event(self, expected_operation=None):
event = next(self.events)
self_expected = event.get("operation")
if expected_operation != self_expected:
raise AssertionError(f"expected {expected_operation}, got {self_expected}")
return event
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/its-docker", "contract_version": 2}
)
def shared_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
return contract, callback(Session(), contract)
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", side_effect=shared_flow):
response = itscreen_registration.register_device(address)
self.assertIn(("register", address, ""), calls)
self.assertTrue(response["ok"])
self.assertTrue(response["data"]["registered"])
def test_frontend_custom_address_reuses_registration_endpoint(self):
frontend_path = os.path.join(
os.path.dirname(__file__), "..", "frontend", "console.js"
)
with open(frontend_path, "r", encoding="utf-8") as frontend_file:
source = frontend_file.read()
self.assertIn('fetchJson("/api/itscreen/register"', source)
self.assertIn('if (state.itscreen.busyAction) return;', source)
self.assertIn('host: targetAddress', source)
self.assertIn('new URL(address.includes("://") ? address : `https://${address}`)', source)
self.assertIn('confirmAction(', source)
self.assertIn('state.itscreen.serverSelectionDirty = true;', source)
self.assertIn('if (state.activeTab === "tscreen") renderActiveTab();', source)
self.assertIn('!state.itscreen.serverSelectionDirty', source)
self.assertIn('Device successfully registered on {address}.', source)
self.assertIn('Failed to register device on {address}: {error}', source)
self.assertIn('class="buttonSpinner"', source)
self.assertIn('class="registrationProgress"', source)
self.assertIn('aria-busy=', source)
self.assertIn('class="registrationProgressSpinner"', source)
self.assertIn('requestAnimationFrame(() => window.requestAnimationFrame(resolve))', source)
self.assertIn('parsed.hostname = `rest.${hostname}`;', source)
self.assertIn('if (mode !== previousMode)', source)
self.assertIn('state.itscreen.customToken = "";', source)
self.assertNotIn('state.itscreen.customToken = itscreenTokenInputValue(payload && payload.token);', source)
def test_concurrent_registration_requests_are_single_flight(self):
active = 0
max_active = 0
active_lock = threading.Lock()
results = []
def run_once(host, token=""):
nonlocal active, max_active
with active_lock:
active += 1
max_active = max(max_active, active)
time.sleep(0.05)
with active_lock:
active -= 1
return {"host": host, "token": token}
def register():
results.append(itscreen_registration.register_device("rest.eva.iomatex.com"))
with patch.object(itscreen_registration, "_register_device_once", side_effect=run_once):
workers = [threading.Thread(target=register) for _ in range(2)]
for worker in workers:
worker.start()
for worker in workers:
worker.join(timeout=1)
self.assertEqual(1, max_active)
self.assertEqual(2, len(results))
def test_log_toggles_align_with_search_input(self):
css_path = os.path.join(
os.path.dirname(__file__), "..", "frontend", "console.css"
)
with open(css_path, "r", encoding="utf-8") as css_file:
source = css_file.read()
toggle_rule = source.split(".itscreenLogsToggle{", 1)[1].split("}", 1)[0]
self.assertIn("align-self:end", toggle_rule)
self.assertNotIn("align-self:center", toggle_rule)
def test_server_selector_displays_complete_public_hostnames(self):
frontend_path = os.path.join(
os.path.dirname(__file__), "..", "frontend", "console.js"
)
with open(frontend_path, "r", encoding="utf-8") as frontend_file:
source = frontend_file.read()
for hostname in (
"dev.it-screen.com",
"uae.iomatex.com",
"public.it-screen.by",
"test.it-screen.by",
):
self.assertIn(f'label: "{hostname}"', source)
for legacy_label in ('label: "DEV"', 'label: "UAE"', 'label: "PUBLIC BY"', 'label: "TEST BY"'):
self.assertNotIn(legacy_label, source)
def test_single_mqtt_test_owns_the_full_correlated_round_trip(self):
backend_path = os.path.join(os.path.dirname(__file__), "app.py")
frontend_path = os.path.join(os.path.dirname(__file__), "..", "frontend", "console.js")
with open(backend_path, "r", encoding="utf-8") as backend_file:
backend = backend_file.read()
with open(frontend_path, "r", encoding="utf-8") as frontend_file:
frontend = frontend_file.read()
self.assertIn('def mqtt_bridge_self_test_payload():', backend)
self.assertIn('def mqtt_path_self_test_payload():', backend)
self.assertIn('"/api/mqtt/bridge-self-test"', backend)
self.assertIn('topic_root = f"iomatex/diagnostics/bridge-self-test/{token}"', backend)
self.assertIn('outbound_topic = f"{topic_root}/outbound"', backend)
self.assertIn('inbound_topic = f"{topic_root}/inbound"', backend)
self.assertIn('BRIDGE_REQUEST token={token}', backend)
self.assertIn('BRIDGE_RESPONSE request_token={token}', backend)
self.assertIn('self.send_json(mqtt_path_self_test_payload())', backend)
self.assertIn('window.__runMqttSelfTest', frontend)
self.assertNotIn('window.__runMqttBridgeTest', frontend)
self.assertIn('const result = overall.local || {};', frontend)
self.assertIn('const result = overall.bridge || {};', frontend)
self.assertIn('Edge to server', frontend)
self.assertIn('Server to Edge', frontend)
self.assertNotIn('showMqttBridgeSelfTestResult', frontend)
def test_mqtt_timeout_never_exposes_the_subprocess_command_or_password(self):
backend_path = os.path.join(os.path.dirname(__file__), "app.py")
with open(backend_path, "r", encoding="utf-8") as backend_file:
backend = backend_file.read()
helper = backend.split("def _mqtt_wait_for_message", 1)[1].split("def mqtt_bridge_self_test_payload", 1)[0]
self.assertNotIn("str(exc)", helper)
self.assertIn("except subprocess.TimeoutExpired:", helper)
self.assertIn("return False, None, timeout_error", helper)
self.assertIn('return False, None, "MQTT diagnostic command failed"', helper)
def test_registered_device_can_switch_to_a_different_server(self):
old_address = "rest.dev.it-screen.com"
new_address = "http://127.0.0.1:8000/api"
persisted = itscreen_registration._default_state()
persisted.update({"registered": True, "host": old_address})
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/dev", "contract_version": 1}
)
flow = {
"event": {"action": "registered", "operation": "confirm", "status": 200},
"event_payload": {"result": True},
"server_state": {"registered": True, "logged": True},
}
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", return_value=(contract, flow)) as shared_flow:
response = itscreen_registration.register_device(new_address)
self.assertEqual(new_address, shared_flow.call_args.kwargs["server_host_hint"])
self.assertTrue(response["data"]["registered"])
def test_transport_loss_after_dispatch_observes_result_without_republishing(self):
address = "rest.dev.it-screen.com"
persisted = itscreen_registration._default_state()
calls = []
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "iomatex/ae", "contract_version": 1}
)
recovered_contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/dev", "contract_version": 1}
)
class Session:
def login(self, _passwords):
return True
def get_server_state(self):
return {"host": "rest.uae.iomatex.com", "registered": False, "logged": False}
def register_device(self, host, token):
calls.append((host, token))
def wait_registered_event(self, expected_operation=None):
raise RuntimeError("Device settings service is unavailable")
def interrupted_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
return contract, callback(Session(), contract)
recovered_state = {
"host": address,
"registered": True,
"logged": True,
"username": "g-box-deadbeef",
}
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", side_effect=interrupted_flow), \
patch.object(itscreen_registration, "_recover_dispatched_registration", return_value=(recovered_contract, recovered_state)) as recover:
response = itscreen_registration.register_device(address)
self.assertEqual([(address, "")], calls)
recover.assert_called_once()
self.assertTrue(response["ok"])
self.assertEqual("registered", response["status"])
self.assertTrue(response["data"]["registered"])
def test_current_server_is_reported_as_already_active_without_register_publish(self):
address = "rest.dev.it-screen.com"
persisted = itscreen_registration._default_state()
persisted.update({"host": address, "registered": True, "logged": True})
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/dev", "contract_version": 1}
)
class Session:
def login(self, _passwords):
return True
def get_server_state(self):
return {"host": address, "registered": True, "logged": True}
def register_device(self, _host, _token):
raise AssertionError("already-active server must not receive register")
def existing_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
return contract, callback(Session(), contract)
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", side_effect=existing_flow):
response = itscreen_registration.register_device(address)
self.assertTrue(response["ok"])
self.assertEqual("already_active", response["status"])
def test_active_contract_is_read_from_client_config_without_topic_probe(self):
with tempfile.TemporaryDirectory() as directory:
config_path = os.path.join(directory, "it-screen.conf")
with open(config_path, "w", encoding="utf-8") as config_file:
config_file.write("mqttPrefix=iomatex/eva\nmqttContractVersion=2\n")
with patch.object(itscreen_registration, "ITSCREEN_CONFIG_PATH", config_path):
contract = itscreen_registration._active_contract_meta("g-box-deadbeef")
self.assertEqual("iomatex/eva", contract["contract_prefix"])
self.assertEqual("iomatex/eva/$devices/settings/g-box-deadbeef/sub", contract["request_topic"])
def test_cached_unregistered_status_is_reverified_through_mqtt(self):
persisted = itscreen_registration._default_state()
persisted.update({"status": "not_registered", "app_version": "4.410.109"})
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/eva", "contract_version": 1}
)
server_state = {
"host": "rest.eva.iomatex.com",
"registered": True,
"logged": True,
"app_version": "4.410.109",
}
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", return_value=(contract, server_state)) as mqtt_flow:
response = itscreen_registration.get_registration_status()
mqtt_flow.assert_called_once()
self.assertEqual("ready", response["status"])
self.assertTrue(response["registered"])
self.assertTrue(response["logged"])
self.assertEqual("4.410.109", response["app_version"])
def test_registration_store_overrides_stale_legacy_registration_fields(self):
with tempfile.TemporaryDirectory() as directory:
config_path = os.path.join(directory, "it-screen.conf")
registration_path = os.path.join(directory, "registration.ini")
with open(config_path, "w", encoding="utf-8") as config_file:
config_file.write(
"server=\n"
"password=\n"
"isRegistered=false\n"
"isLogged=false\n"
"mqttPrefix=it-screen/eva\n"
"mqttContractVersion=1\n"
)
with open(registration_path, "w", encoding="utf-8") as registration_file:
registration_file.write(
"[registration]\n"
"device_name=g-box-deadbeef\n"
"is_logged=true\n"
"is_registered=true\n"
"password=device-secret\n"
"server=rest.eva.iomatex.com\n"
)
with patch.object(itscreen_registration, "ITSCREEN_CONFIG_PATH", config_path), \
patch.object(itscreen_registration, "REGISTRATION_STORE_PATH", registration_path):
fallback = itscreen_registration._load_registration_from_itscreen_config(
"g-box-deadbeef"
)
self.assertEqual("rest.eva.iomatex.com", fallback["host"])
self.assertTrue(fallback["registered"])
self.assertTrue(fallback["local_registered"])
self.assertTrue(fallback["logged"])
self.assertTrue(fallback["password_present"])
self.assertEqual("it-screen/eva", fallback["mqtt_prefix"])
def test_registered_status_is_verified_through_client_owned_mqtt_flow(self):
persisted = itscreen_registration._default_state()
persisted.update({"status": "ready", "registered": True, "logged": True})
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "iomatex/ae", "contract_version": 1}
)
server_state = {"host": "rest.uae.iomatex.com", "registered": True, "logged": True}
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", return_value=(contract, server_state)) as mqtt_flow:
response = itscreen_registration.get_registration_status()
mqtt_flow.assert_called_once()
self.assertEqual("ready", response["status"])
self.assertTrue(response["registered"])
self.assertTrue(response["logged"])
def test_reset_is_idempotent_when_device_is_already_unregistered(self):
persisted = itscreen_registration._default_state()
persisted.update({"status": "error", "app_version": "4.410.109"})
saved = []
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state", side_effect=saved.append), \
patch.object(itscreen_registration, "_with_settings_contract") as mqtt_flow:
response = itscreen_registration.reset_registration()
mqtt_flow.assert_not_called()
self.assertTrue(response["ok"])
self.assertEqual("not_registered", response["data"]["status"])
self.assertFalse(response["data"]["registered"])
self.assertFalse(response["data"]["logged"])
self.assertEqual("clear", response["data"]["last_event"]["action"])
self.assertEqual("success", response["data"]["last_event"]["status"])
self.assertEqual("not_registered", saved[0]["status"])
def test_reset_stops_after_clear_acknowledgement(self):
persisted = itscreen_registration._default_state()
persisted.update({"status": "ready", "registered": True, "logged": True})
contract = itscreen_registration._build_server_contract_topics(
"g-box-deadbeef", {"prefix": "it-screen/its-docker", "contract_version": 2}
)
class Session:
def login(self, _passwords):
return True
def clear_server_registration(self):
return {"action": "clear", "category": "server", "result": True}
def get_server_state(self):
raise AssertionError("reset must not query an already-cleared client")
session = Session()
def run_flow(_device_id, _persisted, _operation, callback, server_host_hint=""):
return contract, callback(session, contract)
with patch.object(itscreen_registration, "load_state", return_value=persisted), \
patch.object(itscreen_registration, "save_state"), \
patch.object(itscreen_registration, "_with_settings_contract", side_effect=run_flow):
response = itscreen_registration.reset_registration()
self.assertTrue(response["ok"])
self.assertEqual("not_registered", response["data"]["status"])
self.assertFalse(response["data"]["registered"])
def test_registration_wait_correlates_register_and_confirm_operations(self):
with open(itscreen_registration.__file__, encoding="utf-8") as source_file:
method_source = source_file.read()
self.assertIn('wait_registered_event(expected_operation="register")', method_source)
self.assertIn('wait_registered_event(expected_operation="confirm")', method_source)
self.assertIn("if expected_operation and", method_source)
def test_reset_response_is_correlated_by_request_id(self):
with open(itscreen_registration.__file__, encoding="utf-8") as source_file:
method_source = source_file.read()
self.assertIn('request_id = uuid.uuid4().hex', method_source)
self.assertIn('item.get("request_id") == request_id', method_source)
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,41 @@
#!/usr/bin/env python3
import json
import unittest
from unittest.mock import patch
import app
class StorageHealthContractTest(unittest.TestCase):
def test_valid_v1_contract_is_returned(self):
expected = {
"schema_version": 1,
"available": True,
"status": "ok",
"warnings": [],
"emmc": {"available": True, "health_score": 10},
"filesystem": {"mount_point": "/userdata", "status": "ok"},
}
with patch.object(app.os.path, "isfile", return_value=True), \
patch.object(app.os, "access", return_value=True), \
patch.object(app, "run", return_value=(0, json.dumps(expected), "")):
self.assertEqual(expected, app.get_storage_health())
def test_invalid_json_degrades_without_breaking_health_endpoint(self):
with patch.object(app.os.path, "isfile", return_value=True), \
patch.object(app.os, "access", return_value=True), \
patch.object(app, "run", return_value=(0, "not-json", "")):
result = app.get_storage_health()
self.assertFalse(result["available"])
self.assertEqual("unavailable", result["status"])
def test_unknown_schema_degrades_safely(self):
with patch.object(app.os.path, "isfile", return_value=True), \
patch.object(app.os, "access", return_value=True), \
patch.object(app, "run", return_value=(0, '{"schema_version":2}', "")):
result = app.get_storage_health()
self.assertFalse(result["available"])
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,55 @@
#!/usr/bin/env python3
import unittest
from datetime import datetime, timezone
from unittest.mock import patch
import app
class TimezoneContractTest(unittest.TestCase):
def test_list_uses_only_valid_zoneinfo_entries(self):
output = "Europe/Warsaw\nAsia/Dubai\n../etc/passwd\n"
with patch.object(app, "run", return_value=(0, output, "")), \
patch.object(app.os.path, "isfile", return_value=True):
zones = app.list_system_timezones()
self.assertEqual(["Asia/Dubai", "Europe/Warsaw"], zones)
def test_rejects_value_outside_system_list_without_running_set(self):
with patch.object(app, "list_system_timezones", return_value=["Asia/Dubai"]), \
patch.object(app, "run") as command:
with self.assertRaisesRegex(ValueError, "Invalid or unavailable"):
app.set_system_timezone("../../etc/passwd")
command.assert_not_called()
def test_applies_and_verifies_selected_timezone(self):
with patch.object(app, "list_system_timezones", return_value=["Europe/Warsaw"]), \
patch.object(app, "run", return_value=(0, "", "")) as command, \
patch.object(app, "get_system_timezone", return_value="Europe/Warsaw"), \
patch.object(app, "get_timezone_payload", return_value={"ok": True, "timezone": "Europe/Warsaw"}):
payload = app.set_system_timezone("Europe/Warsaw")
self.assertEqual("Europe/Warsaw", payload["timezone"])
command.assert_called_once_with(["timedatectl", "set-timezone", "Europe/Warsaw"], timeout=15)
def test_payload_computes_offset_from_configured_timezone(self):
class FixedDateTime(datetime):
@classmethod
def now(cls, tz=None):
instant = cls(2026, 8, 30, 9, 0, tzinfo=timezone.utc)
return instant.astimezone(tz) if tz is not None else instant
with patch.object(app, "get_system_timezone", return_value="Europe/Warsaw"), \
patch.object(app, "datetime", FixedDateTime):
payload = app.get_timezone_payload(include_available=False)
self.assertEqual("Europe/Warsaw", payload["timezone"])
self.assertEqual("2026-08-30T11:00:00+02:00", payload["local_time"])
self.assertEqual("+0200", payload["utc_offset"])
def test_command_failure_is_reported(self):
with patch.object(app, "list_system_timezones", return_value=["Europe/Warsaw"]), \
patch.object(app, "run", return_value=(1, "", "access denied")):
with self.assertRaisesRegex(RuntimeError, "access denied"):
app.set_system_timezone("Europe/Warsaw")
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,40 @@
#!/usr/bin/env python3
import pathlib
import unittest
FRONTEND_PATH = pathlib.Path(__file__).resolve().parents[1] / "frontend" / "console.js"
class TimezoneUiContractTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.source = FRONTEND_PATH.read_text(encoding="utf-8")
def test_timezone_control_is_searchable(self):
self.assertIn('id="timezoneSearchInput" type="search" role="combobox"', self.source)
self.assertIn('id="timezoneDropdown" class="timezoneDropdown" role="listbox"', self.source)
self.assertIn("window.__timezoneToggle", self.source)
self.assertIn("window.__timezoneChoose", self.source)
self.assertIn("filteredTimezones()", self.source)
self.assertNotIn("<datalist", self.source)
def test_polling_preserves_open_or_edited_control(self):
self.assertIn('onfocus="window.__timezoneFocus(true)"', self.source)
self.assertIn('onblur="window.__timezoneFocus(false)"', self.source)
self.assertIn("!timezone.dirty && !timezone.focused", self.source)
self.assertIn("state.timezone.open", self.source)
self.assertIn("timezoneFormIsInteractive()", self.source)
def test_dropdown_closes_on_outside_click_and_escape(self):
self.assertIn('combobox.contains(event.target)', self.source)
self.assertIn('if (state.timezone.open)', self.source)
self.assertIn('closeTimezoneDropdown(true)', self.source)
def test_only_system_timezone_values_can_be_submitted(self):
self.assertIn("zones.includes(selected)", self.source)
self.assertIn("timezoneValidationError()", self.source)
if __name__ == "__main__":
unittest.main()

View File

@ -400,7 +400,7 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
.meta{display:grid;grid-template-columns:140px 1fr;gap:8px 10px;margin-top:16px;font-size:13px}
.compactMeta{margin-top:0}
.splitMeta{
display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:18px;margin-top:16px;
display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:18px;margin-top:16px;
}
.splitMeta section{min-width:0}
.meta .key{color:var(--muted)}
@ -889,6 +889,40 @@ html[dir="rtl"] .itscreenLogsActions{
.actionBtn.secondary{background:var(--button-secondary);color:var(--ink);border:1px solid var(--line)}
.actionBtn.secondary:hover:not(:disabled){background:var(--button-secondary-hover)}
.actionBtn:disabled{opacity:.5;cursor:not-allowed}
.actionBtn.is-loading{gap:9px;opacity:.82}
.buttonSpinner{
width:17px;height:17px;border:2px solid rgba(255,255,255,.42);border-top-color:#fff;border-radius:50%;
animation:registrationSpin .75s linear infinite;flex:0 0 auto;
}
.registrationProgress{
display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:12px;
min-height:68px;padding:12px 14px;border:1px solid rgba(14,122,83,.24);border-radius:14px;
background:rgba(14,122,83,.08);color:var(--muted);font-size:13px;text-align:left;
}
.registrationProgressSpinner{
width:30px;height:30px;border:3px solid rgba(14,122,83,.22);border-top-color:var(--accent);
border-radius:50%;animation:registrationSpin .75s linear infinite;
}
.registrationProgressCopy{display:grid;gap:3px;line-height:1.35}
.registrationProgressCopy strong{color:var(--ink);font-size:14px}
.registrationProgressCopy span{color:var(--muted)}
.registrationProgressDots{display:inline-flex;align-items:center;gap:4px;height:14px}
@media (max-width:560px){
.registrationProgress{grid-template-columns:auto minmax(0,1fr)}
.registrationProgressDots{display:none}
}
.registrationProgressDots i{
width:6px;height:6px;border-radius:50%;background:var(--accent);animation:registrationDot 1.1s ease-in-out infinite;
}
.registrationProgressDots i:nth-child(2){animation-delay:.14s}
.registrationProgressDots i:nth-child(3){animation-delay:.28s}
@keyframes registrationSpin{to{transform:rotate(360deg)}}
@keyframes registrationDot{0%,60%,100%{opacity:.3;transform:translateY(0)}30%{opacity:1;transform:translateY(-3px)}}
@media (prefers-reduced-motion:reduce){
.buttonSpinner{animation:none;border-color:rgba(255,255,255,.7)}
.registrationProgressSpinner{animation:none}
.registrationProgressDots i{animation:none;opacity:.75}
}
.authScreen{
min-height:min(72vh,720px);
display:flex;
@ -1022,6 +1056,78 @@ html[dir="rtl"] .itscreenLogsActions{
.field select:hover{border-color:var(--line)}
.field input:focus-visible{border-color:var(--accent)}
.field select:focus-visible{border-color:var(--accent)}
.timezoneCombobox{
position:relative;
min-width:0;
}
.timezoneComboboxControl{
display:grid;
grid-template-columns:minmax(0,1fr) 44px;
}
.field .timezoneComboboxControl input{
min-width:0;
border-radius:12px 0 0 12px;
border-right:0;
}
.timezoneDropdownToggle{
display:grid;
place-items:center;
padding:0;
border:1px solid var(--line);
border-radius:0 12px 12px 0;
background:var(--panel);
color:var(--ink);
font-size:18px;
cursor:pointer;
}
.timezoneDropdownToggle:hover,
.timezoneDropdownToggle:focus-visible{
background:var(--surface-soft);
color:var(--ink);
border-color:var(--accent);
}
.timezoneDropdownToggle:disabled{cursor:not-allowed;opacity:.55}
.timezoneDropdown{
position:absolute;
z-index:40;
top:calc(100% + 6px);
left:0;
right:0;
max-height:280px;
overflow:auto;
padding:6px;
border:1px solid var(--line);
border-radius:12px;
background:var(--panel);
box-shadow:0 12px 30px rgba(26,44,38,.18);
}
.timezoneDropdown[hidden]{display:none}
.timezoneOption{
display:block;
width:100%;
padding:9px 10px;
border:0;
border-radius:8px;
background:transparent;
color:var(--ink);
text-align:left;
cursor:pointer;
}
.timezoneOption:hover,
.timezoneOption:focus-visible{
background:var(--surface-soft);
color:var(--ink);
outline:none;
}
.timezoneOption.is-selected{font-weight:700;background:var(--surface-strong)}
.timezoneNoResults{padding:10px;color:var(--muted)}
html[dir="rtl"] .field .timezoneComboboxControl input{
border-radius:0 12px 12px 0;
border-right:1px solid var(--line);
border-left:0;
}
html[dir="rtl"] .timezoneDropdownToggle{border-radius:12px 0 0 12px}
html[dir="rtl"] .timezoneOption{text-align:right}
.numberStepper{
display:grid;
grid-template-columns:minmax(0,1fr) auto;
@ -1177,7 +1283,7 @@ html[dir="rtl"] .itscreenLogsActions{
display:inline-flex;
align-items:center;
gap:8px;
align-self:center;
align-self:end;
padding:10px 12px;
border:1px solid var(--line);
border-radius:12px;
@ -1476,6 +1582,29 @@ html[dir="rtl"] .itscreenLogsActions{
color:var(--muted);
line-height:1.5;
}
.platformDialog{
text-align:center;
padding:28px;
}
.platformDialogIcon{
display:grid;
place-items:center;
width:58px;
height:58px;
margin:0 auto 16px;
border-radius:50%;
background:rgba(217,143,24,.14);
color:#b66f00;
font-size:32px;
font-weight:800;
}
.platformDialog.success .platformDialogIcon{
background:rgba(14,122,83,.14);
color:#0e7a53;
}
.platformDialog .actionRow{
justify-content:center;
}
@keyframes pulse{
0%,100%{opacity:.35;transform:scale(.9)}
50%{opacity:1;transform:scale(1)}

View File

@ -56,6 +56,7 @@
"Inactive": "Неактивно",
"Loading": "Загрузка",
"Registration": "Регистрация",
"Registration in progress": "Выполняется регистрация",
"Ready": "Готово",
"Success": "Успех",
"Available": "Доступно",
@ -328,15 +329,77 @@
"Organization": "Организация",
"Token": "Токен",
"Registered": "Зарегистрировано",
"Remote port": "Удалённый порт",
"Remote connection": "Удалённое соединение",
"Reachable": "Доступно",
"Remote MQTT broker is unreachable": "Удалённый MQTT broker недоступен",
"Remote broker": "Удалённый broker",
"Edge to server": "Edge → сервер",
"Server to Edge": "Сервер → Edge",
"Message delivered": "Сообщение доставлено",
"Message not delivered": "Сообщение не доставлено",
"Outbound latency": "Задержка исходящего сообщения",
"Inbound latency": "Задержка входящего сообщения",
"Outbound topic": "Исходящий topic",
"Inbound topic": "Входящий topic",
"Tested at": "Проверено",
"MQTT Bridge end-to-end test": "Сквозной тест MQTT Bridge",
"Sends one message from Edge to the server and another from the server back to Edge.": "Отправляет одно сообщение с Edge на сервер и другое с сервера обратно на Edge.",
"Test Bridge": "Проверить Bridge",
"Testing MQTT Bridge in both directions...": "Проверяем MQTT Bridge в обоих направлениях...",
"MQTT bridge works in both directions": "MQTT Bridge работает в обоих направлениях",
"MQTT bridge round-trip failed": "Сквозная проверка MQTT Bridge не пройдена",
"Local Mosquitto MQTT": "Локальный Mosquitto MQTT",
"Local broker address": "Адрес локального broker",
"Bridged topic trees": "Деревья topic через Bridge",
"The Test button checks local MQTT first, then completes a correlated round-trip through the remote broker.": "Кнопка Test сначала проверяет локальный MQTT, затем выполняет коррелированный полный круг через удалённый broker.",
"Testing the full MQTT path...": "Проверяем полный путь MQTT...",
"Correlation token": "Токен корреляции",
"Full round-trip latency": "Задержка полного круга",
"The request is published locally, received remotely, answered with the same token, and received again in local MQTT.": "Запрос публикуется локально, принимается удалённо, получает ответ с тем же токеном и снова принимается в локальном MQTT.",
"Run Test in the Local Mosquitto MQTT card to verify the complete path.": "Запустите Test в карточке локального Mosquitto MQTT, чтобы проверить весь путь.",
"Waiting for the correlated response through MQTT Bridge...": "Ожидаем коррелированный ответ через MQTT Bridge...",
"Response was not sent because the server did not receive the request": "Ответ не отправлен, потому что сервер не получил запрос",
"Remote MQTT broker did not receive the request in time": "Удалённый MQTT broker не получил запрос за отведённое время",
"Local MQTT broker did not receive the response in time": "Локальный MQTT broker не получил ответ за отведённое время",
"MQTT diagnostic command failed": "Не удалось выполнить диагностическую команду MQTT",
"Registration incomplete": "Регистрация не завершена",
"Registration is incomplete. The server did not confirm the device login, so no verified server record is available.": "Регистрация не завершена. Сервер не подтвердил вход устройства, поэтому проверенной записи на сервере нет.",
"Logged": "Вход выполнен",
"Password state": "Состояние пароля",
"Password set": "Пароль задан",
"Registration Form": "Форма регистрации",
"Server name": "Имя сервера",
"Custom hostname": "Пользовательский hostname",
"Custom server address": "Произвольный адрес сервера",
"http://127.0.0.1:8000/api": "http://127.0.0.1:8000/api",
"Change registration server": "Изменить сервер регистрации",
"Device is currently registered on {current}. Registration will now be attempted on {target}. The current server record will be preserved and will become active again if you return to it later.": "Устройство сейчас зарегистрировано на {current}. Будет выполнена регистрация на {target}. Запись на текущем сервере сохранится и снова станет активной, если вы вернётесь к нему позже.",
"Device is already registered on the selected server": "Устройство уже зарегистрировано на выбранном сервере",
"Register the device on the newly selected server.": "Зарегистрируйте устройство на новом выбранном сервере.",
"Device successfully registered on {address}.": "Устройство успешно зарегистрировано на {address}.",
"Failed to register device on {address}: {error}": "Не удалось зарегистрировать устройство на {address}: {error}",
"Cancel": "Отмена",
"Continue": "Продолжить",
"Edit server address": "Исправить адрес",
"Go to registration status": "Перейти к статусу регистрации",
"Registration is already active": "Регистрация уже активна",
"This device is already registered on {address}.": "Устройство уже зарегистрировано на {address}.",
"Check the server address": "Проверьте адрес сервера",
"The address {address} is invalid. Correct it and try again.": "Адрес {address} некорректен. Исправьте его и повторите попытку.",
"Registration completed": "Регистрация завершена",
"Registration failed": "Ошибка регистрации",
"MQTT prefix": "Префикс MQTT",
"Contract version": "Версия контракта",
"The Edge contacts the selected server directly, receives device credentials, and then applies the server configuration to It-Screen.": "Edge напрямую обращается к выбранному серверу, получает учётные данные устройства и затем применяет серверную конфигурацию в It-Screen.",
"Server not found": "Сервер не найден",
"Registration server is unavailable": "Сервер регистрации недоступен",
"The server {address} does not exist or its name cannot be resolved. Check the address and try again.": "Сервер {address} не существует или его имя не разрешается. Проверьте адрес и повторите попытку.",
"The server {address} did not respond to the registration request. Check the address or try again later.": "Сервер {address} не ответил на запрос регистрации. Проверьте адрес или повторите попытку позже.",
"The backend sends the final hostname in MQTT set server, always in rest.* form.": "Backend отправляет итоговый hostname в MQTT set server, всегда в формате rest.*.",
"Resolved host: {host}": "Итоговый host: {host}",
"Registering...": "Регистрация...",
"Applying server settings and reconnecting MQTT...": "Применяем настройки сервера и переподключаем MQTT...",
"Register": "Зарегистрировать",
"Reset Cloud Registration": "Сбросить облачную регистрацию",
"Device is already registered": "Устройство уже зарегистрировано",
@ -658,11 +721,68 @@
"Server": "Serwer",
"Server name": "Nazwa serwera",
"Custom hostname": "Własny hostname",
"Custom server address": "Własny adres serwera",
"http://127.0.0.1:8000/api": "http://127.0.0.1:8000/api",
"Change registration server": "Zmień serwer rejestracji",
"Device is currently registered on {current}. Registration will now be attempted on {target}. The current server record will be preserved and will become active again if you return to it later.": "Urządzenie jest obecnie zarejestrowane na {current}. Zostanie podjęta próba rejestracji na {target}. Bieżący wpis serwera zostanie zachowany i ponownie stanie się aktywny po powrocie.",
"Device is already registered on the selected server": "Urządzenie jest już zarejestrowane na wybranym serwerze",
"Register the device on the newly selected server.": "Zarejestruj urządzenie na nowo wybranym serwerze.",
"Device successfully registered on {address}.": "Urządzenie zostało pomyślnie zarejestrowane na {address}.",
"Failed to register device on {address}: {error}": "Nie udało się zarejestrować urządzenia na {address}: {error}",
"Cancel": "Anuluj",
"Continue": "Kontynuuj",
"Edit server address": "Popraw adres",
"Go to registration status": "Przejdź do statusu rejestracji",
"Registration is already active": "Rejestracja jest już aktywna",
"This device is already registered on {address}.": "Urządzenie jest już zarejestrowane na {address}.",
"Check the server address": "Sprawdź adres serwera",
"The address {address} is invalid. Correct it and try again.": "Adres {address} jest nieprawidłowy. Popraw go i spróbuj ponownie.",
"Registration completed": "Rejestracja zakończona",
"Server not found": "Nie znaleziono serwera",
"Registration server is unavailable": "Serwer rejestracji jest niedostępny",
"The server {address} does not exist or its name cannot be resolved. Check the address and try again.": "Serwer {address} nie istnieje lub jego nazwy nie można rozpoznać. Sprawdź adres i spróbuj ponownie.",
"The server {address} did not respond to the registration request. Check the address or try again later.": "Serwer {address} nie odpowiedział na żądanie rejestracji. Sprawdź adres lub spróbuj ponownie później.",
"Device ID": "ID urządzenia",
"Device name": "Nazwa urządzenia",
"Organization": "Organizacja",
"Token": "Token",
"Registered": "Zarejestrowano",
"Remote port": "Port zdalny",
"Remote connection": "Połączenie zdalne",
"Reachable": "Dostępne",
"Remote MQTT broker is unreachable": "Zdalny broker MQTT jest niedostępny",
"Remote broker": "Zdalny broker",
"Edge to server": "Edge → serwer",
"Server to Edge": "Serwer → Edge",
"Message delivered": "Wiadomość dostarczona",
"Message not delivered": "Wiadomość niedostarczona",
"Outbound latency": "Opóźnienie wychodzące",
"Inbound latency": "Opóźnienie przychodzące",
"Outbound topic": "Topic wychodzący",
"Inbound topic": "Topic przychodzący",
"Tested at": "Sprawdzono",
"MQTT Bridge end-to-end test": "Kompleksowy test MQTT Bridge",
"Sends one message from Edge to the server and another from the server back to Edge.": "Wysyła jedną wiadomość z Edge do serwera i drugą z serwera z powrotem do Edge.",
"Test Bridge": "Sprawdź Bridge",
"Testing MQTT Bridge in both directions...": "Sprawdzanie MQTT Bridge w obu kierunkach...",
"MQTT bridge works in both directions": "MQTT Bridge działa w obu kierunkach",
"MQTT bridge round-trip failed": "Kompleksowy test MQTT Bridge nie powiódł się",
"Local Mosquitto MQTT": "Lokalny Mosquitto MQTT",
"Local broker address": "Adres lokalnego brokera",
"Bridged topic trees": "Drzewa topic przez Bridge",
"The Test button checks local MQTT first, then completes a correlated round-trip through the remote broker.": "Przycisk Test najpierw sprawdza lokalny MQTT, a następnie wykonuje skorelowany pełny obieg przez zdalny broker.",
"Testing the full MQTT path...": "Sprawdzanie pełnej ścieżki MQTT...",
"Correlation token": "Token korelacji",
"Full round-trip latency": "Opóźnienie pełnego obiegu",
"The request is published locally, received remotely, answered with the same token, and received again in local MQTT.": "Żądanie jest publikowane lokalnie, odbierane zdalnie, otrzymuje odpowiedź z tym samym tokenem i wraca do lokalnego MQTT.",
"Run Test in the Local Mosquitto MQTT card to verify the complete path.": "Uruchom Test na karcie lokalnego Mosquitto MQTT, aby sprawdzić całą ścieżkę.",
"Waiting for the correlated response through MQTT Bridge...": "Oczekiwanie na skorelowaną odpowiedź przez MQTT Bridge...",
"Response was not sent because the server did not receive the request": "Odpowiedź nie została wysłana, ponieważ serwer nie otrzymał żądania",
"Remote MQTT broker did not receive the request in time": "Zdalny broker MQTT nie otrzymał żądania w wyznaczonym czasie",
"Local MQTT broker did not receive the response in time": "Lokalny broker MQTT nie otrzymał odpowiedzi w wyznaczonym czasie",
"MQTT diagnostic command failed": "Nie udało się wykonać polecenia diagnostycznego MQTT",
"Registration incomplete": "Rejestracja nie została zakończona",
"Registration is incomplete. The server did not confirm the device login, so no verified server record is available.": "Rejestracja nie została zakończona. Serwer nie potwierdził logowania urządzenia, dlatego brak zweryfikowanego wpisu na serwerze.",
"Logged": "Zalogowano",
"Password state": "Stan hasła",
"Password set": "Hasło ustawione",
@ -670,6 +790,7 @@
"The backend sends the final hostname in MQTT set server, always in rest.* form.": "Backend wysyła końcowy hostname w MQTT set server, zawsze w formacie rest.*.",
"Resolved host: {host}": "Docelowy host: {host}",
"Registering...": "Rejestrowanie...",
"Applying server settings and reconnecting MQTT...": "Stosowanie ustawień serwera i ponowne łączenie z MQTT...",
"Register": "Zarejestruj",
"Reset Cloud Registration": "Zresetuj rejestrację chmurową",
"Device is already registered": "Urządzenie jest już zarejestrowane",
@ -961,6 +1082,42 @@
"Organization": "المؤسسة",
"Token": "الرمز",
"Registered": "تم التسجيل",
"Remote port": "المنفذ البعيد",
"Remote connection": "الاتصال البعيد",
"Reachable": "متاح",
"Remote MQTT broker is unreachable": "وسيط MQTT البعيد غير متاح",
"Remote broker": "وسيط بعيد",
"Edge to server": "Edge → الخادم",
"Server to Edge": "الخادم → Edge",
"Message delivered": "تم تسليم الرسالة",
"Message not delivered": "لم يتم تسليم الرسالة",
"Outbound latency": "زمن الاستجابة الصادر",
"Inbound latency": "زمن الاستجابة الوارد",
"Outbound topic": "الموضوع الصادر",
"Inbound topic": "الموضوع الوارد",
"Tested at": "وقت الاختبار",
"MQTT Bridge end-to-end test": "اختبار MQTT Bridge من طرف إلى طرف",
"Sends one message from Edge to the server and another from the server back to Edge.": "يرسل رسالة من Edge إلى الخادم ورسالة أخرى من الخادم إلى Edge.",
"Test Bridge": "اختبار Bridge",
"Testing MQTT Bridge in both directions...": "جارٍ اختبار MQTT Bridge في كلا الاتجاهين...",
"MQTT bridge works in both directions": "يعمل MQTT Bridge في كلا الاتجاهين",
"MQTT bridge round-trip failed": "فشل اختبار MQTT Bridge من طرف إلى طرف",
"Local Mosquitto MQTT": "Mosquitto MQTT المحلي",
"Local broker address": "عنوان الوسيط المحلي",
"Bridged topic trees": "أشجار الموضوعات عبر Bridge",
"The Test button checks local MQTT first, then completes a correlated round-trip through the remote broker.": "يتحقق زر Test أولاً من MQTT المحلي، ثم ينفذ دورة مترابطة كاملة عبر الوسيط البعيد.",
"Testing the full MQTT path...": "جارٍ اختبار مسار MQTT الكامل...",
"Correlation token": "رمز الترابط",
"Full round-trip latency": "زمن الدورة الكاملة",
"The request is published locally, received remotely, answered with the same token, and received again in local MQTT.": "يُنشر الطلب محليًا، ويُستلم عن بُعد، ويُجاب عنه بالرمز نفسه، ثم يُستلم مجددًا في MQTT المحلي.",
"Run Test in the Local Mosquitto MQTT card to verify the complete path.": "شغّل Test في بطاقة Mosquitto MQTT المحلي للتحقق من المسار الكامل.",
"Waiting for the correlated response through MQTT Bridge...": "في انتظار الرد المترابط عبر MQTT Bridge...",
"Response was not sent because the server did not receive the request": "لم يُرسل الرد لأن الخادم لم يستلم الطلب",
"Remote MQTT broker did not receive the request in time": "لم يستلم وسيط MQTT البعيد الطلب في الوقت المحدد",
"Local MQTT broker did not receive the response in time": "لم يستلم وسيط MQTT المحلي الرد في الوقت المحدد",
"MQTT diagnostic command failed": "تعذر تنفيذ أمر تشخيص MQTT",
"Registration incomplete": "لم يكتمل التسجيل",
"Registration is incomplete. The server did not confirm the device login, so no verified server record is available.": "لم يكتمل التسجيل. لم يؤكد الخادم تسجيل دخول الجهاز، لذلك لا يوجد سجل خادم تم التحقق منه.",
"Logged": "تم تسجيل الدخول",
"Password state": "حالة كلمة المرور",
"Password set": "تم تعيين كلمة المرور",
@ -1133,9 +1290,31 @@
,"Unit": "الوحدة"
,"Server name": "اسم الخادم"
,"Custom hostname": "اسم مضيف مخصص"
,"Custom server address": "عنوان خادم مخصص"
,"http://127.0.0.1:8000/api": "http://127.0.0.1:8000/api"
,"Change registration server": "تغيير خادم التسجيل"
,"Device is currently registered on {current}. Registration will now be attempted on {target}. The current server record will be preserved and will become active again if you return to it later.": "الجهاز مسجل حاليًا على {current}. ستتم محاولة التسجيل على {target}. سيُحفظ سجل الخادم الحالي ويصبح نشطًا مجددًا عند العودة إليه لاحقًا."
,"Device is already registered on the selected server": "الجهاز مسجل بالفعل على الخادم المحدد"
,"Register the device on the newly selected server.": "سجل الجهاز على الخادم المحدد حديثًا."
,"Device successfully registered on {address}.": "تم تسجيل الجهاز بنجاح على {address}."
,"Failed to register device on {address}: {error}": "تعذر تسجيل الجهاز على {address}: {error}"
,"Cancel": "إلغاء"
,"Continue": "متابعة"
,"Edit server address": "تصحيح العنوان"
,"Go to registration status": "الانتقال إلى حالة التسجيل"
,"Registration is already active": "التسجيل نشط بالفعل"
,"This device is already registered on {address}.": "الجهاز مسجل بالفعل على {address}."
,"Check the server address": "تحقق من عنوان الخادم"
,"The address {address} is invalid. Correct it and try again.": "العنوان {address} غير صالح. صححه وحاول مرة أخرى."
,"Registration completed": "اكتمل التسجيل"
,"Server not found": "لم يتم العثور على الخادم"
,"Registration server is unavailable": "خادم التسجيل غير متاح"
,"The server {address} does not exist or its name cannot be resolved. Check the address and try again.": "الخادم {address} غير موجود أو تعذر حل اسمه. تحقق من العنوان وحاول مرة أخرى."
,"The server {address} did not respond to the registration request. Check the address or try again later.": "لم يستجب الخادم {address} لطلب التسجيل. تحقق من العنوان أو حاول مرة أخرى لاحقًا."
,"The backend sends the final hostname in MQTT set server, always in rest.* form.": "يرسل الـ backend اسم المضيف النهائي في MQTT set server دائماً بصيغة rest.*."
,"Resolved host: {host}": "المضيف النهائي: {host}"
,"Registering...": "جارٍ التسجيل..."
,"Applying server settings and reconnecting MQTT...": "جارٍ تطبيق إعدادات الخادم وإعادة الاتصال بـ MQTT..."
,"Register": "تسجيل"
,"Reset Cloud Registration": "إعادة تعيين التسجيل السحابي"
,"Device is already registered": "الجهاز مسجل بالفعل"
@ -1444,6 +1623,42 @@
"Organization": "संगठन",
"Token": "Token",
"Registered": "पंजीकृत",
"Remote port": "रिमोट पोर्ट",
"Remote connection": "रिमोट कनेक्शन",
"Reachable": "उपलब्ध",
"Remote MQTT broker is unreachable": "रिमोट MQTT ब्रोकर उपलब्ध नहीं है",
"Remote broker": "रिमोट ब्रोकर",
"Edge to server": "Edge → सर्वर",
"Server to Edge": "सर्वर → Edge",
"Message delivered": "संदेश पहुँच गया",
"Message not delivered": "संदेश नहीं पहुँचा",
"Outbound latency": "आउटबाउंड विलंब",
"Inbound latency": "इनबाउंड विलंब",
"Outbound topic": "आउटबाउंड टॉपिक",
"Inbound topic": "इनबाउंड टॉपिक",
"Tested at": "परीक्षण समय",
"MQTT Bridge end-to-end test": "MQTT Bridge एंड-टू-एंड परीक्षण",
"Sends one message from Edge to the server and another from the server back to Edge.": "एक संदेश Edge से सर्वर और दूसरा सर्वर से वापस Edge पर भेजता है।",
"Test Bridge": "Bridge जाँचें",
"Testing MQTT Bridge in both directions...": "दोनों दिशाओं में MQTT Bridge की जाँच हो रही है...",
"MQTT bridge works in both directions": "MQTT Bridge दोनों दिशाओं में काम करता है",
"MQTT bridge round-trip failed": "MQTT Bridge एंड-टू-एंड परीक्षण विफल हुआ",
"Local Mosquitto MQTT": "लोकल Mosquitto MQTT",
"Local broker address": "लोकल ब्रोकर पता",
"Bridged topic trees": "Bridge किए गए टॉपिक ट्री",
"The Test button checks local MQTT first, then completes a correlated round-trip through the remote broker.": "Test बटन पहले लोकल MQTT जाँचता है, फिर रिमोट ब्रोकर के जरिए संबद्ध पूरा चक्र चलाता है।",
"Testing the full MQTT path...": "पूरे MQTT पथ की जाँच हो रही है...",
"Correlation token": "सहसंबंध टोकन",
"Full round-trip latency": "पूर्ण चक्र विलंब",
"The request is published locally, received remotely, answered with the same token, and received again in local MQTT.": "अनुरोध लोकल रूप से प्रकाशित होता है, रिमोट पर मिलता है, उसी टोकन से उत्तर दिया जाता है और फिर लोकल MQTT में मिलता है।",
"Run Test in the Local Mosquitto MQTT card to verify the complete path.": "पूरा पथ जाँचने के लिए लोकल Mosquitto MQTT कार्ड में Test चलाएँ।",
"Waiting for the correlated response through MQTT Bridge...": "MQTT Bridge से संबद्ध उत्तर की प्रतीक्षा हो रही है...",
"Response was not sent because the server did not receive the request": "उत्तर नहीं भेजा गया क्योंकि सर्वर को अनुरोध नहीं मिला",
"Remote MQTT broker did not receive the request in time": "रिमोट MQTT ब्रोकर को निर्धारित समय में अनुरोध नहीं मिला",
"Local MQTT broker did not receive the response in time": "लोकल MQTT ब्रोकर को निर्धारित समय में उत्तर नहीं मिला",
"MQTT diagnostic command failed": "MQTT डायग्नोस्टिक कमांड नहीं चल सकी",
"Registration incomplete": "पंजीकरण पूरा नहीं हुआ",
"Registration is incomplete. The server did not confirm the device login, so no verified server record is available.": "पंजीकरण पूरा नहीं हुआ। सर्वर ने डिवाइस लॉगिन की पुष्टि नहीं की, इसलिए कोई सत्यापित सर्वर रिकॉर्ड उपलब्ध नहीं है।",
"Logged": "लॉगिन",
"Logged in": "लॉगिन है",
"Not logged in": "लॉगिन नहीं है",
@ -1456,9 +1671,31 @@
"Unit": "यूनिट",
"Server name": "सर्वर नाम",
"Custom hostname": "कस्टम hostname",
"Custom server address": "कस्टम सर्वर पता",
"http://127.0.0.1:8000/api": "http://127.0.0.1:8000/api",
"Change registration server": "रजिस्ट्रेशन सर्वर बदलें",
"Device is currently registered on {current}. Registration will now be attempted on {target}. The current server record will be preserved and will become active again if you return to it later.": "डिवाइस अभी {current} पर पंजीकृत है। अब {target} पर पंजीकरण का प्रयास होगा। मौजूदा सर्वर रिकॉर्ड सुरक्षित रहेगा और बाद में लौटने पर फिर सक्रिय होगा।",
"Device is already registered on the selected server": "डिवाइस चुने गए सर्वर पर पहले से पंजीकृत है",
"Register the device on the newly selected server.": "डिवाइस को नए चुने गए सर्वर पर पंजीकृत करें।",
"Device successfully registered on {address}.": "डिवाइस {address} पर सफलतापूर्वक पंजीकृत हुआ।",
"Failed to register device on {address}: {error}": "डिवाइस को {address} पर पंजीकृत नहीं किया जा सका: {error}",
"Cancel": "रद्द करें",
"Continue": "जारी रखें",
"Edit server address": "सर्वर पता सुधारें",
"Go to registration status": "पंजीकरण स्थिति पर जाएँ",
"Registration is already active": "पंजीकरण पहले से सक्रिय है",
"This device is already registered on {address}.": "यह डिवाइस पहले से {address} पर पंजीकृत है।",
"Check the server address": "सर्वर पता जाँचें",
"The address {address} is invalid. Correct it and try again.": "पता {address} अमान्य है। इसे सुधारें और फिर प्रयास करें।",
"Registration completed": "पंजीकरण पूरा हुआ",
"Server not found": "सर्वर नहीं मिला",
"Registration server is unavailable": "पंजीकरण सर्वर उपलब्ध नहीं है",
"The server {address} does not exist or its name cannot be resolved. Check the address and try again.": "सर्वर {address} मौजूद नहीं है या उसका नाम resolve नहीं हो सका। पता जाँचें और फिर प्रयास करें।",
"The server {address} did not respond to the registration request. Check the address or try again later.": "सर्वर {address} ने पंजीकरण अनुरोध का उत्तर नहीं दिया। पता जाँचें या बाद में फिर प्रयास करें।",
"The backend sends the final hostname in MQTT set server, always in rest.* form.": "Backend MQTT set server में अंतिम hostname हमेशा rest.* रूप में भेजता है।",
"Resolved host: {host}": "Resolved host: {host}",
"Registering...": "पंजीकरण हो रहा है...",
"Applying server settings and reconnecting MQTT...": "सर्वर सेटिंग लागू की जा रही हैं और MQTT फिर से कनेक्ट हो रहा है...",
"Register": "पंजीकरण करें",
"Reset Cloud Registration": "क्लाउड पंजीकरण रीसेट करें",
"Device is already registered": "डिवाइस पहले से पंजीकृत है",
@ -1633,4 +1870,125 @@
}
}
};
Object.assign(window.ConsoleI18n.translations.ru, {
"Security & Region": "Безопасность и регион",
"WEB UI account security, recovery, and regional time settings.": "Безопасность учётной записи WEB UI, восстановление доступа и региональные настройки времени.",
"Region and time zone": "Регион и часовой пояс",
"Select the local time zone used by the operating system and It-Screen.": "Выберите локальный часовой пояс, используемый операционной системой и It-Screen.",
"Current time zone": "Текущий часовой пояс",
"Local device time": "Локальное время устройства",
"UTC offset": "Смещение UTC",
"Time zone": "Часовой пояс",
"Search by city or region": "Поиск по городу или региону",
"Select a time zone from the list": "Выберите часовой пояс из списка",
"Open time zone list": "Открыть список часовых поясов",
"No matching time zones": "Подходящие часовые пояса не найдены",
"Apply time zone": "Применить часовой пояс",
"The change applies immediately and does not require a reboot.": "Изменение применяется сразу и не требует перезагрузки.",
"System time zone changed successfully": "Системный часовой пояс успешно изменён",
"Failed to change system time zone": "Не удалось изменить системный часовой пояс",
"Storage": "Накопитель",
"Storage status": "Общее состояние накопителя",
"eMMC health": "Состояние eMMC",
"Estimated wear": "Оценочный износ",
"Lifetime filesystem writes": "Записано файловой системой за всё время",
"Manufactured": "Дата производства",
"/userdata filesystem": "Файловая система /userdata",
"Filesystem errors": "Ошибки файловой системы",
"Journal": "Журнал",
"Attention required": "Требует внимания",
"Critical": "Критическое",
"Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles.": "Износ — приблизительная оценка JEDEC. Эта eMMC не сообщает точные часы работы или число циклов записи."
});
Object.assign(window.ConsoleI18n.translations.pl, {
"Security & Region": "Bezpieczeństwo i region",
"WEB UI account security, recovery, and regional time settings.": "Bezpieczeństwo konta WEB UI, odzyskiwanie dostępu i regionalne ustawienia czasu.",
"Region and time zone": "Region i strefa czasowa",
"Select the local time zone used by the operating system and It-Screen.": "Wybierz lokalną strefę czasową używaną przez system operacyjny i It-Screen.",
"Current time zone": "Bieżąca strefa czasowa",
"Local device time": "Lokalny czas urządzenia",
"UTC offset": "Przesunięcie UTC",
"Time zone": "Strefa czasowa",
"Search by city or region": "Szukaj według miasta lub regionu",
"Select a time zone from the list": "Wybierz strefę czasową z listy",
"Open time zone list": "Otwórz listę stref czasowych",
"No matching time zones": "Nie znaleziono pasujących stref czasowych",
"Apply time zone": "Zastosuj strefę czasową",
"The change applies immediately and does not require a reboot.": "Zmiana jest stosowana natychmiast i nie wymaga ponownego uruchomienia.",
"System time zone changed successfully": "Systemowa strefa czasowa została zmieniona",
"Failed to change system time zone": "Nie udało się zmienić systemowej strefy czasowej",
"Storage": "Pamięć masowa",
"Storage status": "Ogólny stan pamięci",
"eMMC health": "Stan eMMC",
"Estimated wear": "Szacowane zużycie",
"Lifetime filesystem writes": "Całkowity zapis systemu plików",
"Manufactured": "Data produkcji",
"/userdata filesystem": "System plików /userdata",
"Filesystem errors": "Błędy systemu plików",
"Journal": "Dziennik",
"Attention required": "Wymaga uwagi",
"Critical": "Krytyczny",
"Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles.": "Zużycie jest przybliżonym oszacowaniem JEDEC. Ta pamięć eMMC nie udostępnia dokładnych godzin pracy ani liczby cykli zapisu."
});
Object.assign(window.ConsoleI18n.translations.ar, {
"Security & Region": "الأمان والمنطقة",
"WEB UI account security, recovery, and regional time settings.": "أمان حساب واجهة الويب واستعادة الوصول وإعدادات الوقت الإقليمية.",
"Region and time zone": "المنطقة والمنطقة الزمنية",
"Select the local time zone used by the operating system and It-Screen.": "اختر المنطقة الزمنية المحلية التي يستخدمها نظام التشغيل وIt-Screen.",
"Current time zone": "المنطقة الزمنية الحالية",
"Local device time": "الوقت المحلي للجهاز",
"UTC offset": "إزاحة UTC",
"Time zone": "المنطقة الزمنية",
"Search by city or region": "البحث حسب المدينة أو المنطقة",
"Select a time zone from the list": "اختر منطقة زمنية من القائمة",
"Open time zone list": "فتح قائمة المناطق الزمنية",
"No matching time zones": "لم يتم العثور على مناطق زمنية مطابقة",
"Apply time zone": "تطبيق المنطقة الزمنية",
"The change applies immediately and does not require a reboot.": "يُطبق التغيير فورًا ولا يتطلب إعادة التشغيل.",
"System time zone changed successfully": "تم تغيير المنطقة الزمنية للنظام بنجاح",
"Failed to change system time zone": "تعذر تغيير المنطقة الزمنية للنظام",
"Storage": "التخزين",
"Storage status": "حالة التخزين العامة",
"eMMC health": "حالة eMMC",
"Estimated wear": "التآكل التقديري",
"Lifetime filesystem writes": "إجمالي كتابات نظام الملفات",
"Manufactured": "تاريخ التصنيع",
"/userdata filesystem": "نظام ملفات /userdata",
"Filesystem errors": "أخطاء نظام الملفات",
"Journal": "السجل",
"Attention required": "يتطلب الانتباه",
"Critical": "حرج",
"Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles.": "التآكل تقدير JEDEC تقريبي. لا تعرض ذاكرة eMMC هذه ساعات التشغيل الدقيقة أو عدد دورات الكتابة."
});
Object.assign(window.ConsoleI18n.translations.hi, {
"Security & Region": "सुरक्षा और क्षेत्र",
"WEB UI account security, recovery, and regional time settings.": "WEB UI खाता सुरक्षा, पहुँच पुनर्प्राप्ति और क्षेत्रीय समय सेटिंग्स।",
"Region and time zone": "क्षेत्र और समय क्षेत्र",
"Select the local time zone used by the operating system and It-Screen.": "ऑपरेटिंग सिस्टम और It-Screen द्वारा उपयोग किया जाने वाला स्थानीय समय क्षेत्र चुनें।",
"Current time zone": "वर्तमान समय क्षेत्र",
"Local device time": "डिवाइस का स्थानीय समय",
"UTC offset": "UTC ऑफ़सेट",
"Time zone": "समय क्षेत्र",
"Search by city or region": "शहर या क्षेत्र के अनुसार खोजें",
"Select a time zone from the list": "सूची से समय क्षेत्र चुनें",
"Open time zone list": "समय क्षेत्रों की सूची खोलें",
"No matching time zones": "कोई मेल खाता समय क्षेत्र नहीं मिला",
"Apply time zone": "समय क्षेत्र लागू करें",
"The change applies immediately and does not require a reboot.": "बदलाव तुरंत लागू होता है और रीबूट की आवश्यकता नहीं होती।",
"System time zone changed successfully": "सिस्टम समय क्षेत्र सफलतापूर्वक बदल गया",
"Failed to change system time zone": "सिस्टम समय क्षेत्र बदलना विफल रहा",
"Storage": "स्टोरेज",
"Storage status": "कुल स्टोरेज स्थिति",
"eMMC health": "eMMC स्थिति",
"Estimated wear": "अनुमानित घिसाव",
"Lifetime filesystem writes": "कुल फ़ाइल सिस्टम लेखन",
"Manufactured": "निर्माण तिथि",
"/userdata filesystem": "/userdata फ़ाइल सिस्टम",
"Filesystem errors": "फ़ाइल सिस्टम त्रुटियाँ",
"Journal": "जर्नल",
"Attention required": "ध्यान आवश्यक",
"Critical": "गंभीर",
"Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles.": "घिसाव एक मोटा JEDEC अनुमान है। यह eMMC सटीक चालू घंटे या लेखन चक्र नहीं बताती।"
});
})();

View File

@ -42,13 +42,13 @@
};
const ITSCREEN_SERVER_OPTIONS = [
{ mode: "dev", label: "DEV", host: "rest.dev.it-screen.com" },
{ mode: "uae", label: "UAE", host: "rest.uae.iomatex.com" },
{ mode: "public_by", label: "PUBLIC BY", host: "rest.public.it-screen.by" },
{ mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
{ mode: "dev", label: "dev.it-screen.com", host: "rest.dev.it-screen.com" },
{ mode: "uae", label: "uae.iomatex.com", host: "rest.uae.iomatex.com" },
{ mode: "public_by", label: "public.it-screen.by", host: "rest.public.it-screen.by" },
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" }
];
const UI_VERSION = "V 2.2.46";
const UI_VERSION = "V 2.2.78";
const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250;
@ -176,6 +176,7 @@
serverMode: "uae",
customHost: "",
customToken: "",
serverSelectionDirty: false,
focused: false,
loadedAt: 0,
request: null,
@ -314,6 +315,18 @@
showNewPassword: false,
showConfirmPassword: false
},
timezone: {
data: null,
selected: "",
busy: false,
dirty: false,
focused: false,
open: false,
query: "",
error: "",
message: "",
request: null
},
menuOpen: false,
rebootPending: false,
isPolling: false
@ -452,7 +465,7 @@
title: { en: "It-Screen Registration Form Guide", ru: "Руководство по форме регистрации It-Screen", pl: "Przewodnik po formularzu rejestracji It-Screen", ar: "دليل نموذج تسجيل It-Screen", hi: "It-Screen रजिस्ट्रेशन फॉर्म गाइड" },
body: [
{ en: "Use this form to bind the device to a selected It-Screen cloud environment.", ru: "Используйте эту форму, чтобы привязать устройство к выбранному облачному окружению It-Screen.", pl: "Użyj tego formularza, aby powiązać urządzenie z wybranym środowiskiem chmurowym It-Screen.", ar: "استخدم هذا النموذج لربط الجهاز ببيئة It-Screen السحابية المحددة.", hi: "इस फॉर्म का उपयोग डिवाइस को चुने गए It-Screen cloud environment से बाँधने के लिए करें।" },
{ en: "Server name selects the target backend. Custom hostname is for non-standard deployments only. Registration token is optional and should be used only when your cloud setup requires it.", ru: "Server name выбирает целевой backend. Custom hostname нужен только для нестандартных развёртываний. Registration token необязателен и используется только если этого требует ваше облачное окружение.", pl: "Server name wybiera docelowy backend. Custom hostname służy tylko do niestandardowych wdrożeń. Registration token jest opcjonalny i należy go używać tylko wtedy, gdy wymaga tego dane środowisko chmurowe.", ar: "يحدد Server name الواجهة الخلفية المستهدفة. ويُستخدم Custom hostname فقط في البيئات غير القياسية. أما Registration token فهو اختياري ويُستخدم فقط عندما تتطلبه بيئتكم السحابية.", hi: "Server name target backend चुनता है। Custom hostname केवल non-standard deployments के लिए है। Registration token optional है और तभी उपयोग करें जब आपका cloud setup इसकी मांग करे।" },
{ en: "Server name selects the target backend. Custom accepts a hostname, IP address, optional port, or a full HTTP/HTTPS base URL. Registration token is optional and should be used only when your server requires it.", ru: "Server name выбирает целевой backend. Custom принимает hostname, IP-адрес, необязательный порт или полный базовый HTTP/HTTPS URL. Registration token необязателен и используется только если этого требует ваш сервер.", pl: "Server name wybiera docelowy backend. Custom przyjmuje hostname, adres IP, opcjonalny port lub pełny bazowy URL HTTP/HTTPS. Token rejestracyjny jest opcjonalny i należy go używać tylko wtedy, gdy wymaga go serwer.", ar: "يحدد Server name الواجهة الخلفية المستهدفة. يقبل Custom اسم مضيف أو عنوان IP أو منفذاً اختيارياً أو عنوان HTTP/HTTPS أساسياً كاملاً. رمز التسجيل اختياري ويُستخدم فقط عندما يطلبه الخادم.", hi: "Server name target backend चुनता है। Custom hostname, IP address, optional port या पूरा HTTP/HTTPS base URL स्वीकार करता है। Registration token optional है और केवल server की आवश्यकता पर उपयोग होता है।" },
{ en: "Register starts a fresh headless registration flow. Reset Cloud Registration clears the cached registration state so the device can be registered again.", ru: "Register запускает новую headless-регистрацию. Reset Cloud Registration очищает кэшированное состояние регистрации, чтобы устройство можно было зарегистрировать заново.", pl: "Register uruchamia nowy bezgłowy proces rejestracji. Reset Cloud Registration czyści zapisany stan rejestracji, aby można było zarejestrować urządzenie ponownie.", ar: "يبدأ Register عملية تسجيل جديدة بدون واجهة. أما Reset Cloud Registration فيمسح حالة التسجيل المخزنة مؤقتاً حتى يمكن تسجيل الجهاز من جديد.", hi: "Register एक नया headless registration flow शुरू करता है। Reset Cloud Registration cached registration state साफ करता है ताकि डिवाइस को फिर से register किया जा सके।" }
]
},
@ -798,7 +811,7 @@
if (nodes.rebootMenuLabel) nodes.rebootMenuLabel.textContent = t("Reboot");
if (nodes.logoutMenuLabel) nodes.logoutMenuLabel.textContent = t("Logout");
if (nodes.tabHealth) nodes.tabHealth.textContent = t("Health");
if (nodes.tabSecurity) nodes.tabSecurity.textContent = t("Security");
if (nodes.tabSecurity) nodes.tabSecurity.textContent = t("Security & Region");
if (nodes.tabNetwork) nodes.tabNetwork.textContent = t("Network");
if (nodes.tabModbus) nodes.tabModbus.textContent = t("Modbus");
if (nodes.tabTscreen) nodes.tabTscreen.textContent = t("It-Screen");
@ -1011,6 +1024,62 @@
}, 3600);
}
function platformDialog({ tone = "warn", title, message, primaryLabel, secondaryLabel = "" }) {
return new Promise((resolve) => {
const backdrop = document.createElement("div");
backdrop.className = "modalBackdrop";
backdrop.innerHTML = `
<div class="modalCard platformDialog ${esc(tone)}" role="dialog" aria-modal="true" aria-label="${esc(title)}">
<div class="platformDialogIcon" aria-hidden="true">${tone === "success" ? "✓" : "!"}</div>
<h3>${esc(title)}</h3>
<p>${esc(message)}</p>
<div class="actionRow">
${secondaryLabel ? `<button class="actionBtn secondary" type="button" data-dialog-secondary>${esc(secondaryLabel)}</button>` : ""}
<button class="actionBtn" type="button" data-dialog-primary>${esc(primaryLabel)}</button>
</div>
</div>
`;
const finish = (result) => {
document.removeEventListener("keydown", onKeydown);
backdrop.remove();
resolve(result);
};
const onKeydown = (event) => {
if (event.key === "Escape") finish(false);
};
backdrop.addEventListener("click", (event) => {
if (event.target === backdrop) finish(false);
});
const secondaryButton = backdrop.querySelector("[data-dialog-secondary]");
if (secondaryButton) secondaryButton.addEventListener("click", () => finish(false));
backdrop.querySelector("[data-dialog-primary]").addEventListener("click", () => finish(true));
document.addEventListener("keydown", onKeydown);
document.body.appendChild(backdrop);
backdrop.querySelector("[data-dialog-primary]").focus();
});
}
function confirmAction(title, message, continueLabel = t("Continue")) {
return platformDialog({
tone: "warn",
title,
message,
primaryLabel: continueLabel,
secondaryLabel: t("Cancel")
});
}
async function showRegistrationWarning(title, message) {
await platformDialog({ tone: "warn", title, message, primaryLabel: t("Edit server address") });
window.setTimeout(() => {
const input = document.getElementById("itscreenCustomHost");
if (input) {
input.focus();
input.select();
}
}, 0);
}
async function copyTextToClipboard(text) {
const value = textValue(text, "");
if (!value) throw new Error(t("Nothing to copy"));
@ -1306,11 +1375,20 @@
}
function normalizeItscreenHostCandidate(value) {
const raw = textValue(value, "").trim().toLowerCase();
const raw = textValue(value, "").trim();
if (!raw) return "";
if (raw.includes("://") || raw.includes("/") || /\s/.test(raw)) return raw;
if (raw.endsWith(".")) return raw.slice(0, -1);
return raw.startsWith("rest.") ? raw : `rest.${raw}`;
const trimmed = raw.endsWith("/") ? raw.slice(0, -1) : raw;
try {
const hasScheme = trimmed.includes("://");
const parsed = new URL(hasScheme ? trimmed : `https://${trimmed}`);
const hostname = parsed.hostname.toLowerCase();
const isIpAddress = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname) || hostname.includes(":");
if (hostname === "localhost" || isIpAddress || hostname.startsWith("rest.")) return trimmed;
parsed.hostname = `rest.${hostname}`;
return hasScheme ? parsed.toString().replace(/\/$/, "") : `${parsed.host}${parsed.pathname === "/" ? "" : parsed.pathname}`;
} catch (_) {
return trimmed;
}
}
function itscreenPayload() {
@ -1347,10 +1425,14 @@
}
function itscreenHostValidationError() {
const host = itscreenResolvedHost().trim().toLowerCase();
if (!host) return t("Invalid server host");
if (host.includes("://") || host.includes("/") || /\s/.test(host)) return t("Invalid server host");
if (!/^(?=.{1,253}$)(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.(?!-)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/.test(host)) {
const address = itscreenResolvedHost().trim();
if (!address || /\s/.test(address)) return t("Invalid server host");
try {
const parsed = new URL(address.includes("://") ? address : `https://${address}`);
if (!["http:", "https:"].includes(parsed.protocol) || !parsed.hostname || parsed.username || parsed.password || parsed.search || parsed.hash) {
return t("Invalid server host");
}
} catch (_) {
return t("Invalid server host");
}
return "";
@ -1360,6 +1442,7 @@
if (!payload) return { label: t("Loading"), tone: "warn" };
if (state.itscreen.busyAction === "register") return { label: t("Registering..."), tone: "warn" };
if (payload.status === "error" || state.itscreen.error) return { label: t("Error"), tone: "error" };
if (payload.status === "incomplete" || (payload.local_registered && !payload.logged)) return { label: t("Registration incomplete"), tone: "warn" };
if (payload.registered) return { label: t("Registered"), tone: "ok" };
return { label: t("Not registered"), tone: "warn" };
}
@ -1390,16 +1473,11 @@
function itscreenContractLabel(payload) {
const contract = textValue(payload && payload.contract_prefix, "");
if (contract === "it-screen") return "it-screen/$devices/settings";
if (contract === "iomatex") return "iomatex/$devices/settings";
if (contract === "universal") return "$devices/settings";
return t("Not specified");
return contract ? `${contract}/$devices/settings` : t("Not specified");
}
function itscreenMaskedPassword(payload) {
const password = textValue(payload && payload.password, "");
if (!password) return t("Not specified");
return "******";
return payload && payload.password_present ? "******" : t("Not specified");
}
function itscreenResponseDetails() {
@ -1492,8 +1570,13 @@
function itscreenCanRegister(registration) {
if (state.itscreen.busyAction || state.itscreen.loading) return false;
if (!!(registration && registration.registered)) return false;
return !itscreenHostValidationError();
if (itscreenHostValidationError()) return false;
if (!(registration && registration.registered)) return true;
return comparableServerAddress(itscreenResolvedHost()) !== comparableServerAddress(registration.server || registration.host);
}
function comparableServerAddress(value) {
return normalizeItscreenHostCandidate(value).toLowerCase();
}
function formatItscreenAppVersion(value) {
@ -1522,6 +1605,7 @@
const tone = statusTone(card);
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
const errors = Array.isArray(card.errors) ? card.errors : [];
const registrationIncomplete = !!(payload && payload.local_registered && !payload.logged);
const registrationRequired = !!(payload && !payload.registered && !state.itscreen.error);
return `
@ -1541,7 +1625,7 @@
${state.itscreen.loading && !payload ? `<div class="emptyInline">${esc(t("Loading It-screen status..."))}</div>` : `
<div class="list">
<div class="listTitle">${esc(t("Registration"))}</div>
${registrationRequired ? `<div class="banner warn">${esc(t("Registration required. Device is not bound to cloud."))}</div>` : ""}
${registrationIncomplete ? `<div class="banner warn">${esc(t("Registration is incomplete. The server did not confirm the device login, so no verified server record is available."))}</div>` : (registrationRequired ? `<div class="banner warn">${esc(t("Registration required. Device is not bound to cloud."))}</div>` : "")}
<div class="meta compactMeta ${registrationRequired ? "registrationWarnGrid" : ""}">${renderItscreenInfoRows(payload || {}, card && card.version)}</div>
</div>
`}
@ -1567,7 +1651,46 @@
return `${token.slice(0, 10)}…${token.slice(-6)}`;
}
function renderHealthOverviewPanel(metrics, runtimeRows, temps) {
function emmcHealthLabel(value) {
const labels = {
excellent: t("Excellent"),
good: t("Good"),
attention: t("Attention required"),
critical: t("Critical"),
unknown: t("Unknown")
};
return labels[textValue(value, "unknown").toLowerCase()] || t("Unknown");
}
function storageHealthRows(storage) {
const emmc = (storage && storage.emmc) || {};
const filesystem = (storage && storage.filesystem) || {};
if (!storage || !storage.available || !emmc.available) {
return [{ label: t("eMMC health"), value: t("Not available") }];
}
const hasScore = emmc.health_score !== null && emmc.health_score !== undefined && emmc.health_score !== "" && Number.isFinite(Number(emmc.health_score));
const hasWearMin = emmc.wear_percent_min !== null && emmc.wear_percent_min !== undefined && emmc.wear_percent_min !== "" && Number.isFinite(Number(emmc.wear_percent_min));
const hasWearMax = emmc.wear_percent_max !== null && emmc.wear_percent_max !== undefined && emmc.wear_percent_max !== "" && Number.isFinite(Number(emmc.wear_percent_max));
const score = hasScore ? `${Number(emmc.health_score)}/${Number(emmc.health_score_max) || 10}` : t("Unknown");
const wearMin = hasWearMin ? Number(emmc.wear_percent_min) : null;
const wearMax = hasWearMax ? Number(emmc.wear_percent_max) : null;
const wear = wearMin === null ? t("Unknown") : (wearMax === null ? `${wearMin}%+` : `${wearMin}–${wearMax}%`);
const journal = filesystem.journal_enabled === true ? t("Enabled") : (filesystem.journal_enabled === false ? t("Disabled") : t("Unknown"));
const rows = [
{ label: t("Storage status"), value: emmcHealthLabel(storage.status) },
{ label: t("eMMC health"), value: `${score} · ${emmcHealthLabel(emmc.health_label)}` },
{ label: t("Estimated wear"), value: wear },
{ label: t("Lifetime filesystem writes"), value: textValue(filesystem.lifetime_writes, t("Not available")) },
{ label: t("Manufactured"), value: textValue(emmc.manufactured_at, t("Not available")) },
{ label: t("/userdata filesystem"), value: `${textValue(filesystem.state, t("Unknown"))} · ${t("Journal")}: ${journal}` }
];
if (filesystem.error_count !== null && filesystem.error_count !== undefined) {
rows.push({ label: t("Filesystem errors"), value: String(filesystem.error_count) });
}
return rows;
}
function renderHealthOverviewPanel(metrics, runtimeRows, temps, storage) {
const thermalRows = temps.length
? temps.map((item) => ({ label: item.name, value: translateStatusValue(item.label) || t("Not available") }))
: [{ label: t("Sensors"), value: t("Not available") }];
@ -1592,6 +1715,11 @@
<div class="listTitle">${esc(t("Thermals"))}</div>
<div class="meta compactMeta">${renderKeyValueRows(thermalRows)}</div>
</section>
<section>
<div class="listTitle">${esc(t("Storage"))}</div>
<div class="meta compactMeta">${renderKeyValueRows(storageHealthRows(storage))}</div>
<div class="metricHint">${esc(t("Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles."))}</div>
</section>
</div>
</article>
`;
@ -2012,7 +2140,8 @@
function renderMqttSelfTestPanel() {
const selfTest = state.mqttSelfTest || {};
const result = selfTest.result || {};
const overall = selfTest.result || {};
const result = overall.local || {};
const hasResult = !!result.status || !!selfTest.error;
const tone = result.status === "ok" ? "success" : "error";
const rows = result.status ? [
@ -2028,17 +2157,54 @@
<div class="mqttSelfTestHead">
<div>
<div class="listTitle">${esc(t("Local MQTT publish/read test"))}</div>
<div class="metricHint">${esc(t("Publishes an obvious test message to the local broker and reads it back."))}</div>
<div class="metricHint">${esc(t("The Test button checks local MQTT first, then completes a correlated round-trip through the remote broker."))}</div>
</div>
<button class="actionBtn secondary" type="button" ${selfTest.loading ? "disabled" : ""} onclick="window.__runMqttSelfTest()">${esc(selfTest.loading ? t("Testing...") : t("Test"))}</button>
</div>
${selfTest.loading ? `<div class="banner warn">${esc(t("Publishing and reading a local MQTT test message..."))}</div>` : ""}
${selfTest.loading ? `<div class="banner warn">${esc(t("Testing the full MQTT path..."))}</div>` : ""}
${hasResult && !selfTest.loading ? `<div class="banner ${tone}">${esc(result.status === "ok" ? t("Test message was published and received") : (selfTest.error || result.error || result.status_text || t("MQTT self-test failed")))}</div>` : ""}
${rows.length ? `<div class="meta compactMeta mqttSelfTestMeta">${renderKeyValueRows(rows)}</div>` : ""}
</div>
`;
}
function renderMqttBridgeTestPanel() {
const selfTest = state.mqttSelfTest || {};
const overall = selfTest.result || {};
const result = overall.bridge || {};
const outbound = result.outbound || {};
const inbound = result.inbound || {};
const hasResult = !!result.status || !!selfTest.error;
const tone = result.status === "ok" ? "success" : "error";
const rows = result.status ? [
{ label: t("Remote broker"), value: result.remote_host ? `${result.remote_host}:${result.remote_port || 1883}` : t("Not available") },
{ label: t("Edge to server"), value: outbound.ok ? t("Message delivered") : t("Message not delivered") },
{ label: t("Outbound latency"), value: outbound.latency_ms === null || outbound.latency_ms === undefined ? t("Not available") : `${outbound.latency_ms} ms` },
{ label: t("Outbound topic"), value: textValue(outbound.topic, t("Not available")) },
{ label: t("Server to Edge"), value: inbound.ok ? t("Message delivered") : t("Message not delivered") },
{ label: t("Inbound latency"), value: inbound.latency_ms === null || inbound.latency_ms === undefined ? t("Not available") : `${inbound.latency_ms} ms` },
{ label: t("Inbound topic"), value: textValue(inbound.topic, t("Not available")) },
{ label: t("Correlation token"), value: textValue(result.correlation_token, t("Not available")) },
{ label: t("Full round-trip latency"), value: result.round_trip_latency_ms === null || result.round_trip_latency_ms === undefined ? t("Not available") : `${result.round_trip_latency_ms} ms` },
{ label: t("Tested at"), value: formatUtc(result.tested_at) }
] : [];
const detailError = outbound.error || inbound.error || selfTest.error || result.status_text || t("MQTT bridge round-trip failed");
return `
<div class="list mqttSelfTestPanel">
<div class="mqttSelfTestHead">
<div>
<div class="listTitle">${esc(t("MQTT Bridge end-to-end test"))}</div>
<div class="metricHint">${esc(t("The request is published locally, received remotely, answered with the same token, and received again in local MQTT."))}</div>
</div>
</div>
${!selfTest.loading && !result.status ? `<div class="formHint">${esc(t("Run Test in the Local Mosquitto MQTT card to verify the complete path."))}</div>` : ""}
${selfTest.loading ? `<div class="banner warn">${esc(t("Waiting for the correlated response through MQTT Bridge..."))}</div>` : ""}
${hasResult && !selfTest.loading ? `<div class="banner ${tone}">${esc(result.status === "ok" ? t("MQTT bridge works in both directions") : translateUiText(detailError))}</div>` : ""}
${rows.length ? `<div class="meta compactMeta mqttSelfTestMeta">${renderKeyValueRows(rows)}</div>` : ""}
</div>
`;
}
function renderServiceCard(card) {
if (card.id === "itscreen") return renderItscreenServiceCard(card);
if (card.id === "display") return renderDisplayCard(card);
@ -2050,9 +2216,8 @@
const errors = Array.isArray(card.errors) ? card.errors : [];
const details = Array.isArray(card.details) ? card.details : [];
const mqttSelfTest = state.mqttSelfTest || {};
const mqttSelfTestResult = mqttSelfTest.result || {};
const showMqttSelfTest = card.id === "mosquitto";
const showMqttBridgeSelfTestResult = card.id === "mqtt_bridge" && mqttSelfTestResult.status === "ok";
const showMqttBridgeTest = card.id === "mqtt_bridge";
return `
<article class="panel card serviceCard">
@ -2069,7 +2234,7 @@
</div>
${details.length ? `<div class="list"><div class="listTitle">${esc(t("Details"))}</div><div class="meta compactMeta">${renderKeyValueRows(details)}</div></div>` : ""}
${showMqttSelfTest ? renderMqttSelfTestPanel() : ""}
${showMqttBridgeSelfTestResult ? renderMqttSelfTestSummary("MQTT broker test") : ""}
${showMqttBridgeTest ? renderMqttBridgeTestPanel() : ""}
<div class="list">
<div class="listTitle">${esc(t("Flags"))}</div>
<div class="pillRow">
@ -2154,16 +2319,126 @@
`;
}
function renderTimezonePanel() {
const timezone = state.timezone;
const data = timezone.data || {};
const zones = Array.isArray(data.available_timezones) ? data.available_timezones : [];
const selected = timezone.selected || textValue(data.timezone, "");
const localTime = textValue(data.local_time, t("Not available")).replace("T", " ");
const offset = textValue(data.utc_offset, t("Not available"));
const validationError = timezoneValidationError(selected);
const filteredZones = filteredTimezones();
return `
<article class="panel card">
<div class="cardTop">
<div>
${renderPanelTitle(t("Region and time zone"), "panel_generic", t("Select the local time zone used by the operating system and It-Screen."))}
</div>
</div>
<div class="meta compactMeta">
<div class="key">${esc(t("Current time zone"))}</div><div>${esc(textValue(data.timezone, t("Not available")))}</div>
<div class="key">${esc(t("Local device time"))}</div><div>${esc(localTime)}</div>
<div class="key">${esc(t("UTC offset"))}</div><div>${esc(offset)}</div>
</div>
<form class="accountPasswordForm" onsubmit="window.__timezoneSubmit(event)">
<label class="field">
<span>${esc(t("Time zone"))}</span>
<div id="timezoneCombobox" class="timezoneCombobox">
<div class="timezoneComboboxControl">
<input id="timezoneSearchInput" type="search" role="combobox" aria-autocomplete="list" aria-controls="timezoneDropdown" aria-expanded="${timezone.open ? "true" : "false"}" value="${esc(selected)}" autocomplete="off" spellcheck="false" placeholder="${esc(t("Search by city or region"))}" oninput="window.__timezoneInput(this.value)" onfocus="window.__timezoneFocus(true)" onblur="window.__timezoneFocus(false)" onclick="window.__timezoneOpen()" onkeydown="window.__timezoneInputKeydown(event)" ${timezone.busy || !zones.length ? "disabled" : ""}>
<button class="timezoneDropdownToggle" type="button" aria-label="${esc(t("Open time zone list"))}" aria-expanded="${timezone.open ? "true" : "false"}" onclick="window.__timezoneToggle(event)" ${timezone.busy || !zones.length ? "disabled" : ""}>▾</button>
</div>
<div id="timezoneDropdown" class="timezoneDropdown" role="listbox" ${timezone.open ? "" : "hidden"}>${renderTimezoneOptions(filteredZones, selected)}</div>
</div>
</label>
<div id="timezoneValidationError" class="formError" ${validationError ? "" : "hidden"}>${esc(validationError)}</div>
<div class="formHint">${esc(t("The change applies immediately and does not require a reboot."))}</div>
${timezone.message ? `<div class="banner success">${esc(timezone.message)}</div>` : ""}
${timezone.error ? `<div class="banner error">${esc(timezone.error)}</div>` : ""}
<div class="actionRow">
<button id="timezoneApplyButton" class="actionBtn" type="submit" ${timezone.busy || !zones.length || !!validationError || selected === data.timezone ? "disabled" : ""}>${esc(timezone.busy ? t("Applying...") : t("Apply time zone"))}</button>
</div>
</form>
</article>
`;
}
function filteredTimezones() {
const zones = Array.isArray(state.timezone.data && state.timezone.data.available_timezones) ? state.timezone.data.available_timezones : [];
const query = textValue(state.timezone.query, "").trim().toLocaleLowerCase();
if (!query) return zones;
const startsWith = [];
const contains = [];
zones.forEach((zone) => {
const normalized = zone.toLocaleLowerCase();
if (normalized.startsWith(query)) startsWith.push(zone);
else if (normalized.includes(query)) contains.push(zone);
});
return startsWith.concat(contains);
}
function renderTimezoneOptions(zones, selected) {
if (!zones.length) return `<div class="timezoneNoResults">${esc(t("No matching time zones"))}</div>`;
return zones.map((zone) => `<button class="timezoneOption${zone === selected ? " is-selected" : ""}" type="button" role="option" aria-selected="${zone === selected ? "true" : "false"}" data-zone="${esc(zone)}" onclick="window.__timezoneChoose(this.dataset.zone)" onkeydown="window.__timezoneOptionKeydown(event)">${esc(zone)}</button>`).join("");
}
function timezoneValidationError(value = state.timezone.selected) {
const selected = textValue(value, "");
const zones = Array.isArray(state.timezone.data && state.timezone.data.available_timezones) ? state.timezone.data.available_timezones : [];
if (!selected || !zones.includes(selected)) return t("Select a time zone from the list");
return "";
}
function timezoneFormIsInteractive() {
return !!(state.timezone.focused || state.timezone.open || state.timezone.dirty || state.timezone.busy);
}
function updateTimezoneDropdownUi() {
const timezone = state.timezone;
const input = document.getElementById("timezoneSearchInput");
const toggle = document.querySelector(".timezoneDropdownToggle");
const dropdown = document.getElementById("timezoneDropdown");
if (input) input.setAttribute("aria-expanded", timezone.open ? "true" : "false");
if (toggle) toggle.setAttribute("aria-expanded", timezone.open ? "true" : "false");
if (!dropdown) return;
dropdown.hidden = !timezone.open;
dropdown.innerHTML = renderTimezoneOptions(filteredTimezones(), timezone.selected);
}
function closeTimezoneDropdown(restoreFocus = false) {
state.timezone.open = false;
updateTimezoneDropdownUi();
if (restoreFocus) {
const input = document.getElementById("timezoneSearchInput");
if (input) input.focus();
}
}
function updateTimezoneFormUi() {
if (state.activeTab !== "security") return;
const error = timezoneValidationError();
const errorNode = document.getElementById("timezoneValidationError");
const applyButton = document.getElementById("timezoneApplyButton");
if (errorNode) {
errorNode.textContent = error;
errorNode.hidden = !error;
}
if (applyButton) {
applyButton.disabled = !!(state.timezone.busy || error || state.timezone.selected === textValue(state.timezone.data && state.timezone.data.timezone, ""));
}
}
function renderSecurityTab() {
return `
<section class="tabPanel">
<div class="sectionHead">
<div class="panelTitleRow"><h2>${esc(t("Security"))}</h2>${renderHelpButton("panel_generic")}</div>
<p>${esc(t("WEB UI account password management and recovery steps."))}</p>
<div class="panelTitleRow"><h2>${esc(t("Security & Region"))}</h2>${renderHelpButton("panel_generic")}</div>
<p>${esc(t("WEB UI account security, recovery, and regional time settings."))}</p>
</div>
<div class="cards">
${renderAccountSecurityPanel()}
${renderPasswordRecoveryPanel()}
${renderTimezonePanel()}
</div>
</section>
`;
@ -2204,7 +2479,7 @@
return `
<section class="tabPanel">
<div class="cards">
${renderHealthOverviewPanel(metrics, runtimeRows, temps)}
${renderHealthOverviewPanel(metrics, runtimeRows, temps, health.storage || null)}
</div>
<div class="sectionHead">
@ -2467,7 +2742,10 @@
const capabilities = (service && service.capabilities) || {};
const canStartService = !!((typeof capabilities.can_start === "boolean" ? capabilities.can_start : (service.installed && service.status !== "running")) && !serviceBusy);
const canStopService = !!((typeof capabilities.can_stop === "boolean" ? capabilities.can_stop : (service.installed && service.status !== "stopped" && service.status !== "not_installed")) && !serviceBusy);
const registerHelper = payload && payload.registered ? t("Device is already registered") : (hostError || t("Select the target cloud server and start registration."));
const selectedServerDiffers = payload && payload.registered && comparableServerAddress(serverHost) !== comparableServerAddress(payload.server || payload.host);
const registerHelper = payload && payload.registered && !selectedServerDiffers
? t("Device is already registered on the selected server")
: (hostError || (selectedServerDiffers ? t("Register the device on the newly selected server.") : t("Select the target cloud server and start registration.")));
const serviceWarnings = Array.isArray(service && service.warnings) ? service.warnings : [];
const serviceErrors = Array.isArray(service && service.errors) ? service.errors : [];
const registrationRequired = !!(payload && !payload.registered && !state.itscreen.error);
@ -2505,7 +2783,7 @@
${service && service.status === "not_installed" ? `<div class="formHint">${esc(t("It-screen service is not installed on this device."))}</div>` : ""}
</article>
<article class="panel card">
<article id="itscreenRegistrationStatus" class="panel card">
<div class="cardTop">
<div>
${renderPanelTitle(t("Cloud Registration Status"), "itscreen_cloud_status")}
@ -2525,6 +2803,8 @@
<div class="key">${esc(t("Organization"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.organization))}</div>
<div class="key">${esc(t("Token"))}</div><div class="wrapValue" title="${esc(notSpecified(payload && payload.token))}">${esc(compactToken(payload && payload.token))}</div>
<div class="key">${esc(t("Detected contract"))}</div><div>${esc(itscreenContractLabel(payload))}</div>
<div class="key">${esc(t("MQTT prefix"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.mqtt_prefix))}</div>
<div class="key">${esc(t("Contract version"))}</div><div>${esc(payload && payload.contract_version ? `v${payload.contract_version}` : t("Not specified"))}</div>
<div class="key">${esc(t("Request topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.request_topic))}</div>
<div class="key">${esc(t("Response topic"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.response_topic))}</div>
<div class="${registrationWarnKeyClass}">${esc(t("Registered"))}</div><div class="${registrationWarnClass}">${esc(itscreenBooleanLabel(!!(payload && payload.registered), "registered"))}</div>
@ -2543,21 +2823,31 @@
</label>
${state.itscreen.serverMode === "custom" ? `
<label class="field">
<span>${esc(t("Custom hostname"))}</span>
<input id="itscreenCustomHost" type="text" value="${esc(state.itscreen.customHost)}" oninput="window.__setItscreenCustomHost(this.value)" onfocus="window.__setItscreenFocus(true)" onblur="window.__setItscreenFocus(false)" placeholder="${esc(t("rest.custom.example.com"))}">
<span>${esc(t("Custom server address"))}</span>
<input id="itscreenCustomHost" type="text" value="${esc(state.itscreen.customHost)}" oninput="window.__setItscreenCustomHost(this.value)" onfocus="window.__setItscreenFocus(true)" onblur="window.__setItscreenFocus(false)" placeholder="${esc(t("http://127.0.0.1:8000/api"))}">
</label>
` : ""}
<label class="field">
<span>${esc(t("Registration token (optional)"))}</span>
<input id="itscreenCustomToken" type="text" value="${esc(state.itscreen.customToken)}" oninput="window.__setItscreenCustomToken(this.value)" placeholder="${esc(t("Paste organization token if required"))}">
</label>
<div class="formHint">${esc(t("The backend passes the initial registration payload to itscreen through local MQTT and runs the same headless registration flow as Registration.qml."))}</div>
<div class="formHint">${esc(t("The Edge contacts the selected server directly, receives device credentials, and then applies the server configuration to It-Screen."))}</div>
<div id="itscreenResolvedHost" class="formHint">${esc(t("Resolved host: {host}", { host: serverHost }))}</div>
<div id="itscreenHostError" class="formError" ${hostError ? "" : "hidden"}>${esc(hostError)}</div>
<div class="actionColumn">
<button id="itscreenRegisterBtn" class="actionBtn" type="button" ${canRegister ? "" : "disabled"} onclick="window.__itscreenRegister()">${esc(busy === "register" ? t("Registering...") : t("Register"))}</button>
<button id="itscreenRegisterBtn" class="actionBtn ${busy === "register" ? "is-loading" : ""}" type="button" ${canRegister ? "" : "disabled"} aria-busy="${busy === "register" ? "true" : "false"}" onclick="window.__itscreenRegister()">${busy === "register" ? `<span class="buttonSpinner" aria-hidden="true"></span><span>${esc(t("Registering..."))}</span>` : esc(t("Register"))}</button>
<button class="actionBtn secondary" type="button" ${busy === "register" ? "disabled" : ""} onclick="window.__itscreenReset()">${esc(busy === "reset" ? t("Resetting...") : t("Reset Cloud Registration"))}</button>
</div>
${busy === "register" ? `
<div class="registrationProgress" role="status" aria-live="polite" aria-atomic="true">
<span class="registrationProgressSpinner" aria-hidden="true"></span>
<span class="registrationProgressCopy">
<strong>${esc(t("Registration in progress"))}</strong>
<span>${esc(t("Applying server settings and reconnecting MQTT..."))}</span>
</span>
<span class="registrationProgressDots" aria-hidden="true"><i></i><i></i><i></i></span>
</div>
` : ""}
<div class="formHint">${esc(registerHelper)}</div>
<div class="formHint">${esc(t("Reset clears the local registration cache and allows a fresh registration attempt."))}</div>
</article>
@ -4237,10 +4527,15 @@
if (String(url || "").indexOf("/api/auth/login") !== 0) {
setAuthRequired(t("Session expired, please sign in again"));
}
throw new Error(payload.error || t("Session expired, please sign in again"));
const error = new Error(payload.error || t("Session expired, please sign in again"));
error.code = payload.code || "unauthorized";
throw error;
}
if (!response.ok || payload.ok === false) {
throw new Error(payload.error || `HTTP ${response.status}`);
const error = new Error(payload.error || `HTTP ${response.status}`);
error.code = payload.code || "request_failed";
error.status = response.status;
throw error;
}
return payload;
}
@ -4305,6 +4600,22 @@
}
}
async function loadTimezone() {
const timezone = state.timezone;
if (timezone.request) return timezone.request;
timezone.request = (async () => {
const payload = await fetchJson("/api/system/timezone", { cache: "no-store" });
timezone.data = payload;
if (!timezone.dirty && !timezone.focused) timezone.selected = textValue(payload.timezone, "");
return payload;
})();
try {
return await timezone.request;
} finally {
timezone.request = null;
}
}
async function loadNetwork() {
if (state.networkRequest) return state.networkRequest;
state.networkRequest = (async () => {
@ -4368,7 +4679,7 @@
function syncItscreenFormFromBackend() {
const payload = itscreenRegistration();
const host = textValue(payload.server, textValue(payload.host, ""));
if (!state.itscreen.focused && !state.itscreen.busyAction && host && host !== t("Not specified")) {
if (!state.itscreen.focused && !state.itscreen.serverSelectionDirty && !state.itscreen.busyAction && host && host !== t("Not specified")) {
state.itscreen.serverMode = itscreenServerMode(host);
if (state.itscreen.serverMode === "custom") {
state.itscreen.customHost = textValue(host, "");
@ -4376,9 +4687,6 @@
state.itscreen.customHost = textValue(host, "");
}
}
if (!state.itscreen.busyAction) {
state.itscreen.customToken = itscreenTokenInputValue(payload && payload.token);
}
}
async function requestItscreenStatus() {
@ -4582,6 +4890,8 @@
try {
if (state.activeTab === "health") {
await Promise.all([loadHealth(), loadItscreenInitialData()]);
} else if (state.activeTab === "security") {
await loadTimezone();
} else if (state.activeTab === "network") {
await loadNetwork();
} else if (state.activeTab === "modbus") {
@ -4591,10 +4901,12 @@
} else {
await loadStatus();
}
if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive())) {
if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive()) && !(preserveEditing && state.activeTab === "security" && timezoneFormIsInteractive())) {
renderActiveTab();
} else if (state.activeTab === "network") {
updateNetworkFormUi();
} else if (state.activeTab === "security") {
updateTimezoneFormUi();
}
} catch (error) {
nodes.content.innerHTML = `<div class="empty">${esc(t("Failed to load {tab}: {message}", { tab: state.activeTab, message: error.message || String(error) }))}</div>`;
@ -4966,17 +5278,22 @@
};
window.__setItscreenServerMode = function (mode) {
const previousMode = state.itscreen.serverMode;
state.itscreen.serverMode = mode;
if (mode !== "custom" && state.activeTab === "tscreen") renderActiveTab();
state.itscreen.serverSelectionDirty = true;
if (mode !== previousMode) {
state.itscreen.customToken = "";
}
if (mode === "custom" && !state.itscreen.customHost && itscreenRegistration()) {
const payload = itscreenRegistration();
state.itscreen.customHost = textValue(payload.server, textValue(payload.host, ""));
if (state.activeTab === "tscreen") renderActiveTab();
}
if (state.activeTab === "tscreen") renderActiveTab();
};
window.__setItscreenCustomHost = function (value) {
state.itscreen.customHost = value;
state.itscreen.serverSelectionDirty = true;
const error = itscreenHostValidationError();
const errorNode = document.getElementById("itscreenHostError");
const resolvedNode = document.getElementById("itscreenResolvedHost");
@ -5011,27 +5328,52 @@
};
window.__itscreenRegister = async function () {
if (state.itscreen.busyAction) return;
const registration = itscreenRegistration();
if (registration && registration.registered) {
state.itscreen.error = t("Device is already registered");
const targetAddress = itscreenResolvedHost();
const currentAddress = textValue(registration && (registration.server || registration.host), "");
const changingServer = !!(registration && registration.registered && comparableServerAddress(targetAddress) !== comparableServerAddress(currentAddress));
if (registration && registration.registered && !changingServer) {
state.itscreen.error = t("Device is already registered on the selected server");
if (state.activeTab === "tscreen") renderActiveTab();
await platformDialog({
tone: "warn",
title: t("Registration is already active"),
message: t("This device is already registered on {address}.", { address: targetAddress }),
primaryLabel: t("Go to registration status")
});
const statusCard = document.getElementById("itscreenRegistrationStatus");
if (statusCard) statusCard.scrollIntoView({ behavior: "smooth", block: "center" });
return;
}
const validationError = itscreenHostValidationError();
if (validationError) {
state.itscreen.error = validationError;
if (state.activeTab === "tscreen") renderActiveTab();
await showRegistrationWarning(
t("Check the server address"),
t("The address {address} is invalid. Correct it and try again.", { address: targetAddress || t("Not specified") })
);
return;
}
if (changingServer) {
const confirmed = await confirmAction(
t("Change registration server"),
t("Device is currently registered on {current}. Registration will now be attempted on {target}. The current server record will be preserved and will become active again if you return to it later.", { current: currentAddress, target: targetAddress }),
t("Continue")
);
if (!confirmed) return;
}
state.itscreen.error = "";
state.itscreen.busyAction = "register";
if (state.activeTab === "tscreen") renderActiveTab();
await new Promise((resolve) => window.requestAnimationFrame(() => window.requestAnimationFrame(resolve)));
try {
const payload = await fetchJson("/api/itscreen/register", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ host: itscreenResolvedHost(), token: itscreenTokenInputValue(state.itscreen.customToken) })
body: JSON.stringify({ host: targetAddress, token: itscreenTokenInputValue(state.itscreen.customToken) })
});
const nextData = state.itscreen.data || {};
const registration = payload.data || itscreenRegistration();
@ -5039,11 +5381,32 @@
const appVersion = itscreenAppVersionFromRegistration(registration);
if (appVersion) nextService.version = appVersion;
state.itscreen.data = { ...nextData, registration, service: nextService };
state.itscreen.serverSelectionDirty = false;
syncItscreenFormFromBackend();
showToast("success", translateUiText(payload.message || t("Device successfully registered in cloud.")));
const alreadyActive = payload.status === "already_active";
const completionMessage = alreadyActive
? t("This device is already registered on {address}.", { address: targetAddress })
: t("Device successfully registered on {address}.", { address: targetAddress });
showToast(alreadyActive ? "info" : "success", completionMessage);
await platformDialog({
tone: alreadyActive ? "info" : "success",
title: alreadyActive ? t("Registration is already active") : t("Registration completed"),
message: completionMessage,
primaryLabel: t("Go to registration status")
});
const statusCard = document.getElementById("itscreenRegistrationStatus");
if (statusCard) statusCard.scrollIntoView({ behavior: "smooth", block: "center" });
} catch (error) {
state.itscreen.error = error.message || t("Cloud registration failed");
state.itscreen.error = t("Failed to register device on {address}: {error}", { address: targetAddress, error: error.message || t("Cloud registration failed") });
showToast("error", state.itscreen.error);
const errorMessage = String(error.message || t("Cloud registration failed"));
const cannotResolve = errorMessage.includes("hostname could not be resolved");
await showRegistrationWarning(
cannotResolve ? t("Server not found") : t("Registration failed"),
cannotResolve
? t("The server {address} does not exist or its name cannot be resolved. Check the address and try again.", { address: targetAddress })
: errorMessage
);
} finally {
state.itscreen.busyAction = "";
await loadItscreenInitialData({ force: true, maxAgeMs: 0 });
@ -5098,6 +5461,7 @@
const appVersion = itscreenAppVersionFromRegistration(registration);
if (appVersion) nextService.version = appVersion;
state.itscreen.data = { ...nextData, registration, service: nextService };
state.itscreen.serverSelectionDirty = false;
syncItscreenFormFromBackend();
showToast(payload.warning ? "warn" : "success", translateUiText(payload.warning || payload.message || t("Cloud registration has been reset.")));
} catch (error) {
@ -5788,7 +6152,118 @@
account.busy = false;
account.error = translateUiText(error.message || t("Password change failed"));
} finally {
if (state.activeTab === "health") renderActiveTab();
if (state.activeTab === "security") renderActiveTab();
}
};
window.__timezoneInput = function (value) {
state.timezone.selected = textValue(value, "");
state.timezone.query = state.timezone.selected;
state.timezone.open = true;
state.timezone.dirty = state.timezone.selected !== textValue(state.timezone.data && state.timezone.data.timezone, "");
state.timezone.error = "";
state.timezone.message = "";
updateTimezoneFormUi();
updateTimezoneDropdownUi();
};
window.__timezoneFocus = function (focused) {
state.timezone.focused = !!focused;
};
window.__timezoneOpen = function () {
state.timezone.open = true;
state.timezone.query = "";
updateTimezoneDropdownUi();
};
window.__timezoneToggle = function (event) {
if (event && typeof event.preventDefault === "function") event.preventDefault();
state.timezone.open = !state.timezone.open;
state.timezone.query = "";
updateTimezoneDropdownUi();
if (state.timezone.open) {
const input = document.getElementById("timezoneSearchInput");
if (input) input.focus();
}
};
window.__timezoneChoose = function (zone) {
state.timezone.selected = textValue(zone, "");
state.timezone.query = "";
state.timezone.dirty = state.timezone.selected !== textValue(state.timezone.data && state.timezone.data.timezone, "");
state.timezone.error = "";
state.timezone.message = "";
const input = document.getElementById("timezoneSearchInput");
if (input) input.value = state.timezone.selected;
closeTimezoneDropdown(true);
updateTimezoneFormUi();
};
window.__timezoneInputKeydown = function (event) {
if (!event) return;
if (event.key === "ArrowDown") {
event.preventDefault();
state.timezone.open = true;
updateTimezoneDropdownUi();
const firstOption = document.querySelector("#timezoneDropdown .timezoneOption");
if (firstOption) firstOption.focus();
} else if (event.key === "Escape" && state.timezone.open) {
event.preventDefault();
event.stopPropagation();
closeTimezoneDropdown(true);
}
};
window.__timezoneOptionKeydown = function (event) {
if (!event) return;
const options = Array.from(document.querySelectorAll("#timezoneDropdown .timezoneOption"));
const index = options.indexOf(event.currentTarget);
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!options.length) return;
const delta = event.key === "ArrowDown" ? 1 : -1;
options[(index + delta + options.length) % options.length].focus();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
closeTimezoneDropdown(true);
}
};
window.__timezoneSubmit = async function (event) {
if (event && typeof event.preventDefault === "function") event.preventDefault();
const timezone = state.timezone;
if (timezone.busy || !timezone.selected) return;
const validationError = timezoneValidationError();
if (validationError) {
timezone.error = validationError;
updateTimezoneFormUi();
return;
}
timezone.busy = true;
timezone.open = false;
timezone.query = "";
timezone.error = "";
timezone.message = "";
if (state.activeTab === "security") renderActiveTab();
try {
const payload = await fetchJson("/api/system/timezone", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ timezone: timezone.selected })
});
timezone.data = payload;
timezone.selected = textValue(payload.timezone, timezone.selected);
timezone.dirty = false;
timezone.message = translateUiText(payload.message || t("System time zone changed successfully"));
showToast("success", timezone.message);
} catch (error) {
timezone.error = translateUiText(error.message || t("Failed to change system time zone"));
} finally {
timezone.busy = false;
if (state.activeTab === "security") renderActiveTab();
}
};
@ -5905,20 +6380,30 @@
}
document.addEventListener("click", (event) => {
if (!state.menuOpen) return;
if (state.menuOpen) {
const menu = nodes.actionMenu;
const toggle = nodes.menuToggleBtn;
if (!menu || !toggle) {
closeActionMenu();
return;
}
} else {
const target = event.target;
if (menu.contains(target) || toggle.contains(target)) return;
closeActionMenu();
if (!menu.contains(target) && !toggle.contains(target)) closeActionMenu();
}
}
if (state.timezone.open) {
const combobox = document.getElementById("timezoneCombobox");
if (!combobox || !combobox.contains(event.target)) closeTimezoneDropdown();
}
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") closeActionMenu();
if (event.key !== "Escape") return;
if (state.timezone.open) {
event.preventDefault();
closeTimezoneDropdown(true);
return;
}
closeActionMenu();
});
document.addEventListener("visibilitychange", () => {

View File

@ -23,7 +23,7 @@
} catch (error) {}
})();
</script>
<link rel="stylesheet" href="/console.css">
<link rel="stylesheet" href="/console.css?v=2.2.78">
</head>
<body>
<main class="shell">
@ -97,7 +97,7 @@
<nav class="tabs" aria-label="Primary navigation">
<button class="tabBtn is-active" type="button" data-tab="health" id="tabHealth">Health</button>
<button class="tabBtn" type="button" data-tab="security" id="tabSecurity">Security</button>
<button class="tabBtn" type="button" data-tab="security" id="tabSecurity">Security &amp; Region</button>
<button class="tabBtn" type="button" data-tab="network" id="tabNetwork">Network</button>
<button class="tabBtn" type="button" data-tab="modbus" id="tabModbus">Modbus</button>
<button class="tabBtn" type="button" data-tab="tscreen" id="tabTscreen">It-Screen</button>
@ -108,7 +108,7 @@
</main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js"></script>
<script src="/console.js"></script>
<script src="/console.i18n.js?v=2.2.78"></script>
<script src="/console.js?v=2.2.78"></script>
</body>
</html>

View File

@ -3,6 +3,7 @@ import math
import os
import re
import shlex
import socket
DRM_ROOT = "/sys/class/drm"
@ -66,6 +67,16 @@ def _listening_tcp(ctx, port):
return any(needle in line for line in (stdout or "").splitlines())
def _remote_tcp_reachable(host, port, timeout=1.0):
if not host:
return False
try:
with socket.create_connection((host, int(port)), timeout=timeout):
return True
except (OSError, TypeError, ValueError):
return False
def _fallback(value, default="Not available"):
text = str(value or "").strip()
return text if text else default
@ -476,7 +487,7 @@ def mosquitto_card(ctx):
state, status_text = _lifecycle(installed, configured, active, failed=unit["active_state"] == "failed")
return _service_card(
"mosquitto",
"Mosquitto MQTT",
"Local Mosquitto MQTT",
"mosquitto.service",
installed,
configured,
@ -485,6 +496,10 @@ def mosquitto_card(ctx):
status_text,
_short_unit_errors(unit),
warnings,
details=[
{"label": "Local broker address", "value": "127.0.0.1:1883"},
{"label": "Bridged topic trees", "value": "v1/edge/# · it-screen/# · iomatex/#"},
],
)
@ -509,9 +524,11 @@ def mqtt_bridge_card(ctx):
])
)
remote_host = str(env.get("REMOTE_HOST", "")).strip()
remote_port = str(env.get("REMOTE_PORT", "1883")).strip() or "1883"
remote_reachable = _remote_tcp_reachable(remote_host, remote_port) if enabled else False
mosquitto = ctx["systemd_unit"]("mosquitto.service")
health_timer = ctx["systemd_unit"]("iomatex-mqtt-health.timer")
active = bool(enabled and remote_host and bridge_conf_exists and mosquitto["active"])
active = bool(enabled and remote_host and bridge_conf_exists and mosquitto["active"] and remote_reachable)
warnings = []
errors = []
if installed and not enabled:
@ -520,6 +537,8 @@ def mqtt_bridge_card(ctx):
errors.append("REMOTE_HOST is empty")
if installed and enabled and not bridge_conf_exists:
warnings.append("Bridge config missing")
if installed and enabled and remote_host and not remote_reachable:
errors.append("Remote MQTT broker is unreachable")
state, status_text = _lifecycle(installed, configured, active, failed=mosquitto["active_state"] == "failed")
if installed and configured and not active and not enabled:
status_text = "Disabled"
@ -537,6 +556,8 @@ def mqtt_bridge_card(ctx):
details=[
{"label": "Enable bridge", "value": "Yes" if enabled else "No"},
{"label": "Remote host", "value": remote_host or "-"},
{"label": "Remote port", "value": remote_port},
{"label": "Remote connection", "value": "Reachable" if remote_reachable else "Unavailable"},
{"label": "Bridge config", "value": "Present" if bridge_conf_exists else "Missing"},
{"label": "Broker unit", "value": mosquitto["active_state"] or "inactive"},
{"label": "Health timer", "value": health_timer["active_state"] or "inactive"},

View File

@ -38,6 +38,14 @@ SRC_GBOX="${GBOX_SOURCE:-$SCRIPT_DIR/g-box.png}"
APP_BIND="${CONSOLE_BIND:-0.0.0.0}"
APP_PORT="${CONSOLE_PORT:-80}"
APP_EXTRA_PORT="${CONSOLE_EXTRA_PORT:-8099}"
MQTT_ENVIRONMENT="${MQTT_ENVIRONMENT:-it-screen/its-docker}"
MQTT_HEAD_NAMESPACE="${MQTT_ENVIRONMENT%%/*}"
case "$MQTT_HEAD_NAMESPACE" in
""|*[!A-Za-z0-9._-]*)
echo "ERROR: MQTT_ENVIRONMENT must start with a valid MQTT topic namespace" >&2
exit 1
;;
esac
ts="$(date +%s)"
PREV_DIR="${APP_DIR}.prev.${ts}"
LEGACY_APP_DIR="/opt/iomatex-process1-webipc"
@ -313,6 +321,7 @@ Restart=always
RestartSec=2
User=root
Group=root
Environment="MQTT_ENVIRONMENT=${MQTT_ENVIRONMENT}"
[Install]
WantedBy=multi-user.target

View File

@ -693,11 +693,11 @@ const path = require('path');
const crypto = require('crypto');
module.exports = class DevicesMeta {
constructor(zigbee, mqtt, state, publishEntityState, eventBus, settings, logger) {
constructor(zigbee, mqtt, state, publishEntityState, eventBus, enableDisableExtension, restartCallback, addExtension, settings, logger) {
this.mqtt = mqtt;
this.state = state;
this.eventBus = eventBus;
this.settings = settings || {};
this.settings = settings?.get ? settings.get() : (settings || {});
this.logger = logger || console;
const config = this.settings || {};
@ -937,7 +937,7 @@ module.exports = class DevicesMeta {
const periodicDue = (now - this.lastPublishTs) >= 30000;
if (changed || (forcePeriodicCheck && periodicDue) || (!changed && periodicDue)) {
this.mqtt.publish(this.publishTopic, normalized, {retain: true});
this.mqtt.publish(this.publishTopic, normalized, {clientOptions: {retain: true}});
this.lastPublishedHash = hash;
this.lastPublishTs = now;