diff --git a/stage_env/stage_env_install_no_pulse.sh b/stage_env/stage_env_install_no_pulse.sh index ef883db..81c8271 100644 --- a/stage_env/stage_env_install_no_pulse.sh +++ b/stage_env/stage_env_install_no_pulse.sh @@ -220,6 +220,50 @@ apt_install_optional() { done } +migrate_pcp_logs_to_userdata() { + local target="/userdata/pcp" + local current_target="" + local backup_path="" + local ts="" + + if ! mountpoint -q /userdata; then + log "SKIP: /userdata is not mounted; keeping PCP logs at /var/log/pcp" + return 0 + fi + + mkdir -p "$target" + + if [ -L /var/log/pcp ]; then + current_target="$(readlink /var/log/pcp || true)" + if [ "$current_target" != "$target" ]; then + log "WARN: /var/log/pcp is already a symlink to ${current_target}; expected ${target}" + return 0 + fi + chown -R pcp:pcp "$target" 2>/dev/null || true + return 0 + fi + + systemctl_disable_now_safe pmcd pmie pmlogger pmproxy + + if [ -d /var/log/pcp ]; then + rsync -aHAX --numeric-ids /var/log/pcp/ "$target"/ + ts="$(date -u +%Y%m%d%H%M%S)" + backup_path="/var/log/pcp.bak.${ts}" + mv /var/log/pcp "$backup_path" + log "Migrated /var/log/pcp to ${target}; backup: ${backup_path}" + else + rm -f /var/log/pcp 2>/dev/null || true + fi + + ln -s "$target" /var/log/pcp + chown -R pcp:pcp "$target" 2>/dev/null || true + + systemctl_enable_now_safe pmcd + systemctl_enable_now_safe pmie + systemctl_enable_now_safe pmlogger + systemctl_enable_now_safe pmproxy +} + apt_remove_if_installed() { local pkgs=("$@") local installed=() @@ -524,7 +568,10 @@ apt_install_missing \ logrotate \ rsyslog \ network-manager \ - policykit-1 + policykit-1 \ + pulseaudio \ + pulseaudio-utils \ + alsa-utils step "Install mbpoll" install_mbpoll @@ -715,6 +762,7 @@ ensure_edge_name step "Install + enable Cockpit baseline + security reminder" apt_install_missing cockpit network-manager apt_install_optional cockpit-networkmanager cockpit-storaged cockpit-pcp +migrate_pcp_logs_to_userdata systemctl_enable_now_safe NetworkManager IP_MAIN="$(main_ipv4)" @@ -846,10 +894,12 @@ soft_run "Enable iomatex-userdata-bootstrap.service" 20 /bin/systemctl enable io # journald limits (no bind mounts) mkdir -p /etc/systemd/journald.conf.d JOURNALD_CFG_CHANGED=0 -write_if_changed /etc/systemd/journald.conf.d/99-iomatex.conf 0644 <<'EOF' +rm -f /etc/systemd/journald.conf.d/99-iomatex.conf 2>/dev/null || true +write_if_changed /etc/systemd/journald.conf.d/99-iomatex-limits.conf 0644 <<'EOF' [Journal] -SystemMaxUse=100M -SystemKeepFree=50M +SystemMaxUse=50M +SystemMaxFileSize=10M +RuntimeMaxUse=20M MaxRetentionSec=7day Compress=yes EOF @@ -881,12 +931,15 @@ write_if_changed /etc/logrotate.d/rsyslog 0644 <<'EOF' { daily rotate 3 - size 50M + size 10M compress delaycompress missingok notifempty - copytruncate + sharedscripts + postrotate + /usr/lib/rsyslog/rsyslog-rotate >/dev/null 2>&1 || /bin/systemctl reload rsyslog >/dev/null 2>&1 || true + endscript } EOF if [ "$WRITE_CHANGED" -eq 1 ]; then @@ -915,11 +968,9 @@ MOSQ_ROTATE_CHANGED=0 write_if_changed /etc/logrotate.d/mosquitto-iomatex 0644 <<'EOF' /var/log/mosquitto/mosquitto.log { - daily - rotate 7 - size 20M + size 10M + rotate 3 compress - delaycompress missingok notifempty copytruncate @@ -962,7 +1013,8 @@ for log_path in \ /var/log/debug \ /var/log/kern.log \ /var/log/auth.log \ - /var/log/mosquitto/mosquitto.log + /var/log/mosquitto/mosquitto.log \ + /var/lib/itscreen/logs/itscreen.log do [ -f "$log_path" ] || continue : > "$log_path" || true @@ -972,6 +1024,53 @@ logger -t iomatex-log-watchdog "emergency log cleanup finished" exit 0 EOF +write_if_changed /usr/local/sbin/iomatex-storage-sanity 0755 <<'EOF' +#!/usr/bin/env bash +set -u + +echo "== df -h ==" +df -h || true + +echo +echo "== /var/log usage ==" +du -xh /var/log --max-depth=2 2>/dev/null | sort -h | tail || true + +echo +echo "== journald disk usage ==" +journalctl --disk-usage 2>/dev/null || true + +echo +echo "== symlink checks ==" +if test -L /var/lib/itscreen; then + echo "OK: /var/lib/itscreen -> $(readlink /var/lib/itscreen)" +else + echo "WARN: /var/lib/itscreen is not a symlink" +fi +if test -L /var/log/pcp; then + echo "OK: /var/log/pcp -> $(readlink /var/log/pcp)" +else + echo "WARN: /var/log/pcp is not a symlink" +fi + +echo +echo "== service checks ==" +for unit in itscreen-x11 mosquitto systemd-journald; do + printf '%s: ' "$unit" + systemctl is-active "$unit" 2>/dev/null || true +done +EOF + +write_if_changed /usr/local/sbin/iomatex-pcp-maintenance 0755 <<'EOF' +#!/usr/bin/env bash +set -u + +ARCHIVE_MAX="${PCP_ARCHIVE_MAX:-300M}" + +if command -v pmlogger_daily >/dev/null 2>&1; then + pmlogger_daily -d "$ARCHIVE_MAX" >/dev/null 2>&1 || true +fi +EOF + WATCHDOG_UNIT_CHANGED=0 write_if_changed /etc/systemd/system/iomatex-log-watchdog.service 0644 <<'EOF' [Unit] @@ -1008,8 +1107,44 @@ if [ "$WATCHDOG_UNIT_CHANGED" -eq 1 ]; then soft_run "systemd daemon-reload (log watchdog)" 20 /bin/systemctl daemon-reload fi +PCP_MAINT_UNIT_CHANGED=0 +write_if_changed /etc/systemd/system/iomatex-pcp-maintenance.service 0644 <<'EOF' +[Unit] +Description=IOMATEX PCP archive maintenance +ConditionPathIsDirectory=/userdata/pcp + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/iomatex-pcp-maintenance +TimeoutStartSec=300 +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + PCP_MAINT_UNIT_CHANGED=1 +fi + +write_if_changed /etc/systemd/system/iomatex-pcp-maintenance.timer 0644 <<'EOF' +[Unit] +Description=Run IOMATEX PCP archive maintenance daily + +[Timer] +OnCalendar=daily +Persistent=true + +[Install] +WantedBy=timers.target +EOF +if [ "$WRITE_CHANGED" -eq 1 ]; then + PCP_MAINT_UNIT_CHANGED=1 +fi + +if [ "$PCP_MAINT_UNIT_CHANGED" -eq 1 ]; then + soft_run "systemd daemon-reload (PCP maintenance)" 20 /bin/systemctl daemon-reload +fi + soft_run "Enable iomatex-log-watchdog.timer" 20 /bin/systemctl enable --now iomatex-log-watchdog.timer soft_run "Run iomatex-log-watchdog once (best-effort)" 30 /bin/systemctl start iomatex-log-watchdog.service +soft_run "Enable iomatex-pcp-maintenance.timer" 20 /bin/systemctl enable --now iomatex-pcp-maintenance.timer +soft_run "Run PCP archive maintenance once (best-effort)" 300 /bin/systemctl start iomatex-pcp-maintenance.service if [ "$MOSQ_LOG_CFG_CHANGED" -eq 1 ]; then soft_run "Restart mosquitto (production logging baseline)" 30 /bin/systemctl restart mosquitto @@ -1017,6 +1152,7 @@ fi # Run bootstrap once now (best-effort) soft_run "Run userdata bootstrap now (best-effort)" 30 /bin/systemctl start iomatex-userdata-bootstrap.service +soft_run "Run storage sanity check (best-effort)" 30 /usr/local/sbin/iomatex-storage-sanity # ------------------------- # Finish summary diff --git a/stage_itscreen/itscreen b/stage_itscreen/itscreen index de87b8d..f53f317 100644 Binary files a/stage_itscreen/itscreen and b/stage_itscreen/itscreen differ diff --git a/stage_itscreen/qt-video-oes-plugins_1.0.3_arm64.deb b/stage_itscreen/qt-video-oes-plugins_1.0.3_arm64.deb new file mode 100644 index 0000000..af49136 Binary files /dev/null and b/stage_itscreen/qt-video-oes-plugins_1.0.3_arm64.deb differ diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh index 8ab33e5..369b64b 100755 --- a/stage_itscreen/stage_itscreen_install.sh +++ b/stage_itscreen/stage_itscreen_install.sh @@ -15,8 +15,10 @@ ITS_X11_LAUNCHER="/usr/local/bin/itscreen-x11-launch" ITS_X11_CLEANUP="/usr/local/bin/itscreen-x11-cleanup" ITS_BOOT_TRACE_SCRIPT="/usr/local/bin/itscreen-boot-trace" ITS_RECOVERY_SCRIPT="/usr/local/bin/itscreen-boot-recovery" +IOMATEX_PULSE_APPLY_SCRIPT="/usr/local/bin/iomatex-pulse-apply-route" ITS_SERVICE="itscreen-x11.service" ITS_RECOVERY_SERVICE="itscreen-x11-recovery.service" +IOMATEX_PULSE_SERVICE="iomatex-pulseaudio.service" LIGHTDM_SERVICE="lightdm.service" DISPLAY_MANAGER_SERVICE="display-manager.service" NM_WAIT_SERVICE="NetworkManager-wait-online.service" @@ -26,16 +28,24 @@ XSESSION_HOOK="/etc/X11/Xsession.d/99-iomatex-allow-itscreen" XWRAPPER_CONFIG="/etc/X11/Xwrapper.config" ITS_UNIT_FILE="/etc/systemd/system/${ITS_SERVICE}" ITS_RECOVERY_UNIT_FILE="/etc/systemd/system/${ITS_RECOVERY_SERVICE}" +IOMATEX_PULSE_UNIT_FILE="/etc/systemd/system/${IOMATEX_PULSE_SERVICE}" ITS_RUN_DIR="/run/itscreen" LOCK_DIR="/var/lib/itscreen" LOCK_FILE="${LOCK_DIR}/itscreen.lock" ITS_CONFIG_DIR="/var/lib/itscreen/config/it-screen" ITS_CONFIG_FILE="${ITS_CONFIG_DIR}/it-screen.conf" +ITS_USERDATA_DIR="/userdata/itscreen" +IOMATEX_AUDIO_STATE_DIR="/etc/iomatex" +IOMATEX_AUDIO_ROUTE_FILE="${IOMATEX_AUDIO_STATE_DIR}/audio-route.env" +IOMATEX_PULSE_RUNTIME_DIR="/run/iomatex-pulse" +IOMATEX_PULSE_SOCKET="${IOMATEX_PULSE_RUNTIME_DIR}/native" +IOMATEX_PULSE_STATE_DIR="/var/lib/iomatex/pulseaudio" +IOMATEX_PULSE_LOGICAL_DUAL_SINK="iomatex_dual_output" DEVICE_ID_FILE="/userdata/device-id" DEVICE_ID_RE='^g-box-[a-f0-9]{8}$' step_n=0 -TOTAL_STEPS=15 +TOTAL_STEPS=20 log() { local line="[$(date -u +'%F %T UTC')] $*" @@ -316,7 +326,7 @@ install_base_packages() { require_cmd id run_long "APT update" 900 apt-get update - soft_run "Ensure base packages" 600 apt-get install -y procps util-linux x11-xserver-utils xinit psmisc sudo + soft_run "Ensure base packages" 600 apt-get install -y procps util-linux x11-xserver-utils xinit psmisc sudo pulseaudio pulseaudio-utils alsa-utils rsync logrotate if ! command -v Xorg >/dev/null 2>&1; then soft_run "Ensure Xorg core" 900 apt-get install -y xserver-xorg-core fi @@ -326,28 +336,91 @@ install_base_packages() { require_cmd xinit require_cmd Xorg require_cmd fuser + require_cmd rsync id "$ITS_USER" >/dev/null 2>&1 || { echo "Run Stage_0 first"; exit 2; } } +ensure_itscreen_userdata_layout() { + local current_target backup_path ts + + if ! mountpoint -q /userdata; then + warn "/userdata is not mounted; keeping /var/lib/itscreen on root for this run" + return 0 + fi + + ensure_dir "$ITS_USERDATA_DIR" 0755 "$ITS_USER" "$ITS_GROUP" + + if [[ -L /var/lib/itscreen ]]; then + current_target="$(readlink /var/lib/itscreen || true)" + if [[ "$current_target" != "$ITS_USERDATA_DIR" ]]; then + warn "/var/lib/itscreen is already a symlink to ${current_target}; expected ${ITS_USERDATA_DIR}" + return 0 + fi + chown -R "$ITS_USER:$ITS_GROUP" "$ITS_USERDATA_DIR" 2>/dev/null || true + return 0 + fi + + if [[ -d /var/lib/itscreen ]]; then + log "Migrating IT-Screen state to /userdata" + systemctl stop "$ITS_SERVICE" >/dev/null 2>&1 || true + ensure_dir "$ITS_USERDATA_DIR" 0755 "$ITS_USER" "$ITS_GROUP" + rsync -aHAX --numeric-ids /var/lib/itscreen/ "$ITS_USERDATA_DIR"/ + ts="$(date -u +%Y%m%d%H%M%S)" + backup_path="/var/lib/itscreen.bak.${ts}" + mv /var/lib/itscreen "$backup_path" + ln -s "$ITS_USERDATA_DIR" /var/lib/itscreen + chown -R "$ITS_USER:$ITS_GROUP" "$ITS_USERDATA_DIR" 2>/dev/null || true + log "Migrated /var/lib/itscreen to ${ITS_USERDATA_DIR}; backup: ${backup_path}" + return 0 + fi + + rm -f /var/lib/itscreen 2>/dev/null || true + ln -s "$ITS_USERDATA_DIR" /var/lib/itscreen + chown -R "$ITS_USER:$ITS_GROUP" "$ITS_USERDATA_DIR" 2>/dev/null || true +} + ensure_runtime_directories() { step "Ensure runtime directories" ensure_dir /opt/itscreen 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /opt/itscreen/bin 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /opt/itscreen/data 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /opt/itscreen/logs 0755 "$ITS_USER" "$ITS_GROUP" + ensure_itscreen_userdata_layout ensure_dir /var/lib/itscreen 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /var/lib/itscreen/config 0770 "$ITS_USER" "$ITS_GROUP" ensure_dir "$ITS_CONFIG_DIR" 0770 "$ITS_USER" "$ITS_GROUP" + ensure_dir /var/lib/itscreen/Downloads 0770 "$ITS_USER" "$ITS_GROUP" ensure_dir /var/lib/itscreen/data 0770 "$ITS_USER" "$ITS_GROUP" + ensure_dir /var/lib/itscreen/cache 0770 "$ITS_USER" "$ITS_GROUP" ensure_dir /var/lib/itscreen/logs 0770 "$ITS_USER" "$ITS_GROUP" ensure_dir /var/log/itscreen 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /var/log 0755 root root ensure_dir /etc/sudoers.d 0755 root root + ensure_dir "$IOMATEX_AUDIO_STATE_DIR" 0755 root root + ensure_dir "$IOMATEX_PULSE_STATE_DIR" 0755 "$ITS_USER" "$ITS_GROUP" ensure_dir /etc/X11/Xsession.d 0755 root root ensure_dir /etc/systemd/system 0755 root root ensure_dir /usr/local/bin 0755 root root ensure_dir "$ITS_RUN_DIR" 0755 root root + rm -f /var/lib/itscreen/.asoundrc +} + +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 } install_itscreen_config() { @@ -360,6 +433,12 @@ minimizeFrame=0 EOF } +prepare_qt_gles_stack() { + step "Prepare Qt OpenGLES stack" + apt-mark unhold qv4l2 qv4l2-dbgsym >/dev/null 2>&1 || true + apt-get remove -y qv4l2 qv4l2-dbgsym libqt5opengl5 >/dev/null 2>&1 || true +} + install_qt_packages() { step "Install Qt runtime (exact list)" install_packages_best_effort "Install Qt runtime" 1800 \ @@ -388,6 +467,24 @@ install_qt_packages() { ldconfig } +install_qt_video_oes_plugin() { + step "Install Qt Video OES plugin" + + local deb="${SCRIPT_DIR}/qt-video-oes-plugins_1.0.3_arm64.deb" + + if dpkg-query -W -f='${Status}\n' qt-video-oes-plugins 2>/dev/null | grep -qx 'install ok installed'; then + log "qt-video-oes-plugins already installed" + return 0 + fi + + [[ -f "$deb" ]] || die "Missing OES plugin package: $deb" + + run_long "Install Qt Video OES plugin" 300 dpkg -i "$deb" + soft_run "Fix dependencies after OES plugin install" 600 apt-get install -f -y + + ldconfig +} + cleanup_legacy_lightdm_boot_path() { step "Disable LightDM boot path" } @@ -435,6 +532,196 @@ exec flock -n "\$LOCK" /opt/itscreen/bin/itscreen fullscreen "\$@" EOF } +install_audio_route_state() { + step "Initialize PulseAudio route state" + if [[ -f "$IOMATEX_AUDIO_ROUTE_FILE" ]] && grep -qE '^TARGET="?(hdmi|analog|dual)"?$' "$IOMATEX_AUDIO_ROUTE_FILE" 2>/dev/null; then + log "Preserving existing PulseAudio route state: ${IOMATEX_AUDIO_ROUTE_FILE}" + return 0 + fi + write_file "$IOMATEX_AUDIO_ROUTE_FILE" 0644 root root </dev/null || true + printf '%s\n' "\$*" +} + +wait_for_pulse() { + local attempt + for attempt in \$(seq 1 30); do + if PULSE_SERVER="\$PULSE_SERVER" pactl info >/dev/null 2>&1; then + return 0 + fi + sleep 1 + done + return 1 +} + +route_target() { + local target="hdmi" + if [[ -f "\$ROUTE_FILE" ]]; then + target="\$(awk -F= '/^TARGET=/{gsub(/"/, "", \$2); print tolower(\$2); exit}' "\$ROUTE_FILE" 2>/dev/null || true)" + fi + case "\$target" in + hdmi|analog|dual) ;; + *) target="hdmi" ;; + esac + printf '%s\n' "\$target" +} + +sink_name_for() { + local target="\$1" + local line name lower + while IFS=$'\t' read -r _ name _; do + [[ -n "\${name:-}" ]] || continue + lower="\$(printf '%s' "\$name" | tr '[:upper:]' '[:lower:]')" + case "\$target" in + hdmi) + [[ "\$lower" == *hdmi* ]] && { printf '%s\n' "\$name"; return 0; } + ;; + analog) + if [[ "\$lower" != *hdmi* ]] && [[ "\$lower" == *analog* || "\$lower" == *rk809* || "\$lower" == *codec* || "\$lower" == *headphone* ]]; then + printf '%s\n' "\$name" + return 0 + fi + ;; + esac + done < <(PULSE_SERVER="\$PULSE_SERVER" pactl list short sinks 2>/dev/null || true) + + while IFS=$'\t' read -r _ name _; do + [[ -n "\${name:-}" ]] || continue + lower="\$(printf '%s' "\$name" | tr '[:upper:]' '[:lower:]')" + case "\$target" in + hdmi) + [[ "\$lower" == *hdmi* ]] && { printf '%s\n' "\$name"; return 0; } + ;; + analog) + [[ "\$lower" != *hdmi* ]] && { printf '%s\n' "\$name"; return 0; } + ;; + esac + done < <(PULSE_SERVER="\$PULSE_SERVER" pactl list short sinks 2>/dev/null || true) + + return 1 +} + +wait_for_sink() { + local target="\$1" + local attempt sink_name + for attempt in \$(seq 1 15); do + sink_name="\$(sink_name_for "\$target" || true)" + if [[ -n "\$sink_name" ]]; then + printf '%s\n' "\$sink_name" + return 0 + fi + sleep 1 + done + return 1 +} + +unload_dual_sink() { + local module_id module_name module_args + while IFS=$'\t' read -r module_id module_name module_args; do + [[ "\$module_name" == "module-combine-sink" ]] || continue + [[ "\$module_args" == *"sink_name=\${DUAL_SINK_NAME}"* ]] || continue + PULSE_SERVER="\$PULSE_SERVER" pactl unload-module "\$module_id" >/dev/null 2>&1 || true + done < <(PULSE_SERVER="\$PULSE_SERVER" pactl list short modules 2>/dev/null || true) +} + +set_default_sink() { + local sink_name="\$1" + PULSE_SERVER="\$PULSE_SERVER" pactl set-default-sink "\$sink_name" + log "Default sink set to \$sink_name" +} + +apply_route() { + local target="\$1" + local hdmi_sink="" analog_sink="" + + case "\$target" in + hdmi) + hdmi_sink="\$(wait_for_sink hdmi || true)" + [[ -n "\$hdmi_sink" ]] || { log "HDMI sink not found"; return 1; } + unload_dual_sink + set_default_sink "\$hdmi_sink" + ;; + analog) + analog_sink="\$(wait_for_sink analog || true)" + [[ -n "\$analog_sink" ]] || { log "Analog sink not found"; return 1; } + unload_dual_sink + set_default_sink "\$analog_sink" + ;; + dual) + hdmi_sink="\$(wait_for_sink hdmi || true)" + analog_sink="\$(wait_for_sink analog || true)" + [[ -n "\$hdmi_sink" ]] || { log "HDMI sink not found for dual route"; return 1; } + [[ -n "\$analog_sink" ]] || { log "Analog sink not found for dual route"; return 1; } + unload_dual_sink + PULSE_SERVER="\$PULSE_SERVER" pactl load-module module-combine-sink sink_name="\$DUAL_SINK_NAME" slaves="\${hdmi_sink},\${analog_sink}" sink_properties=device.description=IOMATEX_Dual_Output >/dev/null + set_default_sink "\$DUAL_SINK_NAME" + ;; + *) + log "Unsupported route target: \$target" + return 1 + ;; + esac +} + +main() { + local target + wait_for_pulse || { + log "PulseAudio is not ready on \$PULSE_SERVER" + exit 1 + } + target="\$(route_target)" + apply_route "\$target" +} + +main "\$@" +EOF + + write_file "$IOMATEX_PULSE_UNIT_FILE" 0644 root root </dev/null 2>&1 } +wait_for_pulse_ready() { + local attempt + for attempt in $(seq 1 30); do + if PULSE_SERVER="$PULSE_SERVER_VALUE" pactl info >/dev/null 2>&1; then + log "PulseAudio is ready on ${PULSE_SERVER_VALUE}" + return 0 + fi + log "Waiting for PulseAudio on ${PULSE_SERVER_VALUE} (${attempt}/30)" + sleep 1 + done + log "ERROR: PulseAudio is not ready; refusing to start it-screen to prevent ALSA fallback" + return 1 +} + wait_for_x_ready() { local attempt for attempt in $(seq 1 20); do @@ -476,6 +778,27 @@ wait_for_x_ready() { return 0 } +force_display_mode() { + if ! have xrandr; then + log "WARN: xrandr is not installed; cannot force display mode" + return 0 + fi + + if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr | grep -q "^HDMI-1 connected"; then + if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr | grep -q "1920x1080"; then + if DISPLAY="$DISPLAY_VALUE" XAUTHORITY="$XAUTHORITY_VALUE" xrandr --output HDMI-1 --mode 1920x1080 --rate 60 >/dev/null 2>&1; then + log "Display mode forced to HDMI-1 1920x1080@60" + else + log "WARN: failed to force HDMI-1 1920x1080@60" + fi + else + log "WARN: HDMI-1 connected but 1920x1080 mode is not available" + fi + else + log "WARN: HDMI-1 is not connected; skipping display mode force" + fi +} + ensure_openbox() { if ! have openbox; then log "ERROR: openbox is not installed" @@ -556,7 +879,9 @@ apply_fullscreen() { } wait_for_x_ready +force_display_mode ensure_openbox +wait_for_pulse_ready log "Launching it-screen" /usr/local/bin/itscreen-run "$@" >>"$APP_LOG" 2>&1 & @@ -579,6 +904,7 @@ export XDG_CONFIG_HOME=/var/lib/itscreen/config export XDG_DATA_HOME=/var/lib/itscreen/data export XDG_RUNTIME_DIR=/run/itscreen/xdg export ITSCREEN_LOG_DIR=/var/lib/itscreen/logs +export PULSE_SERVER=unix:/run/iomatex-pulse/native exec /usr/bin/setpriv --reuid itscreen --regid itscreen --init-groups \ /usr/bin/env \ @@ -592,6 +918,7 @@ exec /usr/bin/setpriv --reuid itscreen --regid itscreen --init-groups \ XDG_CONFIG_HOME="$XDG_CONFIG_HOME" \ XDG_DATA_HOME="$XDG_DATA_HOME" \ ITSCREEN_LOG_DIR="$ITSCREEN_LOG_DIR" \ + PULSE_SERVER="$PULSE_SERVER" \ /usr/bin/dbus-run-session -- /usr/local/bin/itscreen-session-launch EOF @@ -916,7 +1243,8 @@ install_systemd_unit() { [Unit] Description=ITSCREEN dedicated X11 session Wants=network-online.target -After=NetworkManager.service network-online.target systemd-user-sessions.service +Wants=iomatex-pulseaudio.service +After=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 @@ -931,6 +1259,7 @@ RuntimeDirectory=itscreen RuntimeDirectoryMode=0755 Environment=ITSCREEN_DISPLAY=:0 Environment=ITSCREEN_VT=vt7 +Environment=PULSE_SERVER=unix:/run/iomatex-pulse/native ExecStartPre=-/usr/local/bin/itscreen-boot-trace pre-start ExecStartPre=/usr/bin/nm-online -s -q --timeout=45 # Monitor presence is not required for startup; always attempt the dedicated X11 launch flow, including headless mode. @@ -965,6 +1294,9 @@ enable_managed_services() { systemctl stop "$LIGHTDM_SERVICE" >/dev/null 2>&1 || true systemctl stop "$DISPLAY_MANAGER_SERVICE" >/dev/null 2>&1 || true + enable_service_safe "$IOMATEX_PULSE_SERVICE" + systemctl reset-failed "$IOMATEX_PULSE_SERVICE" >/dev/null 2>&1 || true + restart_service_safe "$IOMATEX_PULSE_SERVICE" enable_service_safe "$ITS_SERVICE" systemctl reset-failed "$ITS_SERVICE" >/dev/null 2>&1 || true restart_service_safe "$ITS_SERVICE" @@ -1011,6 +1343,8 @@ binary_architecture_report() { post_install_self_test() { local missing_path + local oes_plugin_path + local qt_pkg local status_output="" local journal_output="" local service_active="no" @@ -1038,7 +1372,8 @@ post_install_self_test() { "$ITS_X11_LAUNCHER" \ "$ITS_X11_CLEANUP" \ "$ITS_BOOT_TRACE_SCRIPT" \ - "$ITS_RECOVERY_SCRIPT"; do + "$ITS_RECOVERY_SCRIPT" \ + "$IOMATEX_PULSE_APPLY_SCRIPT"; do if [[ ! -x "$missing_path" ]]; then die "Required launcher script missing or not executable: ${missing_path}" fi @@ -1046,7 +1381,7 @@ post_install_self_test() { log "Self-test: waiting up to 30s for ${ITS_SERVICE} to become active" for _ in $(seq 1 30); do - if systemctl is-active --quiet "$ITS_SERVICE"; then + if systemctl is-active --quiet "$IOMATEX_PULSE_SERVICE" && systemctl is-active --quiet "$ITS_SERVICE"; then service_active="yes" break fi @@ -1063,6 +1398,25 @@ post_install_self_test() { log "Self-test: runtime helper scripts present" log "Self-test: uname -m=${arch_machine:-unknown}" log "Self-test: binary architecture check=${arch_status:-unknown} detail=${arch_detail:-unknown}" + + for qt_pkg in qt-video-oes-plugins libqt5gui5-gles libqt5quick5-gles; do + if dpkg-query -W -f='${Status}\n' "$qt_pkg" 2>/dev/null | grep -qx 'install ok installed'; then + log "Self-test: package installed: ${qt_pkg}" + else + warn "Self-test: package is not installed: ${qt_pkg}" + fi + done + + for oes_plugin_path in \ + /usr/lib/aarch64-linux-gnu/qt5/plugins/video/gstvideorenderer/libgstvideooes.so \ + /usr/lib/aarch64-linux-gnu/qt5/plugins/video/videonode/libvideonodeoes.so; do + if [[ -f "$oes_plugin_path" ]]; then + log "Self-test: OES plugin file present: ${oes_plugin_path}" + else + warn "Self-test: OES plugin file missing: ${oes_plugin_path}" + fi + done + if [[ "${arch_status:-unknown}" == "mismatch" ]]; then warn "Self-test: binary architecture does not match uname -m (${arch_machine:-unknown})" elif [[ "${arch_status:-unknown}" == "unknown" ]]; then @@ -1103,18 +1457,27 @@ print_summary() { echo " ${ITS_X11_LAUNCHER}" echo " ${ITS_X11_CLEANUP}" echo " ${ITS_RECOVERY_SCRIPT}" + echo " ${IOMATEX_PULSE_APPLY_SCRIPT}" + echo " ${IOMATEX_AUDIO_ROUTE_FILE}" + echo " ${IOMATEX_PULSE_UNIT_FILE}" echo " ${ITS_UNIT_FILE}" echo " ${ITS_RECOVERY_UNIT_FILE}" echo "Services after install:" echo " ${LIGHTDM_SERVICE}: disabled" + echo " ${IOMATEX_PULSE_SERVICE}: enabled" echo " ${ITS_SERVICE}: enabled" echo "Main log file:" echo " ${LOG}" echo "Quick verification commands:" + echo " systemctl status ${IOMATEX_PULSE_SERVICE} --no-pager" echo " systemctl status ${ITS_SERVICE} --no-pager" echo " systemctl status ${LIGHTDM_SERVICE} --no-pager" + echo " PULSE_SERVER=unix:${IOMATEX_PULSE_SOCKET} pactl info" echo " journalctl -u ${ITS_SERVICE} -n 80 --no-pager" echo " ls -l ${ITS_BINARY} ${ITS_WRAPPER} ${ITS_UNIT_FILE}" + echo " dpkg -l | grep -E \"libqt5gui5-gles|libqt5quick5-gles|qt-video-oes-plugins\"" + echo " sudo grep -Ei \"libGLES|libgstvideooes|libvideonodeoes|libgstrockchipmpp|librockchip_mpp\" /proc/\$(pidof itscreen)/maps | sort -u" + echo " xrandr | grep -E \"\\*|connected\"" echo "Manual desktop mode via SSH:" echo " systemctl stop ${ITS_SERVICE}" echo " systemctl start ${LIGHTDM_SERVICE}" @@ -1135,13 +1498,18 @@ main() { install_base_packages ensure_edge_name ensure_runtime_directories + install_itscreen_logrotate + prepare_qt_gles_stack install_qt_packages + install_qt_video_oes_plugin cleanup_legacy_lightdm_boot_path cleanup_legacy_x11_hacks install_itscreen_binary install_itscreen_config install_sudoers install_wrapper + install_audio_route_state + install_pulseaudio_assets install_x11_session_scripts install_recovery_assets install_systemd_unit diff --git a/stage_mqtt/stage_mqtt_install.sh b/stage_mqtt/stage_mqtt_install.sh index 57c1df6..0c53c45 100755 --- a/stage_mqtt/stage_mqtt_install.sh +++ b/stage_mqtt/stage_mqtt_install.sh @@ -250,6 +250,7 @@ ENV_FILE="/etc/iomatex/mqtt_bridge.env" BRIDGE_CONF="/etc/mosquitto/conf.d/50-iomatex-bridge.conf" MAIN_SNIPPET="/etc/mosquitto/conf.d/01-iomatex-main-listener.conf" STAMP="/run/iomatex-mqtt-apply.sha" +LOCK_FILE="/run/iomatex-mqtt-apply.lock" log(){ echo "[$(date -u +'%F %T UTC')] $*"; } die(){ echo "ERROR: $*" >&2; exit 1; } @@ -358,6 +359,7 @@ validate_value(){ set_kv(){ local k="$1" v="$2" validate_value "$v" + [[ "$(get_kv "$k")" == "$v" ]] && return 0 local tmp; tmp="$(mktemp)" awk -v k="$k" -v v="$v" 'BEGIN{found=0} $0 ~ "^"k"=" {print k"="v; found=1; next} @@ -404,7 +406,8 @@ address ${REMOTE_HOST}:${REMOTE_PORT} bridge_protocol_version mqttv311 cleansession true -try_private true +# Use normal MQTT client bridge mode; private bridge mode can suppress OUT forwarding with bidirectional same-prefix mappings. +try_private false notifications false clientid ${REMOTE_CLIENTID} @@ -517,7 +520,16 @@ main(){ --set-tls) SET_TLS=1; V_TLS="${2-}"; shift 2;; --set-user) SET_USER=1; V_USER="${2-}"; shift 2;; --set-pass) SET_PASS=1; V_PASS="${2-}"; shift 2;; - --set-clientid) SET_CID=1; V_CID="${2-}"; shift 2;; + --set-clientid) + SET_CID=1 + if [[ $# -ge 2 && "${2-}" != --* ]]; then + V_CID="$2" + shift 2 + else + V_CID="" + shift + fi + ;; --set-base-topic) SET_BASE=1; V_BASE="${2-}"; shift 2;; --legacy-itscreen) SET_LEG=1; V_LEG="${2-}"; shift 2;; -h|--help) usage; exit 0;; @@ -530,7 +542,7 @@ main(){ [[ "$SET_TLS" == "1" ]] && set_kv REMOTE_TLS "$V_TLS" [[ "$SET_USER" == "1" ]] && set_kv REMOTE_USERNAME "$V_USER" [[ "$SET_PASS" == "1" ]] && set_kv REMOTE_PASSWORD "$V_PASS" - [[ "$SET_CID" == "1" ]] && set_kv REMOTE_CLIENTID "$V_CID" + [[ "$SET_CID" == "1" && -n "$V_CID" ]] && set_kv REMOTE_CLIENTID "$V_CID" [[ "$SET_BASE" == "1" ]] && set_kv BRIDGE_BASE_TOPIC "$V_BASE" [[ "$SET_LEG" == "1" ]] && set_kv LEGACY_ITSCREEN_TREE "$V_LEG" @@ -573,7 +585,16 @@ main(){ fi } -main "$@" +run_with_lock(){ + require_root + mkdir -p /run + # Serialize apply calls because UI/status polling may call this tool frequently. + exec 9>"$LOCK_FILE" + flock 9 + main "$@" +} + +run_with_lock "$@" __IOMATEX_APPLY__ chmod 0755 "$APPLY" chown root:root "$APPLY" @@ -736,7 +757,6 @@ __IOMATEX_HEALTH_TIMER__ step "Enable services and apply config now" systemctl daemon-reload systemctl enable mosquitto >/dev/null 2>&1 || true -systemctl enable --now iomatex-mqtt-bridge.path systemctl enable --now iomatex-mqtt-health.timer /usr/local/sbin/iomatex-mqtt-apply --print || true diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index ce9fcbc..8f55a5c 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -3,16 +3,20 @@ import glob import importlib.util import ipaddress import json +import math import os +import pwd import shutil import re import secrets import select +import struct import threading import subprocess import sys import tempfile import time +import wave import crypt import spwd from datetime import datetime @@ -77,8 +81,12 @@ LIGHTDM_ACCOUNTSSERVICE_DIR = "/var/lib/AccountsService/users" LIGHTDM_AUTOLOGIN_USER = "iomatex" ITSCREEN_CONFIG_PATH = "/var/lib/itscreen/config/it-screen/it-screen.conf" ITSCREEN_LOG_PATH = "/var/lib/itscreen/logs/itscreen.log" -ITSCREEN_AUDIO_CONFIG_PATH = "/var/lib/itscreen/.asoundrc" ITSCREEN_CLEANUP_SCRIPT = "/usr/local/bin/itscreen-x11-cleanup" +IOMATEX_PULSE_SERVICE_UNIT = "iomatex-pulseaudio.service" +IOMATEX_PULSE_SERVER = "unix:/run/iomatex-pulse/native" +IOMATEX_PULSE_APPLY_SCRIPT = "/usr/local/bin/iomatex-pulse-apply-route" +IOMATEX_AUDIO_ROUTE_PATH = "/etc/iomatex/audio-route.env" +IOMATEX_DUAL_SINK_NAME = "iomatex_dual_output" ITSCREEN_CONFIG_CACHE_TTL_SEC = 3.0 ITSCREEN_LOG_DEFAULT_LINES = 100 ITSCREEN_LOG_MAX_LINES = 100 @@ -168,7 +176,7 @@ def load_config(): return data -def run(cmd, timeout=4): +def run(cmd, timeout=4, env=None): try: proc = subprocess.run( cmd, @@ -177,6 +185,7 @@ def run(cmd, timeout=4): text=True, timeout=timeout, check=False, + env=env, ) return proc.returncode, (proc.stdout or "").strip(), (proc.stderr or "").strip() except Exception as exc: @@ -418,6 +427,39 @@ def trim_output_lines(text, limit=12, width=220): return lines +AUDIO_TARGETS = { + "hdmi": { + "label": "HDMI audio", + "description": "Digital audio over HDMI output", + "match_terms": ("hdmi",), + }, + "analog": { + "label": "Analog audio", + "description": "Analog audio via rockchip-rk809 codec", + "match_terms": ("analog", "rk809", "codec", "headphone", "rockchip"), + }, + "dual": { + "label": "HDMI + Analog", + "description": "PulseAudio combined sink for HDMI and analog output", + "match_terms": ("iomatex dual output", IOMATEX_DUAL_SINK_NAME), + }, +} + + +def pulse_env(): + env = os.environ.copy() + env["PULSE_SERVER"] = IOMATEX_PULSE_SERVER + return env + + +def pactl(args, timeout=4): + return run(["pactl", *args], timeout=timeout, env=pulse_env()) + + +def paplay(args, timeout=8): + return run(["paplay", *args], timeout=timeout, env=pulse_env()) + + def parse_alsa_cards(): raw = read_text("/proc/asound/cards") cards = [] @@ -440,258 +482,306 @@ def parse_alsa_cards(): return cards -def get_alsa_card(card_index): - for card in parse_alsa_cards(): - if card.get("index") == card_index: - return card - return {} +def parse_pactl_info(): + rc, stdout, stderr = pactl(["info"], timeout=4) + info = {} + if rc != 0: + return {"ok": False, "details": trim_output_lines(stderr or stdout, limit=6)} + for line in (stdout or "").splitlines(): + if ":" not in line: + continue + key, value = line.split(":", 1) + info[key.strip()] = value.strip() + return {"ok": True, "info": info, "details": trim_output_lines(stdout, limit=8)} -def audio_route_info(): - pactl_error_lines = [] - if command_exists("pactl"): - rc, stdout, stderr = run(["pactl", "info"], timeout=4) - if rc == 0: - info = {} - for line in (stdout or "").splitlines(): - if ":" not in line: - continue - key, value = line.split(":", 1) - info[key.strip()] = value.strip() - sink = info.get("Default Sink") - server_name = info.get("Server Name") - summary = sink or server_name or "PulseAudio/PipeWire route detected" - return { - "type": "pulse", - "summary": summary, - "details": trim_output_lines(stdout, limit=6), +def parse_pactl_sections(text, prefix): + sections = [] + current = None + matcher = re.compile(rf"^{re.escape(prefix)}\s+#(\d+)") + for raw in (text or "").splitlines(): + line = raw.rstrip() + match = matcher.match(line) + if match: + current = {"index": int(match.group(1))} + sections.append(current) + continue + if not current: + continue + stripped = line.strip() + if not stripped: + continue + if ":" in stripped: + key, value = stripped.split(":", 1) + current[key.strip()] = value.strip() + continue + prop_match = re.match(r"^([a-zA-Z0-9_.-]+)\s*=\s*\"?(.*?)\"?$", stripped) + if prop_match: + current[prop_match.group(1).strip()] = prop_match.group(2).strip().strip('"') + return sections + + +def classify_sink_target(name, description): + haystack = " ".join([str(name or "").lower(), str(description or "").lower()]) + if IOMATEX_DUAL_SINK_NAME in haystack or "iomatex dual output" in haystack: + return "dual" + if "hdmi" in haystack: + return "hdmi" + if any(term in haystack for term in AUDIO_TARGETS["analog"]["match_terms"]): + return "analog" + return "" + + +def list_pulse_sinks(): + rc_short, short_out, short_err = pactl(["list", "short", "sinks"], timeout=4) + rc_full, full_out, full_err = pactl(["list", "sinks"], timeout=5) + if rc_short != 0 or rc_full != 0: + return [], trim_output_lines(short_err or full_err or short_out or full_out, limit=8) + + details_by_name = {} + for section in parse_pactl_sections(full_out, "Sink"): + name = section.get("Name", "") + if name: + details_by_name[name] = section + + sinks = [] + for raw in (short_out or "").splitlines(): + parts = raw.split("\t") + if len(parts) < 2: + continue + name = parts[1].strip() + detail = details_by_name.get(name, {}) + description = detail.get("Description", "") + target = classify_sink_target(name, description) + sinks.append( + { + "index": int(parts[0]) if parts[0].isdigit() else None, + "name": name, + "description": description or name, + "state": detail.get("State", parts[-1].strip() if parts else ""), + "target": target, } - pactl_error_lines = trim_output_lines(stderr or stdout, limit=4) - - rc, stdout, stderr = run(["aplay", "-L"], timeout=4) - if rc == 0: - has_default = any(line.strip() == "default" for line in (stdout or "").splitlines()) - return { - "type": "alsa" if has_default else "unknown", - "summary": "ALSA default device is available" if has_default else "Logical ALSA devices listed", - "details": pactl_error_lines + trim_output_lines(stdout, limit=8 - len(pactl_error_lines)), - } - return { - "type": "unknown", - "summary": trim_output_lines(stderr or stdout, limit=1)[0] if trim_output_lines(stderr or stdout, limit=1) else "Audio route unavailable", - "details": pactl_error_lines + trim_output_lines(stderr or stdout, limit=max(1, 4 - len(pactl_error_lines))), - } - - -def read_audio_device_status(card_index, pcm_index): - card = get_alsa_card(card_index) - pcm_root = f"/proc/asound/card{card_index}/pcm{pcm_index}p" - info_path = os.path.join(pcm_root, "info") - status_path = os.path.join(pcm_root, "sub0/status") - hw_params_path = os.path.join(pcm_root, "sub0/hw_params") - - info_text = read_text(info_path).strip() - status_text = read_text(status_path).strip() - hw_params_text = read_text(hw_params_path).strip() - - status_lower = status_text.lower() - if not os.path.exists(pcm_root): - status = "error" - summary = "PCM playback device not found" - elif not status_text: - status = "error" - summary = "Playback status is unavailable" - elif "closed" in status_lower: - status = "available" - summary = "Playback device is idle" - else: - status = "busy" - summary = trim_output_lines(status_text, limit=1)[0] if trim_output_lines(status_text, limit=1) else "Playback device is busy" - - short_description = "" - info_lines = trim_output_lines(info_text, limit=6) - if info_lines: - short_description = info_lines[0] - elif card.get("description"): - short_description = card["description"] - - return { - "status": status, - "summary": summary, - "card_name": card.get("name") or card.get("id") or f"card {card_index}", - "card_id": card.get("id", ""), - "description": short_description, - "info_lines": info_lines, - "status_lines": trim_output_lines(status_text, limit=6), - "hw_params_lines": trim_output_lines(hw_params_text, limit=6), - } - - -AUDIO_TARGETS = { - "hdmi": { - "label": "HDMI audio", - "default_device": "hw:1,0", - "default_card_index": 1, - "pcm_index": 0, - "description": "Digital audio over HDMI output", - "match_terms": ("hdmi",), - }, - "analog": { - "label": "Analog audio", - "default_device": "hw:0,0", - "default_card_index": 0, - "pcm_index": 0, - "description": "Analog audio via rockchip-rk809 codec", - "match_terms": ("rk809", "codec", "analog", "headphone", "rockchip"), - }, -} - -def resolve_audio_target_config(target, cards=None): - template = AUDIO_TARGETS.get(target) - if not template: - return None - - cards = list(cards or parse_alsa_cards()) - selected_card = None - selected_text = "" - for card in cards: - haystack = " ".join( - str(card.get(key, "")).strip().lower() - for key in ("id", "name", "description") ) - if target == "hdmi": - if "hdmi" in haystack: - selected_card = card - selected_text = haystack - break - continue - if "hdmi" in haystack: - continue - if any(term in haystack for term in template.get("match_terms", ())): - selected_card = card - selected_text = haystack + + if not any(item.get("target") == "analog" for item in sinks): + for item in sinks: + if item.get("target") or item.get("name") == IOMATEX_DUAL_SINK_NAME: + continue + item["target"] = "analog" break - card_index = int(selected_card.get("index")) if selected_card else int(template["default_card_index"]) - pcm_index = int(template["pcm_index"]) - pcm_root = f"/proc/asound/card{card_index}/pcm{pcm_index}p" - present = os.path.exists(pcm_root) + return sinks, [] - if not present and not selected_card: - fallback_root = f"/proc/asound/card{template['default_card_index']}/pcm{pcm_index}p" - if os.path.exists(fallback_root): - card_index = int(template["default_card_index"]) - pcm_root = fallback_root - present = True +def resolve_pulse_sink(target, sinks=None): + sinks = list(sinks or list_pulse_sinks()[0]) + if target == "dual": + for sink in sinks: + if sink.get("name") == IOMATEX_DUAL_SINK_NAME or sink.get("target") == "dual": + return sink + return None + for sink in sinks: + if sink.get("target") == target: + return sink + return None + + +def list_pulse_sink_inputs(): + rc_short, short_out, short_err = pactl(["list", "short", "sink-inputs"], timeout=4) + rc_full, full_out, full_err = pactl(["list", "sink-inputs"], timeout=5) + if rc_short != 0: + return [], trim_output_lines(short_err or short_out, limit=6) + + detail_by_index = {} + if rc_full == 0: + for section in parse_pactl_sections(full_out, "Sink Input"): + detail_by_index[section.get("index")] = section + + sink_map = {sink.get("index"): sink.get("name") for sink in list_pulse_sinks()[0] if sink.get("index") is not None} + items = [] + for raw in (short_out or "").splitlines(): + parts = raw.split("\t") + if len(parts) < 5 or not parts[0].isdigit(): + continue + index = int(parts[0]) + sink_index = int(parts[1]) if parts[1].isdigit() else None + detail = detail_by_index.get(index, {}) + application_name = detail.get("application.name", "") + media_name = detail.get("media.name", "") + binary_name = detail.get("application.process.binary", "") + items.append( + { + "index": index, + "sink_index": sink_index, + "sink_name": sink_map.get(sink_index, ""), + "application": application_name or binary_name or "unknown", + "media_name": media_name or application_name or binary_name or "unknown", + } + ) + return items, trim_output_lines(full_err or short_err, limit=6) + + +def parse_audio_route_state(path=IOMATEX_AUDIO_ROUTE_PATH): + target = str(read_env_file(path).get("TARGET", "hdmi")).strip().lower() + if target not in AUDIO_TARGETS: + target = "hdmi" + meta = AUDIO_TARGETS[target] return { + "status": "configured" if os.path.exists(path) else "default", + "path": path, "target": target, - "label": template["label"], - "device": f"hw:{card_index},{pcm_index}", - "card_index": card_index, - "pcm_index": pcm_index, - "description": template["description"], - "detected": bool(selected_card), - "present": present, - "match_text": selected_text, + "label": meta["label"], + "description": meta["description"], } -def render_itscreen_audio_config(target): - config = resolve_audio_target_config(target) - if not config: - raise ValueError("Unknown audio target") - return ( - "pcm.!default {\n" - " type hw\n" - f" card {config['card_index']}\n" - f" device {config['pcm_index']}\n" - "}\n" - "\n" - "ctl.!default {\n" - " type hw\n" - f" card {config['card_index']}\n" - "}\n" +def write_audio_route_state(target): + write_env_file( + IOMATEX_AUDIO_ROUTE_PATH, + { + "TARGET": target, + "UPDATED_AT": utc_now_iso(), + }, ) -def parse_itscreen_audio_config(path=ITSCREEN_AUDIO_CONFIG_PATH): - if not os.path.exists(path): - return {"status": "not_configured", "path": path} - - raw = read_text(path) - card_match = re.search(r"pcm\.\!default\s*\{[^}]*\bcard\s+(\d+)\b", raw, flags=re.IGNORECASE | re.DOTALL) - device_match = re.search(r"pcm\.\!default\s*\{[^}]*\bdevice\s+(\d+)\b", raw, flags=re.IGNORECASE | re.DOTALL) - card_index = int(card_match.group(1)) if card_match else None - pcm_index = int(device_match.group(1)) if device_match else 0 - configured_device = f"hw:{card_index},{pcm_index}" if card_index is not None else "" - - matched_target = "" - config_by_target = {} - for target in AUDIO_TARGETS: - config = resolve_audio_target_config(target) - config_by_target[target] = config - if configured_device and configured_device == config.get("device"): - matched_target = target - - return { - "status": "configured", - "path": path, - "card_index": card_index, - "pcm_index": pcm_index, - "device": configured_device, - "target": matched_target, - "label": config_by_target.get(matched_target, {}).get("label", ""), - "details": trim_output_lines(raw, limit=12), - } +def move_sink_inputs_to(sink_name): + sink_inputs, _ = list_pulse_sink_inputs() + moved = 0 + for item in sink_inputs: + index = item.get("index") + if index is None: + continue + rc, _, _ = pactl(["move-sink-input", str(index), sink_name], timeout=4) + if rc == 0: + moved += 1 + return moved -def write_itscreen_audio_config(target): - config = resolve_audio_target_config(target) - if not config: +def apply_audio_route(target): + if target not in AUDIO_TARGETS: raise ValueError("Unknown audio target") - if not config.get("present"): - raise RuntimeError(f"{config['label']} device is not detected") + if not os.path.exists(IOMATEX_PULSE_APPLY_SCRIPT): + raise RuntimeError(f"PulseAudio apply script is missing: {IOMATEX_PULSE_APPLY_SCRIPT}") - content = render_itscreen_audio_config(target) - directory = os.path.dirname(ITSCREEN_AUDIO_CONFIG_PATH) or "." - os.makedirs(directory, exist_ok=True) - fd, tmp_path = tempfile.mkstemp(prefix=".tmp-audio-", dir=directory, text=True) - try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(content) - os.chmod(tmp_path, 0o644) - try: - shutil.chown(tmp_path, user="itscreen", group="itscreen") - except Exception: - pass - os.replace(tmp_path, ITSCREEN_AUDIO_CONFIG_PATH) - finally: - if os.path.exists(tmp_path): - os.unlink(tmp_path) + write_audio_route_state(target) + rc, stdout, stderr = run([IOMATEX_PULSE_APPLY_SCRIPT], timeout=20, env=pulse_env()) + if rc != 0: + raise RuntimeError((stderr or stdout or "Failed to apply PulseAudio route").strip()) - try: - shutil.chown(ITSCREEN_AUDIO_CONFIG_PATH, user="itscreen", group="itscreen") - except Exception: - pass - service = get_itscreen_service_status() - restarted = False - if service.get("installed") and service.get("active"): - rc, _, stderr = run(["systemctl", "restart", ITSCREEN_SERVICE_UNIT], timeout=20) - if rc != 0: - raise RuntimeError(stderr or "Audio route was written but failed to restart IT-Screen") - restarted = True - invalidate_cache() + sinks, _ = list_pulse_sinks() + sink = resolve_pulse_sink(target, sinks) + moved = 0 + if sink and sink.get("name"): + moved = move_sink_inputs_to(sink["name"]) + + invalidate_cache() return { "ok": True, "target": target, - "label": config["label"], - "device": config["device"], - "path": ITSCREEN_AUDIO_CONFIG_PATH, - "message": f"IT-Screen audio route set to {config['label']}", + "label": AUDIO_TARGETS[target]["label"], + "message": f"IT-Screen audio route set to {AUDIO_TARGETS[target]['label']}", "applied_at": utc_now_iso(), - "service_restarted": restarted, - "route": parse_itscreen_audio_config(), + "moved_sink_inputs": moved, + "route": parse_audio_route_state(), + } + + +def audio_route_info(): + info = parse_pactl_info() + if not info.get("ok"): + return { + "type": "unknown", + "summary": "PulseAudio route unavailable", + "details": info.get("details", []), + } + payload = info.get("info", {}) + sink = payload.get("Default Sink", "") + server_name = payload.get("Server Name", "") + return { + "type": "pulse", + "summary": sink or server_name or "PulseAudio route detected", + "details": info.get("details", []), + "default_sink_name": sink, + "server_name": server_name, + } + + +def scan_direct_alsa_owners(): + owners = [] + seen = set() + for pid in os.listdir("/proc"): + if not pid.isdigit(): + continue + fd_dir = os.path.join("/proc", pid, "fd") + if not os.path.isdir(fd_dir): + continue + cmdline = read_bytes(os.path.join("/proc", pid, "cmdline")).replace(b"\x00", b" ").decode("utf-8", errors="ignore").strip() + if not cmdline: + cmdline = read_text(os.path.join("/proc", pid, "comm")).strip() + status_text = read_text(os.path.join("/proc", pid, "status")) + uid_match = re.search(r"^Uid:\s+(\d+)", status_text, flags=re.MULTILINE) + username = "" + if uid_match: + try: + username = pwd.getpwuid(int(uid_match.group(1))).pw_name + except Exception: + username = uid_match.group(1) + try: + fd_names = os.listdir(fd_dir) + except Exception: + continue + for fd_name in fd_names: + fd_path = os.path.join(fd_dir, fd_name) + try: + target = os.readlink(fd_path) + except Exception: + continue + if not re.match(r"^/dev/snd/pcmC\d+D\d+p$", target): + continue + key = (pid, target) + if key in seen: + continue + seen.add(key) + owners.append( + { + "pid": int(pid), + "user": username, + "device": target, + "command": cmdline or "unknown", + } + ) + owners.sort(key=lambda item: (item.get("device", ""), item.get("pid", 0))) + return owners + + +def build_audio_device(target, sinks): + meta = AUDIO_TARGETS[target] + if target == "dual": + hdmi_sink = resolve_pulse_sink("hdmi", sinks) + analog_sink = resolve_pulse_sink("analog", sinks) + dual_sink = resolve_pulse_sink("dual", sinks) + present = bool(hdmi_sink and analog_sink) + return { + "target": target, + "label": meta["label"], + "description": meta["description"], + "status": "available" if present else "error", + "summary": dual_sink.get("description") if dual_sink else ("Combined PulseAudio route is ready" if present else "Both HDMI and analog PulseAudio sinks are required"), + "sink_name": dual_sink.get("name", "") if dual_sink else "", + "present": present, + } + + sink = resolve_pulse_sink(target, sinks) + return { + "target": target, + "label": meta["label"], + "description": meta["description"], + "status": "available" if sink else "error", + "summary": sink.get("description", "") if sink else "PulseAudio sink is not detected", + "sink_name": sink.get("name", "") if sink else "", + "present": bool(sink), + "state": sink.get("state", "") if sink else "", } @@ -700,115 +790,97 @@ def get_audio_diagnostics(): aplay_l_rc, aplay_l_out, aplay_l_err = run(["aplay", "-l"], timeout=4) aplay_L_rc, aplay_L_out, aplay_L_err = run(["aplay", "-L"], timeout=4) route = audio_route_info() - itscreen_route = parse_itscreen_audio_config() - devices = {} - - for target in AUDIO_TARGETS: - config = resolve_audio_target_config(target, cards) - device_state = read_audio_device_status(config["card_index"], config["pcm_index"]) - if not config.get("present") and device_state.get("status") == "error": - device_state["summary"] = "Audio device is not detected" - device_state["description"] = config["description"] - devices[target] = { - "target": target, - "label": config["label"], - "device": config["device"], - "card_index": config["card_index"], - "pcm_index": config["pcm_index"], - "description": config["description"], - "detected": config["detected"], - "present": config["present"], - **device_state, - } + saved_route = parse_audio_route_state() + sinks, sink_errors = list_pulse_sinks() + sink_inputs, sink_input_errors = list_pulse_sink_inputs() + direct_alsa_owners = scan_direct_alsa_owners() + default_sink = next((sink for sink in sinks if sink.get("name") == route.get("default_sink_name")), None) + running_sink = next((sink for sink in sinks if str(sink.get("state", "")).upper() == "RUNNING"), None) + alsa_fallback_warning = any( + "itscreen" in str(item.get("command", "")).lower() or str(item.get("user", "")).lower() == "itscreen" + for item in direct_alsa_owners + ) return { - "devices": devices, + "devices": {target: build_audio_device(target, sinks) for target in AUDIO_TARGETS}, "parameters": { "aplay_hardware": trim_output_lines(aplay_l_out if aplay_l_rc == 0 else (aplay_l_err or aplay_l_out), limit=12), "aplay_logical": trim_output_lines(aplay_L_out if aplay_L_rc == 0 else (aplay_L_err or aplay_L_out), limit=12), "default_route": route, - "itscreen_route": itscreen_route, + "saved_route": saved_route, + "pulse_server": IOMATEX_PULSE_SERVER, + "pulse_service": IOMATEX_PULSE_SERVICE_UNIT, + "actual_default_sink": { + "name": default_sink.get("name", "") if default_sink else route.get("default_sink_name", ""), + "description": default_sink.get("description", "") if default_sink else "", + }, + "active_running_sink": { + "name": running_sink.get("name", "") if running_sink else "", + "description": running_sink.get("description", "") if running_sink else "", + }, + "sink_inputs": sink_inputs, + "direct_alsa_owners": direct_alsa_owners, + "alsa_fallback_warning": alsa_fallback_warning, "alsa_cards": cards, + "pulse_errors": sink_errors + sink_input_errors, }, "generated_at": utc_now_iso(), } def classify_audio_test_result(returncode, output): - text = (output or "").lower() - if returncode == 0: - return "success" - if "device or resource busy" in text or "busy" in text: - return "busy" - return "failed" + return "success" if returncode == 0 else "failed" + + +def generate_test_wave_file(): + fd, path = tempfile.mkstemp(prefix="iomatex-audio-test-", suffix=".wav") + with os.fdopen(fd, "wb") as raw_fh: + with wave.open(raw_fh, "wb") as wav_fh: + wav_fh.setnchannels(2) + wav_fh.setsampwidth(2) + wav_fh.setframerate(44100) + amplitude = int(32767 * 0.25) + frames = int(44100 * 0.35) + for index in range(frames): + value = int(amplitude * math.sin(2.0 * math.pi * 440.0 * index / 44100.0)) + wav_fh.writeframesraw(struct.pack(" div:not(.key){ + min-width:0; + overflow-wrap:anywhere; +} .pillRow{display:flex;gap:8px;flex-wrap:wrap} .pill{ display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:700;background:var(--surface-muted);color:var(--ink); @@ -628,7 +680,8 @@ html[dir="rtl"] .itscreenLogsActions{ color:var(--ink); line-height:1.6; } -.displayCard,.accessPointCard{grid-column:span 2} +.displayCard{grid-column:1 / -1} +.accessPointCard{grid-column:span 2} .displayHero,.apHero{ margin-top:16px;padding:16px 18px;border-radius:16px;border:1px solid var(--line); display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap; @@ -651,6 +704,26 @@ html[dir="rtl"] .itscreenLogsActions{ .displayHeroLabel{font-size:12px;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:6px} .displayHeroText{font-size:20px;font-weight:700} .displayHeroMeta{display:flex;gap:10px;flex-wrap:wrap;color:var(--muted);font-size:13px} +.displayDetailsRow{ + display:grid; + grid-template-columns:minmax(0,1fr) minmax(260px,340px); + gap:18px; + align-items:start; + margin-top:16px; +} +.displayDetailsMeta{ + min-width:0; + margin-top:0; +} +.displayModePanel{ + border-left:1px solid var(--line); + padding-left:18px; + min-width:0; +} +.displayModeActions{ + margin-top:12px; + justify-content:flex-start; +} .networkOverviewGrid{ display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); @@ -747,6 +820,9 @@ html[dir="rtl"] .itscreenLogsActions{ background:var(--surface-soft); padding:14px; } +.audioParamsMeta{ + grid-template-columns:minmax(110px,140px) minmax(0,1fr); +} .audioDeviceHead{ display:flex; justify-content:space-between; @@ -1420,6 +1496,13 @@ html[dir="rtl"] .itscreenLogsActions{ .brandDevice{width:min(70vw, 260px);max-height:180px} .wideCard,.displayCard,.accessPointCard{grid-column:auto} .audioDeviceGrid{grid-template-columns:1fr} + .displayDetailsRow{grid-template-columns:1fr;align-items:start} + .displayModePanel{ + border-left:0; + border-top:1px solid var(--line); + padding-left:0; + padding-top:14px; + } .displayHeroText{font-size:18px} .itscreenCards{grid-template-columns:1fr} .itscreenLogsToolbar{grid-template-columns:1fr} diff --git a/stage_ui/console_core/frontend/console.i18n.js b/stage_ui/console_core/frontend/console.i18n.js index d95d918..7ec0452 100644 --- a/stage_ui/console_core/frontend/console.i18n.js +++ b/stage_ui/console_core/frontend/console.i18n.js @@ -31,6 +31,7 @@ "Edge Serial Number": "Серийный номер Edge", "Host / IP": "Хост / IP", "Updated": "Обновлено", + "Session": "Сессия", "Primary navigation": "Основная навигация", "Stopping it-screen service before Modbus session": "Остановка сервиса it-screen перед Modbus-сеансом", "Starting it-screen service after Modbus session": "Запуск сервиса it-screen после Modbus-сеанса", @@ -64,6 +65,21 @@ "Missing": "Отсутствует", "Valid": "Корректно", "Invalid": "Некорректно", + "Test": "Тест", + "Local MQTT publish/read test": "Локальный тест MQTT publish/read", + "Publishes an obvious test message to the local broker and reads it back.": "Публикует понятное тестовое сообщение в локальный broker и читает его обратно.", + "Publishing and reading a local MQTT test message...": "Публикуем и читаем локальное MQTT тестовое сообщение...", + "Test message was published and received": "Тестовое сообщение опубликовано и получено", + "Test message was not published": "Тестовое сообщение не опубликовано", + "Test message was not received": "Тестовое сообщение не получено", + "MQTT self-test failed": "MQTT self-test завершился ошибкой", + "MQTT broker test": "Тест MQTT broker", + "Result": "Результат", + "Published at": "Опубликовано", + "Received at": "Получено", + "Latency": "Задержка", + "Topic": "Топик", + "Message": "Сообщение", "Paused": "Пауза", "Live": "Онлайн", "Disconnected": "Отключено", diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index f93cbe2..0a510f6 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -19,6 +19,10 @@ edgeSerialLabel: document.getElementById("edgeSerialLabel"), hostIpLabel: document.getElementById("hostIpLabel"), updatedLabel: document.getElementById("updatedLabel"), + sessionMeter: document.getElementById("sessionMeter"), + sessionMeterLabel: document.getElementById("sessionMeterLabel"), + sessionMeterValue: document.getElementById("sessionMeterValue"), + sessionMeterFill: document.getElementById("sessionMeterFill"), languageMenuLabel: document.getElementById("languageMenuLabel"), themeMenuLabel: document.getElementById("themeMenuLabel"), refreshMenuLabel: document.getElementById("refreshMenuLabel"), @@ -151,6 +155,11 @@ health: null, healthServices: null, healthRequest: null, + mqttSelfTest: { + loading: false, + result: null, + error: "" + }, networkRequest: null, network: null, itscreen: { @@ -291,6 +300,7 @@ error: "", info: "", expiresAt: 0, + sessionStartedAt: 0, sessionRequestId: 0 }, accountPassword: { @@ -781,6 +791,7 @@ if (nodes.edgeSerialLabel) nodes.edgeSerialLabel.textContent = t("Edge Serial Number"); if (nodes.hostIpLabel) nodes.hostIpLabel.textContent = t("Host / IP"); if (nodes.updatedLabel) nodes.updatedLabel.textContent = t("Updated"); + if (nodes.sessionMeterLabel) nodes.sessionMeterLabel.textContent = t("Session"); if (nodes.languageMenuLabel) nodes.languageMenuLabel.textContent = t("Language"); if (nodes.themeMenuLabel) nodes.themeMenuLabel.textContent = t("Theme"); if (nodes.refreshMenuLabel) nodes.refreshMenuLabel.textContent = t("Refresh"); @@ -858,11 +869,13 @@ state.auth.error = ""; state.auth.info = message || t("Authorization required"); state.auth.expiresAt = 0; + state.auth.sessionStartedAt = 0; state.itscreen.loading = false; resetAccountPasswordForm(false); deactivateItscreenLogs({ status: "disconnected" }); closeActionMenu(); setPrimaryUiLocked(true); + updateSessionMeter(); renderActiveTab(); } @@ -876,8 +889,10 @@ state.auth.showPassword = false; state.auth.username = textValue(payload && payload.username, "iomatex"); state.auth.expiresAt = Number(payload && payload.expires_at) || 0; + state.auth.sessionStartedAt = state.auth.expiresAt ? Math.floor(Date.now() / 1000) : 0; setPrimaryUiLocked(!state.auth.authenticated); syncActionMenu(); + updateSessionMeter(); } function resetAccountPasswordForm(keepMessage) { @@ -1429,6 +1444,38 @@ return text || t("unknown"); } + function formatSessionRemaining(seconds) { + const total = Math.max(0, Math.floor(Number(seconds) || 0)); + const minutes = Math.floor(total / 60); + const restSeconds = total % 60; + if (minutes >= 60) { + const hours = Math.floor(minutes / 60); + const hourMinutes = minutes % 60; + return `${hours}h ${hourMinutes}m`; + } + if (minutes > 0) return `${minutes}m ${String(restSeconds).padStart(2, "0")}s`; + return `${restSeconds}s`; + } + + function updateSessionMeter() { + if (!nodes.sessionMeter || !nodes.sessionMeterFill || !nodes.sessionMeterValue) return; + if (!state.auth.authenticated || !state.auth.expiresAt) { + nodes.sessionMeter.hidden = true; + return; + } + const now = Math.floor(Date.now() / 1000); + const expiresAt = Number(state.auth.expiresAt) || 0; + const startedAt = Number(state.auth.sessionStartedAt) || now; + const total = Math.max(1, expiresAt - startedAt); + const remaining = Math.max(0, expiresAt - now); + const percent = Math.max(0, Math.min(100, (remaining / total) * 100)); + nodes.sessionMeter.hidden = false; + nodes.sessionMeterValue.textContent = formatSessionRemaining(remaining); + nodes.sessionMeterFill.style.width = `${percent}%`; + nodes.sessionMeter.classList.toggle("is-warning", remaining <= 10 * 60); + nodes.sessionMeter.classList.toggle("is-danger", remaining <= 2 * 60); + } + function formatInterval(value, disabledLabel = "Disabled") { const seconds = Number(value); if (!Number.isFinite(seconds)) return "—"; @@ -1461,13 +1508,9 @@ { label: t("Server"), value: itscreenServerValue(payload) }, { label: t("Device ID"), value: notSpecified(payload && payload.device_id) }, { label: t("Device name"), value: notSpecified(payload && payload.device_name) }, - { label: t("Username"), value: notSpecified(payload && payload.username) }, { label: t("Password"), value: itscreenMaskedPassword(payload) }, { label: t("Organization"), value: notSpecified(payload && payload.organization) }, { label: t("Token"), value: notSpecified(payload && payload.token) }, - { label: t("Detected contract"), value: itscreenContractLabel(payload) }, - { label: t("Request topic"), value: notSpecified(payload && payload.request_topic) }, - { label: t("Response topic"), value: notSpecified(payload && payload.response_topic) }, { label: t("Registered"), value: itscreenBooleanLabel(!!(payload && payload.registered), "registered") }, { label: t("Logged"), value: itscreenBooleanLabel(!!(payload && payload.logged), "logged") }, { label: t("Password state"), value: displayValue(payload && payload.password_state, t("Not specified")) } @@ -1565,7 +1608,11 @@ const audio = card.audio_diagnostics || {}; const audioDevices = audio.devices || {}; const audioParams = audio.parameters || {}; - const itscreenRoute = audioParams.itscreen_route || {}; + const savedRoute = audioParams.saved_route || {}; + const actualDefaultSink = audioParams.actual_default_sink || {}; + const runningSink = audioParams.active_running_sink || {}; + const pulseErrors = Array.isArray(audioParams.pulse_errors) ? audioParams.pulse_errors : []; + const alsaFallbackWarning = !!audioParams.alsa_fallback_warning; const displayMode = card.display_mode || {}; const connectorsOpen = !!state.displayUi.connectorsOpen; const busyMode = textValue(state.displayUi.busyMode, ""); @@ -1599,15 +1646,15 @@ const busyRoute = audioBusyRouteTarget === device.target; const deviceStatusMeta = audioStatusMeta(device && device.status); const unavailable = textValue(device && device.status, "error").toLowerCase() === "error"; - const routeActive = textValue(itscreenRoute.target, "") === textValue(device && device.target, ""); + const routeActive = textValue(savedRoute.target, "") === textValue(device && device.target, ""); return `
${esc(displayValue(device.label, t("Audio device")))}
${esc(textValue(device.description, t("Not available")))}
-
${esc(t("ALSA device: {device}", { device: textValue(device.device, t("Not available")) }))}
-
${esc(routeActive ? t("IT-Screen route: active") : t("IT-Screen route: inactive"))}
+
${esc(t("Pulse sink: {device}", { device: textValue(device.sink_name, t("Not available")) }))}
+
${esc(routeActive ? t("Saved route: active") : t("Saved route: inactive"))}
${esc(unavailable ? t("Unavailable") : deviceStatusMeta.label)}
@@ -1662,23 +1709,36 @@ ${esc(t("Primary: {name}", { name: textValue(status.connector, t("Not available")) }))} -
${renderKeyValueRows(details)}
-
-
${esc(t("Display mode"))}
-
${esc(translateStatusValue(displayMode.status_text) || t("Display mode is unknown"))}
-
${esc(displayMode.hdmi_connected ? t("HDMI monitor detected") : t("HDMI monitor not detected"))}
-
- - -
+
+
${renderKeyValueRows(details)}
+
${esc(t("Audio diagnostics"))}
-
${esc(t("IT-Screen default route: {route}", { route: textValue(itscreenRoute.label || itscreenRoute.device, t("Not configured")) }))}
- ${renderAudioDevice(audioDevices.hdmi || { target: "hdmi", label: "HDMI audio", device: "hw:1,0" }, "Test HDMI sound")} - ${renderAudioDevice(audioDevices.analog || { target: "analog", label: "Analog audio", device: "hw:0,0" }, "Test Analog sound")} + ${renderAudioDevice(audioDevices.hdmi || { target: "hdmi", label: "HDMI audio" }, "Test HDMI sound")} + ${renderAudioDevice(audioDevices.analog || { target: "analog", label: "Analog audio" }, "Test Analog sound")} + ${renderAudioDevice(audioDevices.dual || { target: "dual", label: "HDMI + Analog" }, "Test Dual sound")} +
+
${esc(t("Audio diagnostics"))}
+
${renderKeyValueRows([ + { label: t("Saved IT-Screen route"), value: textValue(savedRoute.label, t("Not configured")) }, + { label: t("Actual PulseAudio default sink"), value: textValue(actualDefaultSink.description || actualDefaultSink.name, t("Not available")) }, + { label: t("Active RUNNING sink"), value: textValue(runningSink.description || runningSink.name, t("Not available")) }, + { label: t("PulseAudio server"), value: textValue(audioParams.pulse_server, t("Not available")) } + ])}
+ ${alsaFallbackWarning ? `
${esc(t("it-screen is using direct ALSA fallback. PulseAudio mixer is bypassed."))}
` : ""} +
+ ${pulseErrors.length ? `
${esc(pulseErrors.join("\n"))}
` : ""}
@@ -1932,6 +1992,53 @@ `; } + function renderMqttSelfTestSummary(title) { + const result = (state.mqttSelfTest && state.mqttSelfTest.result) || {}; + if (result.status !== "ok") return ""; + const rows = [ + { label: t("Result"), value: t(result.status_text || "Test message was published and received") }, + { label: t("Received at"), value: formatUtc(result.received_at) }, + { label: t("Latency"), value: result.latency_ms === null || result.latency_ms === undefined ? t("Not available") : `${result.latency_ms} ms` }, + { label: t("Topic"), value: textValue(result.topic, t("Not available")) } + ]; + return ` +
+
${esc(t(title))}
+ +
${renderKeyValueRows(rows)}
+
+ `; + } + + function renderMqttSelfTestPanel() { + const selfTest = state.mqttSelfTest || {}; + const result = selfTest.result || {}; + const hasResult = !!result.status || !!selfTest.error; + const tone = result.status === "ok" ? "success" : "error"; + const rows = result.status ? [ + { label: t("Result"), value: t(result.status_text || (result.status === "ok" ? "Test message was published and received" : "Test message was not received")) }, + { label: t("Published at"), value: formatUtc(result.published_at) }, + { label: t("Received at"), value: formatUtc(result.received_at) }, + { label: t("Latency"), value: result.latency_ms === null || result.latency_ms === undefined ? t("Not available") : `${result.latency_ms} ms` }, + { label: t("Topic"), value: textValue(result.topic, t("Not available")) }, + { label: t("Message"), value: textValue(result.received_message || result.message, t("Not available")) } + ] : []; + return ` +
+
+
+
${esc(t("Local MQTT publish/read test"))}
+
${esc(t("Publishes an obvious test message to the local broker and reads it back."))}
+
+ +
+ ${selfTest.loading ? `` : ""} + ${hasResult && !selfTest.loading ? `` : ""} + ${rows.length ? `
${renderKeyValueRows(rows)}
` : ""} +
+ `; + } + function renderServiceCard(card) { if (card.id === "itscreen") return renderItscreenServiceCard(card); if (card.id === "display") return renderDisplayCard(card); @@ -1942,6 +2049,10 @@ const warnings = Array.isArray(card.warnings) ? card.warnings : []; 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"; return `
@@ -1957,6 +2068,8 @@
${esc(t("Status"))}
${esc(displayValue(card.status_text, "-"))}
${details.length ? `
${esc(t("Details"))}
${renderKeyValueRows(details)}
` : ""} + ${showMqttSelfTest ? renderMqttSelfTestPanel() : ""} + ${showMqttBridgeSelfTestResult ? renderMqttSelfTestSummary("MQTT broker test") : ""}
${esc(t("Flags"))}
@@ -4698,6 +4811,25 @@ } }; + window.__runMqttSelfTest = async function () { + if (state.mqttSelfTest.loading) return; + state.mqttSelfTest.loading = true; + state.mqttSelfTest.error = ""; + state.mqttSelfTest.result = null; + if (state.activeTab === "health") renderActiveTab(); + try { + const payload = await fetchJsonAllowLogicalFailure("/api/mqtt/self-test", { cache: "no-store" }); + state.mqttSelfTest.result = payload; + state.mqttSelfTest.error = payload.ok === false ? (payload.error || payload.status_text || t("MQTT self-test failed")) : ""; + } catch (error) { + state.mqttSelfTest.result = null; + state.mqttSelfTest.error = error.message || t("MQTT self-test failed"); + } finally { + state.mqttSelfTest.loading = false; + if (state.activeTab === "health") renderActiveTab(); + } + }; + window.__toggleTunnelGroup = function (groupKey) { if (!groupKey) return; state.reverseTunnelUi.openGroups[groupKey] = !state.reverseTunnelUi.openGroups[groupKey]; @@ -4773,7 +4905,8 @@ body: JSON.stringify({ target }) }); state.audioActions.results[target] = payload; - showToast(payload.result === "success" ? "success" : (payload.result === "busy" ? "warn" : "error"), payload.error || t("{target} audio test: {result}", { target: target === "hdmi" ? t("HDMI") : t("Analog"), result: payload.result || t("unknown") })); + const targetLabel = target === "hdmi" ? t("HDMI") : (target === "analog" ? t("Analog") : t("HDMI + Analog")); + showToast(payload.result === "success" ? "success" : "error", payload.error || t("{target} audio test: {result}", { target: targetLabel, result: payload.result || t("unknown") })); await loadHealth(); } catch (error) { state.audioActions.results[target] = { @@ -5807,6 +5940,7 @@ applyTheme(loadThemePreference()); syncActionMenu(); setPrimaryUiLocked(true); + updateSessionMeter(); renderActiveTab(); loadAuthSession().then(() => { if (!state.auth.authenticated) return; @@ -5822,4 +5956,5 @@ if (state.activeTab === "tscreen") return; loadForActiveTab({ preserveEditing: true }).catch(() => {}); }, 15000); + setInterval(updateSessionMeter, 30000); })(); diff --git a/stage_ui/console_core/frontend/index.html b/stage_ui/console_core/frontend/index.html index 4c6bc93..a400f56 100644 --- a/stage_ui/console_core/frontend/index.html +++ b/stage_ui/console_core/frontend/index.html @@ -49,6 +49,15 @@
Updated - +
diff --git a/stage_ui/console_core/providers/00_core_services.py b/stage_ui/console_core/providers/00_core_services.py index 238ad6a..8f4f8c9 100644 --- a/stage_ui/console_core/providers/00_core_services.py +++ b/stage_ui/console_core/providers/00_core_services.py @@ -494,6 +494,7 @@ def mqtt_bridge_card(ctx): installed = ctx["any_exists"]([ "/etc/iomatex/mqtt_bridge.env", "/usr/local/sbin/iomatex-mqtt-apply", + "/etc/systemd/system/iomatex-mqtt-health.timer", "/etc/systemd/system/iomatex-mqtt-bridge.service", "/etc/systemd/system/iomatex-mqtt-bridge.path", ]) @@ -502,14 +503,15 @@ def mqtt_bridge_card(ctx): ctx["file_exists"]("/etc/iomatex/mqtt_bridge.env") and ctx["file_exists"]("/usr/local/sbin/iomatex-mqtt-apply") and ctx["any_exists"]([ + "/etc/systemd/system/iomatex-mqtt-health.timer", "/etc/systemd/system/iomatex-mqtt-bridge.service", "/etc/systemd/system/iomatex-mqtt-bridge.path", ]) ) remote_host = str(env.get("REMOTE_HOST", "")).strip() - bridge_service = ctx["systemd_unit"]("iomatex-mqtt-bridge.service") - bridge_path = ctx["systemd_unit"]("iomatex-mqtt-bridge.path") - active = bool(enabled and bridge_conf_exists and (bridge_service["active"] or bridge_path["active"])) + 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"]) warnings = [] errors = [] if installed and not enabled: @@ -518,13 +520,13 @@ 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") - state, status_text = _lifecycle(installed, configured, active, failed=bridge_service["active_state"] == "failed") + 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" return _service_card( "mqtt_bridge", "MQTT Bridge", - "iomatex-mqtt-bridge.service", + "mosquitto.service", installed, configured, active, @@ -536,8 +538,8 @@ def mqtt_bridge_card(ctx): {"label": "Enable bridge", "value": "Yes" if enabled else "No"}, {"label": "Remote host", "value": remote_host or "-"}, {"label": "Bridge config", "value": "Present" if bridge_conf_exists else "Missing"}, - {"label": "Path watcher", "value": bridge_path["active_state"] or "inactive"}, - {"label": "Apply unit", "value": bridge_service["active_state"] or "inactive"}, + {"label": "Broker unit", "value": mosquitto["active_state"] or "inactive"}, + {"label": "Health timer", "value": health_timer["active_state"] or "inactive"}, ], ) @@ -988,5 +990,4 @@ def get_cards(ctx): reverse_tunnel_card(ctx), access_point_card(ctx), display_card(ctx), - placeholder_card("edge_api", "Edge API"), ]