import {ObserverSession} from './observer-session.mjs'; import {readBathymetry} from './lake-model.mjs'; import {assembleView, originFromCsv} from './depth-scene.mjs'; import {mountDepthView} from './depth-view.mjs'; const $ = id => document.getElementById(id); let view = {ok: false, setModel() {}}; try { view = mountDepthView($('depth')); } catch { view = {ok: false, setModel() {}}; } let state = null; let timer = null; let generation = 0; let paused = false; let mode = 'idle'; let lastMesh = 0; let drawn = false; let cachedMesh = null; let token = ''; let session = ''; let lastReceived = 0; let csv = null; const fragment = new URLSearchParams(location.hash.slice(1)); token = fragment.get('token') || ''; session = fragment.get('session') || ''; history.replaceState(null, '', location.pathname + location.search); function stop() { generation += 1; clearTimeout(timer); state = null; drawn = false; cachedMesh = null; lastMesh = 0; lastReceived = 0; paused = false; $('pause').textContent = 'Anzeige pausieren'; } function row(container, name, value, cls = '') { const line = document.createElement('div'); line.className = 'stat'; const label = document.createElement('span'); const reading = document.createElement('span'); label.textContent = name; reading.textContent = value; reading.className = cls; line.append(label, reading); container.append(line); } function samples() { const points = []; if (csv) points.push(...csv.points); if (state?.geometry?.samples) points.push(...state.geometry.samples); if (state?.depths) points.push(...state.depths); return points; } function paint() { if (!view.ok) { $('notice').textContent = '3D-Ansicht nicht verfügbar: WebGL fehlt.'; return; } const overlay = state ? state.overlay(false) : null; const model = assembleView({ mode: mode === 'demo' && !csv ? 'demo' : mode, mesh: cachedMesh, points: samples(), overlay, heading: state?.state?.heading, fitKey: mode + ':' + (state?.session || '') + ':' + (csv ? csv.name + ':' + csv.points.length : '') }); $('banner').hidden = !model.banner; if (model.banner) $('banner').textContent = model.banner; $('range').textContent = Number.isFinite(model.min) ? model.min.toFixed(1) + '–' + model.max.toFixed(1) + ' m' : ''; $('viewstatus').textContent = model.status + (csv ? ' · lokale Datei ' + csv.name + ', nicht hochgeladen' : ''); view.setModel(model); } function draw() { if (!state?.state) { paint(); return; } const stale = mode === 'live' && Date.now() - lastReceived > 6000; const reading = stale ? {...state.state, position: null, heading: null, speedMps: null, gps: false, compass: false, lidarCm: null, sonarM: null, phoneBattery: null, boatBatteryV: null} : state.state; const origin = state.geometry.origin; const geo = reading.position && origin ? [origin[0] + reading.position[1] / 111319.490793, origin[1] + reading.position[0] / (111319.490793 * Math.cos(origin[0] * Math.PI / 180))] : null; $('state').replaceChildren(); for (const [name, value] of [['Modus', reading.mode], ['Position', geo ? geo.map(n => n.toFixed(6)).join(', ') : 'unbekannt'], ['Kurs', reading.heading == null ? 'unbekannt' : reading.heading.toFixed(1) + '°'], ['Tempo', reading.speedMps == null ? 'unbekannt' : reading.speedMps.toFixed(2) + ' m/s'], ['KI-Schritt', reading.aiStep ?? 'keine aktuelle KI-Meldung'], ['Wegpunkt', reading.nextWaypoint ?? '–'], ['Messpunkte (neu)', state.depths.length], ['Letzte Entscheidung', reading.decision.source + ': ' + reading.decision.reason]]) { row($('state'), name, String(value)); } $('sensors').replaceChildren(); for (const [name, value] of [['GPS', reading.gps ? 'frisch' : null], ['Kompass', reading.compass ? 'Rohdaten vorhanden' : null], ['LiDAR', reading.lidarCm == null ? null : reading.lidarCm + ' cm'], ['Sonar', reading.sonarM == null ? null : reading.sonarM + ' m'], ['Handy-Akku', reading.phoneBattery == null ? null : reading.phoneBattery + ' %'], ['Boot-Akku', reading.boatBatteryV == null ? null : reading.boatBatteryV + ' V']]) { row($('sensors'), name, value ?? 'unbekannt', value == null ? 'unknown' : 'ok'); } $('warning').textContent = [...(reading.locked ? ['Motorfreigabe gesperrt'] : []), ...(reading.estop ? ['NOTSTOPP'] : []), ...reading.warnings].join(' · ') || 'Keine gemeldete Warnung'; $('log').replaceChildren(); for (const entry of [...state.log].reverse()) { const item = document.createElement('li'); item.textContent = new Date(entry.utc).toLocaleTimeString('de-AT') + ' ' + entry.source + ': ' + entry.reason; $('log').append(item); } try { if (!drawn) { cachedMesh = state.scene(); drawn = true; lastMesh = Date.now(); } const refresh = state.depths.length !== state.meshAt && Date.now() - lastMesh > 8000; if (refresh) { try { cachedMesh = state.scene(); } catch (error) { $('notice').textContent = 'Rastergrenze erreicht; Messpunkte weiterhin sichtbar'; } lastMesh = Date.now(); } if (stale && state) { const hidden = state.overlay(false); hidden.boat = []; hidden.status += ' · letzte Messung veraltet'; const model = assembleView({mode, mesh: cachedMesh, points: samples(), overlay: hidden, heading: null, fitKey: mode + ':' + state.session + ':' + (csv ? csv.name + ':' + csv.points.length : '')}); $('banner').hidden = !model.banner; $('range').textContent = model.min.toFixed(1) + '–' + model.max.toFixed(1) + ' m'; $('viewstatus').textContent = model.status; if (view.ok) view.setModel(model); return; } paint(); } catch (error) { $('notice').textContent = '3D-Ansicht nicht verfügbar: ' + error.message; } } function schedule(fn, id, ms = 2000) { if (id === generation) timer = setTimeout(() => fn(id), ms); } async function live(id) { if (id !== generation) return; if (paused) { schedule(live, id); return; } try { const headers = {}; if (token.length >= 16) headers.Authorization = 'Bearer ' + token; const response = await fetch('telemetry.php?' + new URLSearchParams({session, after: String(state.seq)}), {headers, cache: 'no-store', redirect: 'error'}); if (!response.ok) throw Error('HTTP ' + response.status); const page = await response.json(); if (id !== generation) return; if (page.schemaVersion !== 2 || page.session !== session || !Array.isArray(page.events) || page.events.length > 32) throw Error('Vertrag'); for (const event of page.events) state.apply(event); lastReceived = page.receivedUtc; $('connection').textContent = Date.now() - lastReceived > 6000 ? 'Letzter Stand – Daten veraltet' : 'Live'; $('notice').textContent = token.length >= 16 ? 'Privater Beobachtungslink · keine Rücksteuerung' : 'Öffentliche Live-Ansicht · keine Steuerung. Position ist ohne Schlüssel sichtbar.'; draw(); schedule(live, id, page.more ? 100 : 2000); } catch (error) { if (id !== generation) return; $('connection').textContent = 'Verbindung unterbrochen / Daten veraltet'; $('notice').textContent = error.message; lastReceived = 0; draw(); schedule(live, id, 4000); } } async function replay(animated) { stop(); csv = null; mode = 'demo'; const id = generation; state = new ObserverSession(); $('connection').textContent = 'DEMO – synthetische Daten'; try { const response = await fetch('demo.json', {cache: 'no-store'}); if (!response.ok) throw Error('Demo fehlt'); const events = await response.json(); if (id !== generation) return; $('notice').textContent = 'Synthetische Wiedergabe – keine Verbindung zum realen Boot. Die Datei wird nicht hochgeladen.'; if (!animated) { for (const event of events) state.apply(event); draw(); $('connection').textContent = 'DEMO – synthetische Daten'; return; } let index = 0; function step(run) { if (run !== generation) return; if (!paused && index < events.length) { state.apply(events[index]); index += 1; draw(); } if (index < events.length) schedule(step, run, 1000); else { $('connection').textContent = 'DEMO – Wiedergabe beendet'; try { cachedMesh = state.scene(); draw(); } catch (error) { $('notice').textContent = error.message; } } } step(id); } catch (error) { $('notice').textContent = error.message; } } $('demo').onclick = () => replay(true); $('pause').onclick = () => { paused = !paused; $('pause').textContent = paused ? 'Anzeige fortsetzen' : 'Anzeige pausieren'; if (paused) $('connection').textContent = 'Anzeige pausiert – eingefrorener Stand'; else if (mode === 'demo') $('connection').textContent = 'DEMO – synthetische Daten'; }; $('csv').addEventListener('change', async event => { const file = event.target.files && event.target.files[0]; event.target.value = ''; if (!file) return; try { if (file.size > 4000000) throw Error('CSV zu groß'); const text = await file.text(); const origin = mode === 'live' && state?.geometry?.origin ? state.geometry.origin : originFromCsv(text); const points = readBathymetry(text, origin); if (!points.length) throw Error('Keine Tiefenpunkte'); if (mode === 'demo') stop(); if (mode !== 'live') { mode = 'file'; $('state').replaceChildren(); $('sensors').replaceChildren(); $('log').replaceChildren(); $('warning').textContent = ''; } csv = {name: file.name, origin, points}; $('notice').textContent = 'Lokale Datei ' + file.name + ': ' + points.length + ' Punkte. Nichts wurde hochgeladen.'; $('connection').textContent = mode === 'live' ? $('connection').textContent : 'Lokale Datei'; drawn = false; draw(); } catch (error) { $('notice').textContent = error.message; } }); const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; function beginPublic(id) { stop(); session = id; token = ''; mode = 'live'; state = new ObserverSession(); $('connection').textContent = 'Öffentlich · verbinde…'; $('notice').textContent = 'Öffentliche Live-Ansicht · keine Steuerung. Position ist ohne Schlüssel sichtbar.'; live(generation); } async function watchPublic(id) { if (id !== generation || mode === 'file' || mode === 'live' || token.length >= 16) return; try { const response = await fetch('telemetry.php', {cache: 'no-store', redirect: 'error'}); if (id !== generation) return; if (response.status === 401 || response.status === 404 || response.status === 503) return; if (!response.ok) { schedule(watchPublic, id, 5000); return; } const info = await response.json(); if (info.public === true && uuidRe.test(info.session || '')) { beginPublic(info.session); return; } } catch { /* Demo bleibt, wenn kein PHP läuft. */ } schedule(watchPublic, id, 5000); } if (uuidRe.test(session) && token.length >= 16) { state = new ObserverSession(); mode = 'live'; live(generation); } else if (uuidRe.test(session)) { beginPublic(session); } else { replay(false).then(() => schedule(watchPublic, generation, 5000)); }