unit It-Screen App registartion data revised

This commit is contained in:
Andrei Smaliak 2026-04-25 10:32:11 +04:00
parent dbf660e149
commit b88b8e12a9
3 changed files with 205 additions and 60 deletions

View File

@ -39,7 +39,7 @@ 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.10"
UI_VERSION = "V 2.2.17"
DEFAULT_CONFIG = {
"bind": "0.0.0.0",
@ -421,21 +421,74 @@ def read_audio_device_status(card_index, pcm_index):
AUDIO_TARGETS = {
"hdmi": {
"label": "HDMI audio",
"device": "hw:1,0",
"card_index": 1,
"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",
"device": "hw:0,0",
"card_index": 0,
"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
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)
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
return {
"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,
}
def get_audio_diagnostics():
cards = parse_alsa_cards()
aplay_l_rc, aplay_l_out, aplay_l_err = run(["aplay", "-l"], timeout=4)
@ -443,8 +496,12 @@ def get_audio_diagnostics():
route = audio_route_info()
devices = {}
for target, config in AUDIO_TARGETS.items():
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"],
@ -452,6 +509,8 @@ def get_audio_diagnostics():
"card_index": config["card_index"],
"pcm_index": config["pcm_index"],
"description": config["description"],
"detected": config["detected"],
"present": config["present"],
**device_state,
}
@ -477,11 +536,22 @@ def classify_audio_test_result(returncode, output):
def perform_audio_test(target):
config = AUDIO_TARGETS.get(target)
config = resolve_audio_target_config(target)
if not config:
raise ValueError("Unknown audio target")
if not command_exists("speaker-test"):
raise RuntimeError("speaker-test command is not available")
if not config.get("present"):
return {
"ok": False,
"target": target,
"device": config["device"],
"result": "failed",
"returncode": None,
"error": f"{config['label']} device is not detected",
"output": [f"{config['label']} device is not detected", f"Expected PCM: card{config['card_index']}/pcm{config['pcm_index']}p"],
"tested_at": utc_now_iso(),
}
cmd = [
"speaker-test",
@ -506,15 +576,19 @@ def perform_audio_test(target):
check=False,
)
output = "\n".join(part for part in [(proc.stdout or "").strip(), (proc.stderr or "").strip()] if part).strip()
return {
result = classify_audio_test_result(proc.returncode, output)
payload = {
"ok": proc.returncode == 0,
"target": target,
"device": config["device"],
"result": classify_audio_test_result(proc.returncode, output),
"result": result,
"returncode": proc.returncode,
"output": trim_output_lines(output, limit=10),
"tested_at": utc_now_iso(),
}
if not payload["ok"]:
payload["error"] = trim_output_lines(output, limit=1)[0] if trim_output_lines(output, limit=1) else f"{config['label']} test failed"
return payload
except subprocess.TimeoutExpired as exc:
output = "\n".join(part for part in [(exc.stdout or "").strip(), (exc.stderr or "").strip()] if part).strip()
return {
@ -523,6 +597,7 @@ def perform_audio_test(target):
"device": config["device"],
"result": "failed",
"returncode": None,
"error": "Audio test timed out",
"output": trim_output_lines(output or "Audio test timed out", limit=10),
"tested_at": utc_now_iso(),
}

View File

@ -29,10 +29,20 @@ 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": "device/settings"},
{"contract_prefix": "universal", "base_prefix": "$devices/settings"},
)
DEFAULT_CONTRACT_PREFIX = SETTINGS_CONTRACTS[0]["contract_prefix"]
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",
}
def _debug(message):
@ -81,11 +91,11 @@ def _host_contract_hint(host):
value = str(host or "").strip().lower()
if not value:
return ""
if "iomatex" in value:
return "iomatex"
if "it-screen" in value:
if value in ITSCREEN_HOSTS:
return "it-screen"
return ""
if value in IOMATEX_HOSTS:
return "iomatex"
return "universal"
def get_candidate_device_topics(device_id, server_host_hint=None):
@ -125,7 +135,20 @@ 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()
for candidate in (preferred_contract, _host_contract_hint(server_host_hint), DEFAULT_CONTRACT_PREFIX):
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)
@ -305,22 +328,7 @@ def _load_registration_from_itscreen_config(device_id, persisted=None):
def _candidate_login_passwords(device_id, persisted=None):
candidates = []
seen = set()
def add(value):
text = _truncate_empty(value)
if not text or text in seen:
return
seen.add(text)
candidates.append(text)
persisted = persisted or {}
add((persisted or {}).get("password"))
config_payload = _load_registration_from_itscreen_config(device_id, persisted=persisted)
add(config_payload.get("password"))
add(LOGIN_PASSWORD)
return candidates
return [LOGIN_PASSWORD]
def _extract_response_payload(response_text):
@ -503,25 +511,34 @@ class MqttSettingsSession:
self.connected = threading.Event()
self.error = None
self.contract_meta = dict(contract_meta or {})
self._subscribe_lock = threading.Lock()
self._subscribe_status = {}
self._response_sub_mid = None
self.client = mqtt.Client(client_id=f"console-core-{device_id}-{int(time.time() * 1000)}", clean_session=True)
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
self.client.on_subscribe = self._on_subscribe
def _on_connect(self, client, userdata, flags, rc):
if rc != 0:
self.error = f"MQTT connect failed ({rc})"
return
result, _ = client.subscribe(self.contract_meta["response_topic"], qos=0)
result, mid = client.subscribe(self.contract_meta["response_topic"], qos=0)
if result != mqtt.MQTT_ERR_SUCCESS:
self.error = "Device settings service is unavailable"
return
self._mark_subscribe_pending(mid)
self._response_sub_mid = mid
self.connected.set()
def _on_disconnect(self, client, userdata, rc):
if rc not in (0, None) and not self.error:
self.error = "Device settings service is unavailable"
def _on_subscribe(self, client, userdata, mid, granted_qos):
self._mark_subscribe_done(mid)
def _on_message(self, client, userdata, msg):
raw = msg.payload.decode("utf-8", errors="ignore")
try:
@ -530,6 +547,28 @@ class MqttSettingsSession:
payload = {"__invalid_json__": raw}
self.queue.put(payload)
def _mark_subscribe_pending(self, mid):
with self._subscribe_lock:
self._subscribe_status[mid] = self._subscribe_status.get(mid, False)
def _mark_subscribe_done(self, mid):
with self._subscribe_lock:
self._subscribe_status[mid] = True
def _wait_for_subscribe(self, mid, timeout=2.0):
if mid is None:
raise RuntimeError("Device settings service is unavailable")
deadline = time.time() + timeout
while time.time() < deadline:
if self.error:
raise RuntimeError(self.error)
with self._subscribe_lock:
done = self._subscribe_status.get(mid)
if done is True:
return
time.sleep(0.05)
raise TimeoutError("MQTT subscribe timeout")
def __enter__(self):
host, port = _parse_mqtt_url(MQTT_URL)
try:
@ -540,6 +579,7 @@ class MqttSettingsSession:
if not self.connected.wait(5):
self.close()
raise RuntimeError(self.error or "Device settings service is unavailable")
self._wait_for_subscribe(self._response_sub_mid, timeout=2.0)
return self
def __exit__(self, exc_type, exc, tb):
@ -626,9 +666,11 @@ class MqttSettingsSession:
def read_retained_topic_payload(self, topic, timeout=1.5):
self._drain()
result, _ = self.client.subscribe(topic, qos=0)
result, mid = self.client.subscribe(topic, qos=0)
if result != mqtt.MQTT_ERR_SUCCESS:
raise RuntimeError("Device registration topic subscribe failed")
self._mark_subscribe_pending(mid)
self._wait_for_subscribe(mid, timeout=2.0)
deadline = time.time() + timeout
try:
while time.time() < deadline:
@ -748,16 +790,7 @@ def get_registration_status():
try:
def _status_flow(session, _contract_meta):
session.login(_candidate_login_passwords(state["device_id"], persisted))
server_state = session.get_server_state()
device_state = _read_device_registration_snapshot(
session,
state["device_id"],
server_host_hint=_truncate_empty(server_state.get("host")) or _truncate_empty(server_state.get("server")),
)
return {
"server_state": server_state,
"device_state": device_state,
}
return session.get_server_state()
contract_meta, status_flow = _with_settings_contract(
state["device_id"],
@ -766,9 +799,7 @@ def get_registration_status():
_status_flow,
server_host_hint=state.get("host", ""),
)
server_state = status_flow["server_state"]
device_state = status_flow.get("device_state") or {}
merged_state = _merge_device_registration_payload(server_state, device_state)
merged_state = status_flow if isinstance(status_flow, dict) else {}
current = {
"host": _truncate_empty(merged_state.get("host")) or _truncate_empty(merged_state.get("server")),
"username": _truncate_empty(merged_state.get("username")),

View File

@ -44,7 +44,7 @@
{ mode: "test_by", label: "TEST BY", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" }
];
const UI_VERSION = "V 2.2.10";
const UI_VERSION = "V 2.2.17";
const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250;
@ -279,7 +279,8 @@
busy: false,
error: "",
info: "",
expiresAt: 0
expiresAt: 0,
sessionRequestId: 0
},
accountPassword: {
busy: false,
@ -1067,12 +1068,18 @@
function itscreenContractLabel(payload) {
const contract = textValue(payload && payload.contract_prefix, "");
if (contract === "it-screen") return "it-screen";
if (contract === "iomatex") return "iomatex";
if (contract === "universal") return "device/settings";
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");
}
function itscreenMaskedPassword(payload) {
const password = textValue(payload && payload.password, "");
if (!password) return t("Not specified");
return "******";
}
function itscreenResponseDetails() {
return textValue(state.itscreen.details, "");
}
@ -1141,7 +1148,7 @@
{ 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: notSpecified(payload && payload.password) },
{ 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) },
@ -1267,6 +1274,8 @@
function renderAudioDevice(device, buttonLabel) {
const testMeta = audioTestMeta(device && device.target);
const busy = audioBusyTarget === device.target;
const deviceStatusMeta = audioStatusMeta(device && device.status);
const unavailable = textValue(device && device.status, "error").toLowerCase() === "error";
return `
<article class="audioDeviceCard">
<div class="audioDeviceHead">
@ -1275,9 +1284,11 @@
<div class="audioDeviceSubhead">${esc(textValue(device.description, t("Not available")))}</div>
<div class="audioDeviceMeta">${esc(t("ALSA device: {device}", { device: textValue(device.device, t("Not available")) }))}</div>
</div>
<span class="actionBadge actionBadge-${deviceStatusMeta.tone}">${esc(unavailable ? t("Unavailable") : deviceStatusMeta.label)}</span>
</div>
${device && device.summary ? `<div class="audioDeviceMeta">${esc(device.summary)}</div>` : ""}
<div class="audioActionRow">
<button class="actionBtn" type="button" ${busy ? "disabled" : ""} onclick="window.__runAudioTest('${esc(device.target)}')">${esc(busy ? t("Testing...") : t(buttonLabel))}</button>
<button class="actionBtn" type="button" ${(busy || unavailable) ? "disabled" : ""} onclick="window.__runAudioTest('${esc(device.target)}')">${esc(busy ? t("Testing...") : t(buttonLabel))}</button>
</div>
${testMeta.hasResult ? `<div class="audioTestSummary"><span class="actionBadge actionBadge-${testMeta.tone}">${esc(testMeta.label)}</span><span class="audioTestTime">${esc(testMeta.testedAt)}</span></div>` : ""}
${testMeta.output.length ? `<pre class="diagBlock testOutput">${esc(testMeta.output.join("\n"))}</pre>` : ""}
@ -2059,7 +2070,7 @@
<div class="key">${esc(t("Device ID"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.device_id))}</div>
<div class="key">${esc(t("Device name"))}</div><div class="wrapValue">${esc(notSpecified(payload && payload.device_name))}</div>
<div class="key">${esc(t("Username"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.username))}</div>
<div class="key">${esc(t("Password"))}</div><div class="wrapValue monoValue">${esc(notSpecified(payload && payload.password))}</div>
<div class="key">${esc(t("Password"))}</div><div class="wrapValue monoValue">${esc(itscreenMaskedPassword(payload))}</div>
<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>
@ -3563,6 +3574,8 @@
async function loadAuthSession(options = {}) {
const silent = !!options.silent;
const requestId = (Number(state.auth.sessionRequestId) || 0) + 1;
state.auth.sessionRequestId = requestId;
if (!silent) {
state.auth.loading = true;
state.auth.error = "";
@ -3575,6 +3588,7 @@
if (!response.ok) {
throw new Error(payload.error || `HTTP ${response.status}`);
}
if (requestId !== state.auth.sessionRequestId) return payload;
if (payload.authenticated) {
applyAuthSession(payload);
} else {
@ -3582,6 +3596,7 @@
}
return payload;
} catch (error) {
if (requestId !== state.auth.sessionRequestId) throw error;
setAuthRequired(t("Authorization required"));
throw error;
}
@ -3602,6 +3617,21 @@
return payload;
}
async function fetchJsonAllowLogicalFailure(url, options) {
const response = await fetch(url, options || { cache: "no-store" });
const payload = await response.json().catch(() => ({}));
if (response.status === 401) {
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"));
}
if (!response.ok) {
throw new Error(payload.error || `HTTP ${response.status}`);
}
return payload;
}
function replaceServiceCard(nextCard) {
if (!nextCard || !state.healthServices || !Array.isArray(state.healthServices.services)) return;
state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card));
@ -3798,13 +3828,13 @@
state.itscreen.details = (payload && payload.details) || "";
state.itscreen.registrationLoadedAt = Date.now();
syncItscreenFormFromBackend();
if (state.activeTab === "tscreen") renderActiveTab();
if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab();
return state.itscreen.data.registration;
} catch (error) {
if (error && error.name === "AbortError") return itscreenRegistration();
state.itscreen.error = error.message || t("Cloud registration status is unavailable");
state.itscreen.details = "";
if (state.activeTab === "tscreen") renderActiveTab();
if (state.activeTab === "tscreen" || state.activeTab === "health") renderActiveTab();
return itscreenRegistration();
} finally {
state.itscreen.registrationRequestController = null;
@ -3837,7 +3867,7 @@
state.itscreen.loadedAt = Date.now();
if (!state.itscreen.registrationLoadedAt || force) {
window.setTimeout(() => {
if (state.activeTab === "tscreen" && state.auth.authenticated) {
if ((state.activeTab === "tscreen" || state.activeTab === "health") && state.auth.authenticated) {
loadItscreenRegistration({ force, maxAgeMs: 30000 }).catch(() => {});
}
}, 0);
@ -4181,14 +4211,14 @@
state.audioActions.busyTarget = target;
if (state.activeTab === "health") renderActiveTab();
try {
const payload = await fetchJson("/api/actions/audio-test", {
const payload = await fetchJsonAllowLogicalFailure("/api/actions/audio-test", {
method: "POST",
cache: "no-store",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ target })
});
state.audioActions.results[target] = payload;
showToast(payload.result === "success" ? "success" : (payload.result === "busy" ? "warn" : "error"), t("{target} audio test: {result}", { target: target === "hdmi" ? t("HDMI") : t("Analog"), result: payload.result || t("unknown") }));
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") }));
await loadHealth();
} catch (error) {
state.audioActions.results[target] = {
@ -4960,6 +4990,7 @@
window.__authSubmit = async function (event) {
if (event && typeof event.preventDefault === "function") event.preventDefault();
if (state.auth.busy || state.auth.loading) return;
state.auth.sessionRequestId = (Number(state.auth.sessionRequestId) || 0) + 1;
const username = textValue(state.auth.username, "iomatex");
const password = state.auth.password || "";
if (!password.trim()) {
@ -4979,12 +5010,20 @@
body: JSON.stringify({ username, password })
});
applyAuthSession(payload);
state.auth.loading = true;
renderActiveTab();
try {
await loadForActiveTab();
} finally {
state.auth.loading = false;
}
if (state.activeTab === "tscreen") {
activateItscreenLogs().catch(() => {});
}
renderActiveTab();
} catch (error) {
state.auth.busy = false;
state.auth.loading = false;
state.auth.authenticated = false;
state.auth.error = error.message || t("Invalid password");
renderActiveTab();