Init
This commit is contained in:
@@ -0,0 +1,325 @@
|
||||
const APP_VERSION = "1.0.0";
|
||||
const hud = document.querySelector("#hud");
|
||||
const wall = document.querySelector("#wall");
|
||||
const canvas = document.querySelector("#motionCanvas");
|
||||
const ctx = canvas.getContext("2d", { alpha: true });
|
||||
const clock = document.querySelector("#clock");
|
||||
const version = document.querySelector("#version");
|
||||
const sceneTitle = document.querySelector("#sceneTitle");
|
||||
const tileId = location.pathname.startsWith("/output/") ? location.pathname.split("/").pop() : "left";
|
||||
|
||||
const sceneNames = {
|
||||
overview: "LED 大屏投放平台",
|
||||
energy: "能源驾驶舱",
|
||||
security: "安防态势",
|
||||
};
|
||||
|
||||
let ws = null;
|
||||
let tile = null;
|
||||
let state = null;
|
||||
let paused = false;
|
||||
let pageIndex = 0;
|
||||
let clockOffsetMs = 0;
|
||||
let bestRttMs = Number.POSITIVE_INFINITY;
|
||||
let pendingCommands = new Map();
|
||||
let frameCount = 0;
|
||||
let droppedFrames = 0;
|
||||
let lastFrameAt = performance.now();
|
||||
let lastFpsAt = performance.now();
|
||||
let fps = 0;
|
||||
let frameTimeMs = 0;
|
||||
let nodeId = sessionStorage.getItem("led-platform-node-id");
|
||||
|
||||
if (!nodeId) {
|
||||
const randomId = crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(16).slice(2);
|
||||
nodeId = `${tileId}-${randomId}`;
|
||||
sessionStorage.setItem("led-platform-node-id", nodeId);
|
||||
}
|
||||
|
||||
function clientNowMs() {
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
function serverNowMs() {
|
||||
return clientNowMs() + clockOffsetMs;
|
||||
}
|
||||
|
||||
async function bootstrap() {
|
||||
const res = await fetch(`/api/bootstrap/${tileId}`);
|
||||
const data = await res.json();
|
||||
tile = data.tile;
|
||||
applyState(data.state);
|
||||
buildStaticContent();
|
||||
layout();
|
||||
connectWs();
|
||||
requestAnimationFrame(renderLoop);
|
||||
}
|
||||
|
||||
function layout() {
|
||||
if (!tile) return;
|
||||
const scale = Math.min(window.innerWidth / tile.width, window.innerHeight / tile.height);
|
||||
document.documentElement.style.setProperty("--wall-width", `${tile.wall_width}px`);
|
||||
document.documentElement.style.setProperty("--wall-height", `${tile.wall_height}px`);
|
||||
document.documentElement.style.setProperty("--scale", `${scale}`);
|
||||
document.documentElement.style.setProperty("--offset-x", `${-tile.x * scale}px`);
|
||||
document.documentElement.style.setProperty("--offset-y", `${-tile.y * scale}px`);
|
||||
canvas.width = tile.wall_width;
|
||||
canvas.height = tile.wall_height;
|
||||
updateHud();
|
||||
}
|
||||
|
||||
function buildStaticContent() {
|
||||
document.querySelector("#overviewKpis").innerHTML = [
|
||||
["渲染模式", "Local GPU"],
|
||||
["同步方式", "Timeline"],
|
||||
["逻辑宽度", "14,880"],
|
||||
["逻辑高度", "3,510"],
|
||||
["左/右分区", "7,440"],
|
||||
["目标帧率", "60 FPS"],
|
||||
].map(([label, value]) => `<article class="kpi"><span>${label}</span><strong>${value}</strong></article>`).join("");
|
||||
|
||||
const bars = document.querySelector("#overviewBars");
|
||||
bars.innerHTML = "";
|
||||
for (let i = 0; i < 32; i += 1) {
|
||||
const bar = document.createElement("div");
|
||||
bar.className = "bar";
|
||||
bar.style.height = `${180 + ((i * 137) % 760)}px`;
|
||||
bars.append(bar);
|
||||
}
|
||||
|
||||
document.querySelector("#cameraGrid").innerHTML = Array.from({ length: 8 }, (_, index) => {
|
||||
const id = String(index + 1).padStart(2, "0");
|
||||
return `<article class="camera"><strong>CAM-${id}</strong><span>在线 | 1080P | 低延迟</span></article>`;
|
||||
}).join("");
|
||||
|
||||
document.querySelector("#alertRail").innerHTML = [
|
||||
"北侧通道人员聚集",
|
||||
"机房门禁异常",
|
||||
"消防通道占用",
|
||||
"视频质量波动",
|
||||
].map((item) => `<article class="alert">${item}</article>`).join("");
|
||||
}
|
||||
|
||||
function applyState(nextState) {
|
||||
state = nextState;
|
||||
version.textContent = `v${state.version}`;
|
||||
setScene(state.active_view);
|
||||
}
|
||||
|
||||
function setScene(view) {
|
||||
const normalized = view || "overview";
|
||||
document.querySelectorAll(".scene").forEach((scene) => {
|
||||
scene.classList.toggle("active", scene.dataset.view === normalized);
|
||||
});
|
||||
sceneTitle.textContent = sceneNames[normalized] || sceneNames.overview;
|
||||
pulse();
|
||||
}
|
||||
|
||||
function scheduleAt(applyAtMs, callback) {
|
||||
const leadTimeMs = applyAtMs - serverNowMs();
|
||||
const late = leadTimeMs < 80;
|
||||
setTimeout(() => callback(late), Math.max(0, leadTimeMs));
|
||||
}
|
||||
|
||||
function prepareScene(message) {
|
||||
pendingCommands.set(message.command_id, message.payload);
|
||||
sendAck(message, "prepared");
|
||||
}
|
||||
|
||||
function commitScene(message) {
|
||||
const payload = pendingCommands.get(message.command_id) || message.payload;
|
||||
scheduleAt(payload.apply_at_ms, (late) => {
|
||||
applyState(payload.state);
|
||||
pendingCommands.delete(message.command_id);
|
||||
sendAck(message, late ? "late" : "committed");
|
||||
});
|
||||
}
|
||||
|
||||
function runComponentAction(message) {
|
||||
const { action, args, apply_at_ms: applyAtMs } = message.payload;
|
||||
scheduleAt(applyAtMs, (late) => {
|
||||
applyAction(action, args || {});
|
||||
sendAck(message, late ? "late" : "action_committed");
|
||||
});
|
||||
}
|
||||
|
||||
function applyAction(action, args) {
|
||||
if (action === "page.next") {
|
||||
pageIndex += 1;
|
||||
rotateValues();
|
||||
} else if (action === "page.prev") {
|
||||
pageIndex = Math.max(0, pageIndex - 1);
|
||||
rotateValues();
|
||||
} else if (action === "energy.mode") {
|
||||
document.querySelector("#modeValue").textContent = args.mode || "削峰";
|
||||
} else if (action === "security.alert") {
|
||||
const rail = document.querySelector("#alertRail");
|
||||
const alert = document.createElement("article");
|
||||
alert.className = "alert pulse";
|
||||
alert.textContent = args.text || "新增联动告警";
|
||||
rail.prepend(alert);
|
||||
while (rail.children.length > 5) rail.lastElementChild.remove();
|
||||
} else if (action === "timeline.pause") {
|
||||
paused = true;
|
||||
} else if (action === "timeline.resume") {
|
||||
paused = false;
|
||||
}
|
||||
pulse();
|
||||
}
|
||||
|
||||
function rotateValues() {
|
||||
const values = [
|
||||
["8.42 MW", "+3.8%", "均衡"],
|
||||
["7.91 MW", "-1.2%", "削峰"],
|
||||
["9.08 MW", "+6.1%", "保供"],
|
||||
][pageIndex % 3];
|
||||
document.querySelector("#powerValue").textContent = values[0];
|
||||
document.querySelector("#trendValue").textContent = values[1];
|
||||
document.querySelector("#modeValue").textContent = values[2];
|
||||
}
|
||||
|
||||
function timelineMs() {
|
||||
if (!state) return 0;
|
||||
return Math.max(0, serverNowMs() - state.scene_started_at_ms);
|
||||
}
|
||||
|
||||
function renderLoop(now) {
|
||||
frameTimeMs = now - lastFrameAt;
|
||||
if (frameTimeMs > 40) droppedFrames += 1;
|
||||
frameCount += 1;
|
||||
if (now - lastFpsAt >= 1000) {
|
||||
fps = frameCount * 1000 / (now - lastFpsAt);
|
||||
frameCount = 0;
|
||||
lastFpsAt = now;
|
||||
}
|
||||
lastFrameAt = now;
|
||||
|
||||
drawMotion(paused ? 0 : timelineMs());
|
||||
updateAnimatedBars(paused ? 0 : timelineMs());
|
||||
updateHud();
|
||||
requestAnimationFrame(renderLoop);
|
||||
}
|
||||
|
||||
function drawMotion(t) {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.globalAlpha = 0.72;
|
||||
for (let i = 0; i < 24; i += 1) {
|
||||
const phase = (t / 1000) + i * 0.42;
|
||||
const x = (Math.sin(phase * 0.42) * 0.5 + 0.5) * canvas.width;
|
||||
const y = (Math.cos(phase * 0.36) * 0.5 + 0.5) * canvas.height;
|
||||
const r = 80 + (i % 5) * 28;
|
||||
const grad = ctx.createRadialGradient(x, y, 0, x, y, r * 5);
|
||||
grad.addColorStop(0, i % 2 ? "rgba(249,115,22,0.23)" : "rgba(20,184,166,0.25)");
|
||||
grad.addColorStop(1, "rgba(0,0,0,0)");
|
||||
ctx.fillStyle = grad;
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, r * 5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
}
|
||||
|
||||
function updateAnimatedBars(t) {
|
||||
document.querySelectorAll(".bar").forEach((bar, index) => {
|
||||
const scale = 0.82 + (Math.sin(t / 760 + index * 0.36) + 1) * 0.16;
|
||||
bar.style.transform = `scaleY(${scale.toFixed(3)})`;
|
||||
});
|
||||
}
|
||||
|
||||
function pulse() {
|
||||
wall.classList.remove("pulse");
|
||||
requestAnimationFrame(() => wall.classList.add("pulse"));
|
||||
}
|
||||
|
||||
function updateHud() {
|
||||
if (!tile) return;
|
||||
const rtt = Number.isFinite(bestRttMs) ? Math.round(bestRttMs) : "--";
|
||||
const offset = `${clockOffsetMs >= 0 ? "+" : ""}${Math.round(clockOffsetMs)}ms`;
|
||||
hud.textContent = `${tile.id} | ${nodeId.slice(0, 18)} | ${fps.toFixed(1)}fps | ${frameTimeMs.toFixed(1)}ms | rtt ${rtt}ms | offset ${offset}`;
|
||||
}
|
||||
|
||||
function sendAck(message, status) {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
ws.send(JSON.stringify({
|
||||
type: "ack",
|
||||
command_id: message.command_id,
|
||||
node_id: nodeId,
|
||||
tile_id: tile.id,
|
||||
status,
|
||||
client_time_ms: clientNowMs(),
|
||||
server_estimated_ms: serverNowMs(),
|
||||
clock_offset_ms: clockOffsetMs,
|
||||
rtt_ms: Number.isFinite(bestRttMs) ? bestRttMs : null,
|
||||
}));
|
||||
}
|
||||
|
||||
function syncClock() {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
||||
ws.send(JSON.stringify({ type: "clock_ping", node_id: nodeId, client_send_ms: clientNowMs() }));
|
||||
}
|
||||
|
||||
function handleClockPong(payload) {
|
||||
const receiveMs = clientNowMs();
|
||||
const sendMs = payload.client_send_ms;
|
||||
if (typeof sendMs !== "number") return;
|
||||
const rtt = receiveMs - sendMs;
|
||||
const estimatedServerAtReceive = payload.server_time_ms + rtt / 2;
|
||||
const nextOffset = estimatedServerAtReceive - receiveMs;
|
||||
if (rtt < bestRttMs) {
|
||||
bestRttMs = rtt;
|
||||
clockOffsetMs = nextOffset;
|
||||
} else {
|
||||
clockOffsetMs = clockOffsetMs * 0.85 + nextOffset * 0.15;
|
||||
}
|
||||
}
|
||||
|
||||
function sendTelemetry() {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN || !tile) return;
|
||||
ws.send(JSON.stringify({
|
||||
type: "telemetry",
|
||||
node_id: nodeId,
|
||||
tile_id: tile.id,
|
||||
fps,
|
||||
frame_time_ms: frameTimeMs,
|
||||
dropped_frames: droppedFrames,
|
||||
}));
|
||||
}
|
||||
|
||||
function connectWs() {
|
||||
const protocol = location.protocol === "https:" ? "wss" : "ws";
|
||||
ws = new WebSocket(`${protocol}://${location.host}/ws/output/${tile.id}`);
|
||||
ws.addEventListener("open", () => {
|
||||
ws.send(JSON.stringify({
|
||||
type: "hello",
|
||||
node_id: nodeId,
|
||||
tile_id: tile.id,
|
||||
app_version: APP_VERSION,
|
||||
user_agent: navigator.userAgent,
|
||||
}));
|
||||
syncClock();
|
||||
});
|
||||
ws.addEventListener("close", () => setTimeout(connectWs, 1200));
|
||||
ws.addEventListener("message", (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.type === "clock_pong") handleClockPong(message.payload);
|
||||
if (message.type === "state") commitScene({ command_id: message.command_id, payload: message.payload });
|
||||
if (message.type === "prepare_scene") prepareScene(message);
|
||||
if (message.type === "commit_scene") commitScene(message);
|
||||
if (message.type === "component_action") runComponentAction(message);
|
||||
});
|
||||
}
|
||||
|
||||
function tickClock() {
|
||||
clock.textContent = new Date().toLocaleTimeString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
window.addEventListener("resize", layout);
|
||||
window.addEventListener("keydown", (event) => {
|
||||
if (event.key.toLowerCase() === "h") hud.hidden = !hud.hidden;
|
||||
});
|
||||
|
||||
bootstrap();
|
||||
tickClock();
|
||||
setInterval(tickClock, 1000);
|
||||
setInterval(syncClock, 2500);
|
||||
setInterval(sendTelemetry, 1000);
|
||||
Reference in New Issue
Block a user