Observatório
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Observatory</title>
<style>
:root {
--bg: #05070f;
--panel: rgba(9, 14, 32, .78);
--line: rgba(124, 146, 230, .17);
--line-red: rgba(255, 90, 77, .34);
--red: #ff5a4d;
--red-hot: #ff9488;
--red-dim: rgba(255, 90, 77, .16);
--blue: #7fa4ff;
--text: #dfe4f6;
--muted: #8793bd;
--faint: #55608a;
--sans: "Avenir Next", "Segoe UI", Roboto, "Helvetica Neue", system-ui, sans-serif;
--mono: ui-monospace, "Roboto Mono", "Cascadia Mono", "SF Mono", Menlo, Consolas, monospace;
}
* { box-sizing: border-box; }
html, body { min-height: 100%; }
body {
margin: 0; color: var(--text); font: 13px/1.35 var(--sans); overflow-x: hidden;
-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent;
-webkit-text-size-adjust: 100%; text-size-adjust: 100%;
background-color: var(--bg);
background-image:
radial-gradient(ellipse 120% 50% at 50% 0%, rgba(40, 62, 150, .30), rgba(40, 62, 150, 0) 70%),
radial-gradient(ellipse 90% 34% at 50% 100%, rgba(255, 60, 48, .13), rgba(255, 60, 48, 0) 70%);
background-attachment: fixed;
}
#sky { position: fixed; inset: 0; width: 100%; height: 100%; z-index: 0; pointer-events: none; }
main {
position: relative; z-index: 1; max-width: 460px; margin: 0 auto;
padding: calc(12px + env(safe-area-inset-top)) calc(14px + env(safe-area-inset-right)) calc(22px + env(safe-area-inset-bottom)) calc(14px + env(safe-area-inset-left));
}
.lab { font: 9.5px/1 var(--mono); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); white-space: nowrap; }
.num { font-family: var(--mono); font-variant-numeric: tabular-nums; font-feature-settings: "tnum"; }
/* ---------- title ---------- */
header { display: flex; justify-content: space-between; align-items: flex-end; gap: 10px; padding: 0 2px 10px; }
.ident { min-width: 0; flex: 1; }
.eyebrow { font: 9.5px/1 var(--mono); letter-spacing: .18em; text-transform: uppercase; color: var(--faint); white-space: nowrap; }
.eyebrow b { font-weight: 400; color: var(--red); }
h1 { margin: 6px 0 0; font-size: 23px; line-height: 1.05; font-weight: 600; letter-spacing: .02em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
h1 span { font-size: 13px; font-weight: 400; color: var(--muted); letter-spacing: .04em; margin-left: 6px; }
.link { flex: none; display: flex; flex-direction: column; align-items: flex-end; gap: 5px; }
.chip { display: inline-flex; align-items: center; gap: 7px; height: 22px; padding: 0 9px; border: 1px solid var(--line-red); border-radius: 11px;
font: 9.5px/1 var(--mono); letter-spacing: .16em; text-transform: uppercase; color: var(--red); background: var(--red-dim); white-space: nowrap; }
.chip i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; box-shadow: 0 0 8px currentColor; animation: beat 2.4s ease-in-out infinite; }
.chip.off { color: var(--muted); border-color: var(--line); background: transparent; }
.chip.off i { animation: none; box-shadow: none; }
@keyframes beat { 50% { opacity: .35; } }
/* ---------- the stack ---------- */
.view { position: relative; aspect-ratio: 1; border-radius: 14px; overflow: hidden; background: #02030a;
border: 1px solid var(--line-red); box-shadow: 0 0 0 1px rgba(0, 0, 0, .6), 0 18px 50px rgba(0, 0, 0, .55), 0 0 44px rgba(255, 60, 48, .08); }
.view canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
.shade { position: absolute; inset: 0; pointer-events: none;
background: radial-gradient(circle at 50% 50%, rgba(2, 3, 10, 0) 52%, rgba(2, 3, 10, .62) 100%),
linear-gradient(rgba(2, 3, 10, .55), rgba(2, 3, 10, 0) 22%, rgba(2, 3, 10, 0) 76%, rgba(2, 3, 10, .7)); }
.corner { position: absolute; width: 16px; height: 16px; border: 0 solid var(--red); opacity: .8; pointer-events: none; }
.corner.a { left: 9px; top: 9px; border-left-width: 1.5px; border-top-width: 1.5px; }
.corner.b { right: 9px; top: 9px; border-right-width: 1.5px; border-top-width: 1.5px; }
.corner.c { left: 9px; bottom: 12px; border-left-width: 1.5px; border-bottom-width: 1.5px; }
.corner.d { right: 9px; bottom: 12px; border-right-width: 1.5px; border-bottom-width: 1.5px; }
.cross { position: absolute; left: 50%; top: 50%; width: 44px; height: 44px; margin: -22px 0 0 -22px; pointer-events: none; opacity: .5; transition: opacity .4s;
background: linear-gradient(var(--red), var(--red)) 50% 0 / 1px 13px no-repeat, linear-gradient(var(--red), var(--red)) 50% 100% / 1px 13px no-repeat,
linear-gradient(var(--red), var(--red)) 0 50% / 13px 1px no-repeat, linear-gradient(var(--red), var(--red)) 100% 50% / 13px 1px no-repeat; }
.view.empty .cross { opacity: 0; }
.hud { position: absolute; display: flex; flex-direction: column; gap: 5px; pointer-events: none; text-shadow: 0 1px 6px #000, 0 0 2px #000; }
.hud.tl { left: 20px; top: 19px; }
.hud.tr { right: 20px; top: 19px; align-items: flex-end; }
.hud.bl { left: 20px; bottom: 24px; }
.hud.br { right: 20px; bottom: 24px; align-items: flex-end; }
.hud .lab { color: rgba(223, 228, 246, .72); }
.hud b { font: 500 13px/1 var(--mono); color: var(--text); }
#frames { font-size: 34px; font-weight: 500; letter-spacing: .02em; color: var(--red); text-shadow: 0 0 18px rgba(255, 60, 48, .6), 0 1px 6px #000; }
.mode { display: inline-flex; align-items: center; gap: 6px; height: 20px; padding: 0 8px; border-radius: 3px; background: rgba(2, 3, 10, .6);
border: 1px solid var(--line-red); font: 9.5px/1 var(--mono); letter-spacing: .18em; text-transform: uppercase; color: var(--red); text-shadow: none; }
.mode i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; animation: beat 1.2s ease-in-out infinite; }
.mode.idle { color: var(--muted); border-color: var(--line); }
.mode.idle i { animation: none; }
.expbar { position: absolute; left: 0; right: 0; bottom: 0; height: 3px; background: rgba(255, 90, 77, .14); }
.expbar i { display: block; height: 100%; width: 0; background: linear-gradient(90deg, rgba(255, 90, 77, .5), var(--red-hot)); box-shadow: 0 0 10px var(--red); }
.veil { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; text-align: center;
pointer-events: none; opacity: 0; transition: opacity .5s; }
.veil.show { opacity: 1; }
.veil b { font: 500 15px/1 var(--mono); letter-spacing: .34em; margin-right: -.34em; color: var(--red); text-shadow: 0 0 18px rgba(255, 60, 48, .7); }
.veil span { font-size: 12px; color: var(--muted); letter-spacing: .04em; }
.flash { position: absolute; inset: 0; border-radius: 13px; pointer-events: none; opacity: 0; box-shadow: inset 0 0 0 1.5px var(--red-hot), inset 0 0 34px rgba(255, 90, 77, .45); }
.flash.lit { animation: flash .9s ease-out; }
@keyframes flash { 0% { opacity: .95; } 100% { opacity: 0; } }
/* ---------- panels ---------- */
.panel { margin-top: 10px; padding: 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel);
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); }
.metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
.metric { position: relative; height: 60px; padding: 9px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); overflow: hidden; }
.metric canvas { position: absolute; right: 0; bottom: 0; width: 52%; height: 30px; display: block; }
.metric .val { position: relative; display: flex; align-items: baseline; gap: 6px; margin-top: 8px; }
.metric .val b { font: 500 24px/1 var(--mono); color: var(--red); text-shadow: 0 0 14px rgba(255, 60, 48, .45); }
.metric.cool .val b { color: var(--blue); text-shadow: 0 0 14px rgba(127, 164, 255, .4); }
/* ---------- mount ---------- */
.mount { display: grid; grid-template-columns: 136px 1fr; gap: 4px 14px; align-items: center; }
#chart { width: 136px; height: 136px; display: block; touch-action: manipulation; }
.coords { min-width: 0; display: flex; flex-direction: column; gap: 9px; }
.coord { display: flex; flex-direction: column; gap: 5px; }
.coord b { font: 500 19px/1 var(--mono); letter-spacing: .01em; color: var(--red); white-space: nowrap; text-shadow: 0 0 14px rgba(255, 60, 48, .4); }
.mstate { display: flex; align-items: center; gap: 7px; font: 10px/1 var(--mono); letter-spacing: .16em; text-transform: uppercase; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mstate i { flex: none; width: 7px; height: 7px; border-radius: 50%; border: 1.5px solid var(--red); }
.mstate.slew i { border-style: dashed; animation: spin 1.2s linear infinite; }
.mstate.slew { color: var(--red-hot); }
@keyframes spin { to { transform: rotate(360deg); } }
.targets { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(4, 1fr); gap: 7px; margin-top: 8px; }
button { font: inherit; color: inherit; background: none; border: 0; margin: 0; padding: 0; cursor: pointer; touch-action: manipulation; }
button:disabled { cursor: default; opacity: .45; }
.target { height: 46px; border: 1px solid var(--line); border-radius: 9px; background: rgba(124, 146, 230, .05); display: flex; flex-direction: column;
align-items: center; justify-content: center; gap: 5px; transition: border-color .3s, background .3s, color .3s; }
.target b { font: 500 14px/1 var(--mono); }
.target span { font: 8.5px/1 var(--mono); letter-spacing: .14em; text-transform: uppercase; color: var(--faint); }
.target.on { border-color: var(--red); background: var(--red-dim); color: var(--red); box-shadow: 0 0 18px rgba(255, 60, 48, .14); }
.target.on span { color: var(--red); opacity: .8; }
.target:active:not(:disabled) { background: rgba(255, 90, 77, .22); }
/* ---------- camera ---------- */
.row { display: flex; align-items: center; gap: 12px; }
.row + .row { margin-top: 10px; }
.row > .lab { width: 62px; flex: none; }
.seg { flex: 1; display: grid; grid-template-columns: repeat(4, 1fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; }
.seg button { height: 34px; font: 500 12px/1 var(--mono); color: var(--muted); border-left: 1px solid var(--line); transition: background .25s, color .25s; }
.seg button:first-child { border-left: 0; }
.seg button.on { background: var(--red-dim); color: var(--red); box-shadow: inset 0 -2px 0 var(--red); }
.gain { flex: 1; display: flex; align-items: center; gap: 10px; }
.step { flex: none; width: 34px; height: 34px; border: 1px solid var(--line); border-radius: 9px; font: 500 16px/1 var(--mono); color: var(--text); }
.step:active:not(:disabled) { background: var(--red-dim); }
.bar { flex: 1; position: relative; height: 4px; border-radius: 2px; background: rgba(124, 146, 230, .16); }
.bar i { position: absolute; left: 0; top: 0; bottom: 0; width: 0; border-radius: 2px; background: var(--red); box-shadow: 0 0 10px rgba(255, 60, 48, .7); transition: width .3s; }
#gain { flex: none; width: 34px; text-align: right; font: 500 14px/1 var(--mono); color: var(--red); }
.go { width: 100%; height: 42px; margin-top: 12px; border: 1px solid var(--red); border-radius: 10px; background: var(--red-dim); color: var(--red);
font: 500 11.5px/1 var(--mono); letter-spacing: .26em; text-transform: uppercase; display: flex; align-items: center; justify-content: center; gap: 10px; transition: background .25s; }
.go i { width: 9px; height: 9px; background: currentColor; border-radius: 1.5px; }
.go.start i { border-radius: 50%; }
.go:active:not(:disabled) { background: rgba(255, 90, 77, .3); }
.hint { margin-top: 9px; font-size: 11px; color: var(--faint); text-align: center; }
/* ---------- downlink ---------- */
.wire { display: flex; align-items: center; gap: 10px; margin-top: 11px; }
.node { flex: none; display: flex; align-items: center; gap: 7px; font: 9.5px/1 var(--mono); letter-spacing: .16em; text-transform: uppercase; color: var(--text); }
.node svg { width: 20px; height: 20px; stroke: var(--red); fill: none; stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.track { flex: 1; position: relative; height: 12px; overflow: hidden;
background: radial-gradient(circle, rgba(124, 146, 230, .4) 1px, transparent 1.4px) 0 50% / 9px 9px repeat-x; }
.track i { position: absolute; top: 3px; left: 0; width: 22px; height: 6px; border-radius: 3px; opacity: 0;
background: linear-gradient(90deg, rgba(255, 90, 77, 0), var(--red-hot)); box-shadow: 0 0 10px var(--red); }
.track.send i { animation: send .8s cubic-bezier(.3, 0, .2, 1); }
@keyframes send { 0% { left: -22px; opacity: 1; } 85% { opacity: 1; } 100% { left: 100%; opacity: 0; } }
.pulls { margin-top: 10px; display: flex; justify-content: space-between; gap: 10px; font: 11px/1.3 var(--mono); color: var(--muted); }
.pulls b { font-weight: 500; color: var(--red); }
.toast { position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom)); transform: translate(-50%, 12px); max-width: calc(100% - 40px); padding: 9px 14px;
border: 1px solid var(--line-red); border-radius: 9px; background: rgba(12, 6, 10, .94); color: var(--red-hot); font-size: 12px; opacity: 0; pointer-events: none;
transition: opacity .3s, transform .3s; z-index: 5; }
.toast.show { opacity: 1; transform: translate(-50%, 0); }
@media (max-width: 374px) {
.mount { grid-template-columns: 120px 1fr; gap: 4px 12px; }
#chart { width: 120px; height: 120px; }
.coord b { font-size: 17px; }
h1 { font-size: 21px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; }
}
</style>
</head>
<body>
<canvas id="sky" aria-hidden="true"></canvas>
<main>
<header>
<div class="ident">
<div class="eyebrow">Remote observatory<b id="sim"></b></div>
<h1 id="title">Observatory</h1>
</div>
<div class="link"><span class="chip off" id="link"><i></i><span id="linkText">Connecting</span></span></div>
</header>
<section class="view" aria-label="Live stack">
<canvas id="image"></canvas>
<div class="shade"></div>
<div class="cross"></div>
<div class="corner a"></div><div class="corner b"></div><div class="corner c"></div><div class="corner d"></div>
<div class="veil" id="veil"><b id="veilTitle"></b><span id="veilText"></span></div>
<div class="hud tl"><span class="lab">Frames stacked</span><span class="num" id="frames">000</span></div>
<div class="hud tr"><span class="mode idle" id="mode"><i></i><span id="modeText">--</span></span></div>
<div class="hud bl"><span class="lab">Integration</span><b class="num" id="integration">0:00</b></div>
<div class="hud br"><span class="lab">Exposure</span><b class="num" id="settings">--</b></div>
<div class="expbar"><i id="expFill"></i></div>
<div class="flash" id="flash"></div>
</section>
<section class="metrics">
<div class="metric"><span class="lab">Signal to noise</span><canvas id="sparkSnr"></canvas><div class="val"><b class="num" id="snr">--</b></div></div>
<div class="metric cool"><span class="lab">Noise · counts</span><canvas id="sparkNoise"></canvas><div class="val"><b class="num" id="noise">--</b></div></div>
</section>
<section class="panel" aria-label="Frame downlink">
<span class="lab">Frame downlink · machine to machine</span>
<div class="wire">
<span class="node"><svg viewBox="0 0 20 20"><path d="M3 9l9-5 2 3.5-9 5zM14 5.2l3-1.7M9 11.5V17M6 17h6"/></svg>Telescope</span>
<div class="track" id="track"><i></i></div>
<span class="node">Stacker<svg viewBox="0 0 20 20"><rect x="2.5" y="4" width="15" height="9.5" rx="1.2"/><path d="M7 17h6M10 13.5V17"/></svg></span>
</div>
<div class="pulls"><span id="pullText">No program has pulled a frame yet.</span><span id="pullCount"></span></div>
</section>
<section class="panel mount" aria-label="Mount">
<canvas id="chart" role="img" aria-label="Where the mount points, on a chart around the celestial pole"></canvas>
<div class="coords">
<div class="coord"><span class="lab">Right ascension</span><b class="num" id="ra">--</b></div>
<div class="coord"><span class="lab">Declination</span><b class="num" id="dec">--</b></div>
<div class="mstate" id="mstate"><i></i><span id="mstateText">--</span></div>
</div>
<div class="targets" id="targets"></div>
</section>
<section class="panel" aria-label="Camera">
<div class="row"><span class="lab">Exposure</span><div class="seg" id="exposures"></div></div>
<div class="row"><span class="lab">Gain</span>
<div class="gain"><button class="step" id="gainDown" aria-label="Less gain">−</button><div class="bar"><i id="gainFill"></i></div><span id="gain">--</span><button class="step" id="gainUp" aria-label="More gain">+</button></div>
</div>
<button class="go" id="capture"><i></i><span id="captureText">Capture</span></button>
<div class="hint">A new exposure or gain starts a new stack.</div>
</section>
</main>
<div class="toast" id="toast" role="status"></div>
<script>
(() => {
'use strict';
/* ======================= helpers ======================= */
const $ = id => document.getElementById(id);
const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const sleep = ms => new Promise(r => setTimeout(r, ms));
const pad = (n, w) => String(n).padStart(w || 2, '0');
const set = (id, text) => { const el = $(id); text = String(text); if (el && el.textContent !== text) el.textContent = text; };
const num = v => typeof v === 'number' && isFinite(v) ? v : 0;
const dpr = () => Math.min(2, window.devicePixelRatio || 1);
const EXPOSURES = [1, 2, 4, 8], GAIN_STEP = 30, GAIN_MAX = 300;
const KINDS = { spiral: 'Galaxy', nebula: 'Nebula', cluster: 'Cluster', ring: 'Planetary', field: 'Field' };
function raText(hours) {
const s = Math.round((((hours % 24) + 24) % 24) * 3600) % 86400;
return pad(s / 3600 | 0) + 'h ' + pad(s / 60 % 60 | 0) + 'm ' + pad(s % 60) + 's';
}
function decText(degrees) {
const s = Math.round(Math.abs(degrees) * 3600);
return (degrees < 0 ? '−' : '+') + pad(s / 3600 | 0) + '° ' + pad(s / 60 % 60 | 0) + '′ ' + pad(s % 60) + '″';
}
function duration(seconds) {
const s = Math.max(0, Math.round(seconds)), h = s / 3600 | 0;
return h ? h + ':' + pad(s / 60 % 60 | 0) + ':' + pad(s % 60) : (s / 60 | 0) + ':' + pad(s % 60);
}
const wrapHours = h => ((h + 12) % 24 + 24) % 24 - 12; // a difference of right ascension, the short way round
/* ======================= what the device said ======================= */
let st = null, stAt = 0; // the latest state and when it arrived (performance.now)
let targets = [];
let online = null, failures = 0, busy = false;
let shownRa = 0, shownDec = 0, speedX = 0, speedY = 0; // the pointer on screen follows the mount smoothly
let trail = [], trailSerial = -1; // { frames, snr, noise } of the stack that is running
let pulls = -1;
function validState(s) {
return s && typeof s === 'object' && s.mount && s.camera && s.capture && s.stack ? s : null;
}
function applyState(next) {
next = validState(next); if (!next) return;
const first = !st;
st = next; stAt = performance.now();
if (first || reduced) { shownRa = num(st.mount.ra); shownDec = num(st.mount.dec); }
applyStack(st.stack);
const served = st.downlink ? num(st.downlink.framesServed) : 0;
if (pulls >= 0 && served > pulls) sendPulse();
pulls = served;
renderStatic();
wantStack();
if (reduced) drawAll(performance.now());
}
function applyStack(stack) {
if (!stack) return;
if (st) st.stack = stack;
if (stack.serial !== trailSerial) { trailSerial = stack.serial; trail = []; }
if (stack.frames > 0 && (!trail.length || trail[trail.length - 1].frames !== stack.frames)) {
trail.push({ frames: stack.frames, snr: num(stack.snr), noise: num(stack.noise) });
if (trail.length > 400) trail.shift();
}
drawSparks();
}
/* ======================= transport: the bridge's WebSocket, else polling ======================= */
let socket = null, socketLive = false, lastMessage = 0, socketRetryAt = 0;
async function request(path, method, body) {
const init = { method: method || 'GET', cache: 'no-store' };
if (body !== undefined) { init.headers = { 'Content-Type': 'application/json' }; init.body = JSON.stringify(body); }
return Promise.race([
fetch(path, init),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 8000)),
]);
}
async function requestJson(path, method, body) {
const answer = await request(path, method, body);
let value = null;
try { value = await answer.json(); } catch (e) { /* not JSON */ }
return { ok: answer.ok, status: answer.status, value };
}
function openSocket() {
const bridge = window.connectivitizer;
if (!bridge || typeof bridge.webSocket !== 'function' || socket) return;
let ws;
try { ws = bridge.webSocket('/events'); } catch (e) { return; }
socket = ws;
ws.onopen = () => { if (socket === ws) lastMessage = performance.now(); };
ws.onmessage = event => {
if (socket !== ws || typeof event.data !== 'string') return;
let message;
try { message = JSON.parse(event.data); } catch (e) { return; }
if (!message || typeof message !== 'object') return;
socketLive = true; lastMessage = performance.now();
setOnline(true);
if (message.type === 'state') applyState(message.state);
else if (message.type === 'frame' && st) { applyStack(message.stack); renderStatic(); wantStack(); }
};
ws.onclose = () => { if (socket === ws) dropSocket(); };
ws.onerror = () => { if (socket === ws) dropSocket(); };
}
function dropSocket() {
const ws = socket; socket = null; socketLive = false; socketRetryAt = performance.now() + 5000;
if (ws) { ws.onmessage = ws.onclose = ws.onerror = null; try { ws.close(); } catch (e) { /* already closed */ } }
}
function setOnline(on) {
if (on) failures = 0;
if (on === online) return;
online = on;
renderLink();
renderStatic();
}
async function loop() {
for (;;) {
const now = performance.now();
// A socket that has been silent for a while is taken for dead; the page asks by itself until it is back.
if (socket && now - lastMessage > 6000) dropSocket();
if (!socket && now >= socketRetryAt) openSocket();
try {
if (!targets.length) {
const list = (await requestJson('/targets')).value;
if (Array.isArray(list)) { targets = list.filter(t => t && typeof t.id === 'string'); renderTargets(); }
}
if (!socketLive) {
const answer = await requestJson('/state');
if (!answer.ok) throw new Error('http ' + answer.status);
applyState(answer.value);
setOnline(true);
}
} catch (e) {
if (++failures >= 2 || online === null) setOnline(false);
}
await sleep(socketLive ? 1000 : 600);
}
}
/* ======================= the live stack ======================= */
// GET /stack answers the average of all frames so far, 8 bits a sample: 16 bytes of head ('CZFR', width,
// height, channels, bits, serial of the stack, frames in it), then red, green, blue for every pixel.
let current = null, previous = null, fade = 1; // two small canvases, the new one fading in over the old
let shownKey = '', loadingStack = false;
function decodeStack(buffer) {
if (!(buffer instanceof ArrayBuffer) || buffer.byteLength < 16) return null;
const view = new DataView(buffer);
if (view.getUint32(0, false) !== 0x435a4652) return null; // 'CZFR'
const width = view.getUint16(4, true), height = view.getUint16(6, true), channels = view.getUint8(8), bits = view.getUint8(9);
if (bits !== 8 || channels < 1 || !width || !height || buffer.byteLength !== 16 + width * height * channels) return null;
const samples = new Uint8Array(buffer, 16), canvas = document.createElement('canvas');
canvas.width = width; canvas.height = height;
const context = canvas.getContext('2d'), picture = context.createImageData(width, height), data = picture.data;
for (let from = 0, to = 0; to < data.length; from += channels, to += 4) {
data[to] = samples[from];
data[to + 1] = samples[channels >= 3 ? from + 1 : from];
data[to + 2] = samples[channels >= 3 ? from + 2 : from];
data[to + 3] = 255;
}
context.putImageData(picture, 0, 0);
return { canvas, serial: view.getUint16(10, true), frames: view.getUint32(12, true) };
}
async function wantStack() {
if (!st || loadingStack) return;
const stack = st.stack;
if (!(stack.frames > 0)) {
if (current) { current = previous = null; shownKey = ''; viewDirty = true; renderStatic(); }
return;
}
const key = stack.serial + ':' + stack.frames;
if (key === shownKey) return;
loadingStack = true;
try {
const answer = await request('/stack');
const picture = answer.ok ? decodeStack(await answer.arrayBuffer()) : null;
// A picture of a stack that has ended meanwhile (the mount slews) is not shown.
if (picture && st && picture.serial === (st.stack.serial & 0xffff) && st.stack.frames > 0) {
previous = reduced ? null : current;
current = picture.canvas;
fade = previous ? 0 : 1;
shownKey = picture.serial + ':' + picture.frames;
viewDirty = true;
flash();
renderStatic();
if (reduced) drawAll(performance.now());
}
} catch (e) { /* the next state asks again */ }
loadingStack = false;
if (st && st.stack.frames > 0 && st.stack.serial + ':' + st.stack.frames !== shownKey) setTimeout(wantStack, 150);
}
function flash() {
if (reduced) return;
const el = $('flash');
el.classList.remove('lit'); void el.offsetWidth; el.classList.add('lit');
}
function sendPulse() {
if (reduced) return;
const el = $('track');
el.classList.remove('send'); void el.offsetWidth; el.classList.add('send');
}
/* ======================= drawing ======================= */
const sky = $('sky'), image = $('image'), chart = $('chart');
let viewDirty = true, chartHits = [];
function fit(canvas) {
const box = canvas.getBoundingClientRect(), scale = dpr();
const width = Math.max(1, Math.round(box.width * scale)), height = Math.max(1, Math.round(box.height * scale));
if (canvas.width !== width || canvas.height !== height) { canvas.width = width; canvas.height = height; }
return canvas.getContext('2d');
}
// The page's own backdrop: decoration, not data.
const backdrop = [];
for (let i = 0, seed = 7; i < 120; i++) {
const next = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296;
backdrop.push({ x: next(), y: next(), size: .4 + 1.1 * Math.pow(next(), 3), phase: next() * 6.28, rate: .4 + next() * 1.4, warm: next() });
}
function drawSky(now) {
const c = fit(sky), w = sky.width, h = sky.height, scale = dpr(), t = reduced ? 0 : now / 1000;
c.clearRect(0, 0, w, h);
for (const star of backdrop) {
const x = ((star.x + t * .0022) % 1) * w, y = star.y * h;
const alpha = .22 + .5 * star.size / 1.5 * (.6 + .4 * Math.sin(star.phase + t * star.rate));
c.fillStyle = star.warm > .8 ? 'rgba(255,170,150,' + alpha + ')' : 'rgba(190,206,255,' + alpha + ')';
c.beginPath(); c.arc(x, y, star.size * scale, 0, 6.2832); c.fill();
}
}
// While there is no picture (the mount slews, or the first exposure runs): red marks that streak with the motion.
const marks = [];
for (let i = 0, seed = 99; i < 70; i++) {
const next = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 4294967296;
marks.push({ x: next(), y: next(), depth: .4 + next() * .6 });
}
let driftX = 0, driftY = 0;
function drawView(now, dt) {
const slewing = st && st.mount.state === 'slewing';
if (!viewDirty && current && fade >= 1) return;
const c = fit(image), w = image.width, h = image.height;
c.globalAlpha = 1;
c.fillStyle = '#02030a'; c.fillRect(0, 0, w, h);
if (current) {
c.imageSmoothingEnabled = true; c.imageSmoothingQuality = 'high';
if (previous && fade < 1) {
c.drawImage(previous, 0, 0, w, h);
c.globalAlpha = fade * fade * (3 - 2 * fade);
}
c.drawImage(current, 0, 0, w, h);
c.globalAlpha = 1;
if (fade < 1) fade = Math.min(1, fade + dt / .7); else { previous = null; viewDirty = false; }
return;
}
driftX += speedX * dt * .012; driftY += speedY * dt * .012;
const length = Math.hypot(speedX, speedY), scale = dpr();
c.lineCap = 'round';
for (const mark of marks) {
const x = (((mark.x - driftX * mark.depth) % 1) + 1) % 1 * w, y = (((mark.y + driftY * mark.depth) % 1) + 1) % 1 * h;
const tail = slewing ? Math.min(60, length * 1.6) * mark.depth * scale : 0;
const ux = length > .01 ? speedX / length : 0, uy = length > .01 ? -speedY / length : 0;
c.strokeStyle = 'rgba(255,90,77,' + (.14 + .4 * mark.depth) + ')';
c.lineWidth = (.8 + mark.depth) * scale;
c.beginPath(); c.moveTo(x, y); c.lineTo(x + ux * tail + .01, y + uy * tail); c.stroke();
}
viewDirty = !reduced;
}
// The chart: the sky around the celestial pole, declination +90 in the middle down to -30 at the rim,
// right ascension around it. The targets and the place the mount points at are on it.
function chartPoint(ra, dec, cx, cy, radius) {
const r = radius * clamp((90 - dec) / 120, 0, 1), angle = ra / 24 * 6.2832;
return [cx - r * Math.sin(angle), cy - r * Math.cos(angle)];
}
function drawChart(now) {
const c = fit(chart), w = chart.width, scale = dpr(), cx = w / 2, cy = w / 2, radius = w / 2 - 13 * scale;
c.clearRect(0, 0, w, w);
const glow = c.createRadialGradient(cx, cy, 0, cx, cy, radius);
glow.addColorStop(0, 'rgba(60,84,190,.30)'); glow.addColorStop(1, 'rgba(20,30,80,.10)');
c.fillStyle = glow; c.beginPath(); c.arc(cx, cy, radius, 0, 6.2832); c.fill();
c.lineWidth = scale;
for (const dec of [60, 30, 0, -30]) {
c.strokeStyle = dec === 0 ? 'rgba(127,164,255,.5)' : dec === -30 ? 'rgba(255,90,77,.5)' : 'rgba(124,146,230,.2)';
c.beginPath(); c.arc(cx, cy, radius * (90 - dec) / 120, 0, 6.2832); c.stroke();
}
c.strokeStyle = 'rgba(124,146,230,.14)';
c.font = 8 * scale + 'px ui-monospace, Menlo, Consolas, monospace'; c.textAlign = 'center'; c.textBaseline = 'middle';
for (let hour = 0; hour < 24; hour += 2) {
const a = chartPoint(hour, 75, cx, cy, radius), b = chartPoint(hour, -30, cx, cy, radius);
c.beginPath(); c.moveTo(a[0], a[1]); c.lineTo(b[0], b[1]); c.stroke();
if (hour % 6 === 0) {
const angle = hour / 24 * 6.2832, lx = cx - (radius + 5 * scale) * Math.sin(angle), ly = cy - (radius + 5 * scale) * Math.cos(angle);
c.fillStyle = 'rgba(135,147,189,.9)'; c.fillText(hour + 'h', lx, ly);
}
}
chartHits = [];
if (!st) return;
const goal = st.mount.target, slewing = st.mount.state === 'slewing';
const list = targets.slice();
if (goal && !list.some(t => t.id === goal.id)) list.push(goal);
for (const target of list) {
const p = chartPoint(target.ra, target.dec, cx, cy, radius), on = goal && goal.id === target.id, size = (on ? 3.6 : 2.8) * scale;
chartHits.push({ x: p[0] / scale, y: p[1] / scale, target });
c.fillStyle = on ? '#ff5a4d' : 'rgba(223,228,246,.85)';
c.beginPath(); c.moveTo(p[0], p[1] - size); c.lineTo(p[0] + size, p[1]); c.lineTo(p[0], p[1] + size); c.lineTo(p[0] - size, p[1]); c.closePath(); c.fill();
c.fillStyle = on ? '#ff9488' : 'rgba(135,147,189,.95)';
// The name stands on the far side of the mark, seen from the pole; near the rim on the near side.
const dx = p[0] - cx, dy = p[1] - cy, far = Math.hypot(dx, dy) || 1, away = (far < radius * .6 ? 1 : -1) * (on ? 17 : 9) * scale / far;
c.fillText(target.name, p[0] + dx * away * 1.3, p[1] + dy * away);
}
const at = chartPoint(shownRa, shownDec, cx, cy, radius);
if (slewing && goal) {
const to = chartPoint(goal.ra, goal.dec, cx, cy, radius);
c.setLineDash([3 * scale, 3 * scale]); c.lineDashOffset = reduced ? 0 : -now / 60 * scale;
c.strokeStyle = 'rgba(255,148,136,.8)'; c.beginPath(); c.moveTo(at[0], at[1]); c.lineTo(to[0], to[1]); c.stroke();
c.setLineDash([]);
}
// The pointer: a ring with four ticks, and a second ring that breathes while the mount tracks.
const ring = 7 * scale;
c.strokeStyle = '#ff5a4d'; c.lineWidth = 1.4 * scale; c.shadowColor = 'rgba(255,60,48,.9)'; c.shadowBlur = 8 * scale;
c.beginPath(); c.arc(at[0], at[1], ring, 0, 6.2832); c.stroke();
c.beginPath();
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { c.moveTo(at[0] + dx * ring, at[1] + dy * ring); c.lineTo(at[0] + dx * (ring + 4 * scale), at[1] + dy * (ring + 4 * scale)); }
c.stroke();
c.shadowBlur = 0;
if (!slewing && !reduced) {
const beat = (now / 1800) % 1;
c.strokeStyle = 'rgba(255,90,77,' + (.55 * (1 - beat)) + ')'; c.lineWidth = scale;
c.beginPath(); c.arc(at[0], at[1], ring + beat * 11 * scale, 0, 6.2832); c.stroke();
}
}
function drawSpark(canvas, key, colour, fill) {
const c = fit(canvas), w = canvas.width, h = canvas.height, scale = dpr();
c.clearRect(0, 0, w, h);
if (trail.length < 3) return;
let max = 0;
for (const point of trail) max = Math.max(max, point[key]);
if (!(max > 0)) return;
const last = trail[trail.length - 1].frames, first = trail[0].frames, span = Math.max(5, last - first);
c.beginPath();
trail.forEach((point, index) => {
const x = (point.frames - first) / span * (w - 2 * scale) + scale, y = h - 2 * scale - point[key] / max * (h - 6 * scale);
index ? c.lineTo(x, y) : c.moveTo(x, y);
});
c.strokeStyle = colour; c.lineWidth = 1.5 * scale; c.lineJoin = 'round'; c.stroke();
const end = (last - first) / span * (w - 2 * scale) + scale;
c.lineTo(end, h); c.lineTo(scale, h); c.closePath();
c.fillStyle = fill; c.fill();
}
function drawSparks() {
drawSpark($('sparkSnr'), 'snr', 'rgba(255,90,77,.9)', 'rgba(255,90,77,.10)');
drawSpark($('sparkNoise'), 'noise', 'rgba(127,164,255,.9)', 'rgba(127,164,255,.10)');
}
/* ======================= text and controls ======================= */
function renderLink() {
const bridge = window.connectivitizer, device = bridge && bridge.device;
// Only what the app reported about its session is said here.
const route = device ? (device.path === 'direct' ? 'Direct' : device.path === 'relayed' ? 'Relayed' : 'Session') + (device.endToEndEncrypted === true ? ' · E2E' : '') : 'Browser';
set('linkText', online === false ? 'Offline' : online === null ? 'Connecting' : route);
$('link').classList.toggle('off', online !== true);
}
function renderStatic() {
if (!st) return;
const mount = st.mount, target = mount.target, stack = st.stack, camera = st.camera, slewing = mount.state === 'slewing';
const running = st.capture.running === true;
const title = $('title');
const name = target ? target.name : 'Observatory', sub = target ? target.title : '';
if (title.dataset.key !== name + '|' + sub) {
title.dataset.key = name + '|' + sub;
title.textContent = name;
if (sub) { const span = document.createElement('span'); span.textContent = sub; title.appendChild(span); }
}
set('sim', st.simulated ? ' · simulated sky' : '');
set('frames', pad(num(stack.frames), 3));
set('integration', duration(num(stack.integrationSeconds)));
set('settings', num(camera.exposureSeconds) + ' s · gain ' + num(camera.gain));
set('snr', stack.frames > 0 ? num(stack.snr).toFixed(1) : '--');
set('noise', stack.frames > 0 ? (stack.noise >= 100 ? Math.round(stack.noise) : num(stack.noise).toFixed(1)) : '--');
set('modeText', slewing ? 'Slewing' : running ? 'Stacking' : 'Paused');
$('mode').classList.toggle('idle', !slewing && !running);
const veil = $('veil'), empty = !current;
veil.classList.toggle('show', empty);
veil.parentNode.classList.toggle('empty', empty);
if (empty) {
set('veilTitle', slewing ? 'SLEWING' : running ? 'EXPOSING' : 'CAPTURE STOPPED');
set('veilText', slewing ? 'to ' + (target ? target.name + ' · ' + target.title : 'the new position') : running ? 'The first frame of this stack is on its way.' : 'Start the capture to stack frames.');
}
$('mstate').classList.toggle('slew', slewing);
set('mstateText', slewing ? 'Slewing to ' + (target ? target.name : 'position') : 'Tracking');
if (!slewing || reduced) { set('ra', raText(num(mount.ra))); set('dec', decText(num(mount.dec))); }
const off = online === false || busy;
for (const button of $('targets').children) {
button.classList.toggle('on', !!target && button.dataset.id === target.id);
button.disabled = off;
}
for (const button of $('exposures').children) {
button.classList.toggle('on', Number(button.dataset.seconds) === camera.exposureSeconds);
button.disabled = off;
}
set('gain', num(camera.gain));
$('gainFill').style.width = clamp(num(camera.gain) / GAIN_MAX, 0, 1) * 100 + '%';
$('gainDown').disabled = off || camera.gain <= 0;
$('gainUp').disabled = off || camera.gain >= GAIN_MAX;
$('capture').disabled = off;
$('capture').classList.toggle('start', !running);
set('captureText', running ? 'Stop capture' : 'Start capture');
const link = st.downlink;
if (link && link.framesServed > 0) {
const ago = num(link.lastSecondsAgo);
$('pullText').textContent = '';
$('pullText').append('Frame ', Object.assign(document.createElement('b'), { textContent: '#' + link.lastSequence }), ' pulled ' + (ago < 1.5 ? 'just now' : ago < 90 ? Math.round(ago) + ' s ago' : duration(ago) + ' ago'));
set('pullCount', link.framesServed + (link.framesServed === 1 ? ' pull' : ' pulls'));
} else {
set('pullText', 'No program has pulled a frame yet.');
set('pullCount', '');
}
if (!reduced) return;
$('expFill').style.width = clamp(num(st.capture.exposureProgress), 0, 1) * 100 + '%';
}
function renderTargets() {
const box = $('targets');
box.textContent = '';
for (const target of targets) {
const button = document.createElement('button');
button.className = 'target'; button.dataset.id = target.id;
const name = document.createElement('b'), kind = document.createElement('span');
name.textContent = target.name; kind.textContent = KINDS[target.kind] || 'Target';
button.append(name, kind);
button.setAttribute('aria-label', 'Slew to ' + target.name + ', ' + target.title);
button.addEventListener('click', () => command('/slew', { target: target.id }));
box.appendChild(button);
}
renderStatic();
}
let toastTimer = 0;
function toast(text) {
const el = $('toast');
el.textContent = text; el.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove('show'), 2800);
}
async function command(path, body) {
if (busy || online === false) return;
busy = true; renderStatic();
try {
const answer = await requestJson(path, 'POST', body);
if (answer.ok) applyState(answer.value);
else toast(answer.value && answer.value.error ? answer.value.error : 'The observatory answered ' + answer.status + '.');
} catch (e) {
toast('The observatory did not answer.');
}
busy = false; renderStatic();
}
for (const seconds of EXPOSURES) {
const button = document.createElement('button');
button.dataset.seconds = seconds; button.textContent = seconds + ' s';
button.addEventListener('click', () => { if (st && st.camera.exposureSeconds !== seconds) command('/capture', { exposureSeconds: seconds }); });
$('exposures').appendChild(button);
}
$('gainDown').addEventListener('click', () => { if (st) command('/capture', { gain: clamp(st.camera.gain - GAIN_STEP, 0, GAIN_MAX) }); });
$('gainUp').addEventListener('click', () => { if (st) command('/capture', { gain: clamp(st.camera.gain + GAIN_STEP, 0, GAIN_MAX) }); });
$('capture').addEventListener('click', () => { if (st) command('/capture', { running: !st.capture.running }); });
chart.addEventListener('click', event => {
const box = chart.getBoundingClientRect(), x = event.clientX - box.left, y = event.clientY - box.top;
let best = null, distance = 24;
for (const hit of chartHits) { const d = Math.hypot(hit.x - x, hit.y - y); if (d < distance && hit.target.id !== 'custom') { distance = d; best = hit.target; } }
if (best && st && !(st.mount.target && st.mount.target.id === best.id)) command('/slew', { target: best.id });
});
/* ======================= the frame loop ======================= */
let lastFrame = performance.now(), turn = 0;
function drawAll(now) {
drawSky(now); viewDirty = true; drawView(now, 0); drawChart(now); drawSparks();
}
function frame(now) {
const dt = clamp((now - lastFrame) / 1000, 0, .1);
lastFrame = now;
if (st) {
// The pointer follows what the device reported, a little behind and without steps.
const ease = 1 - Math.exp(-dt / .16), dRa = wrapHours(num(st.mount.ra) - shownRa), dDec = num(st.mount.dec) - shownDec;
const slewing = st.mount.state === 'slewing';
if (dt > 0) {
speedX += (dRa * 15 * Math.cos(shownDec * Math.PI / 180) * ease / dt - speedX) * .2;
speedY += (dDec * ease / dt - speedY) * .2;
}
shownRa = ((shownRa + dRa * ease) % 24 + 24) % 24;
shownDec += dDec * ease;
if (slewing) { set('ra', raText(shownRa)); set('dec', decText(shownDec)); }
const capture = st.capture, exposure = Math.max(.1, num(st.camera.exposureSeconds));
const progress = capture.running && !slewing ? clamp(num(capture.exposureProgress) + (now - stAt) / 1000 / exposure, 0, 1) : 0;
$('expFill').style.width = progress * 100 + '%';
}
if (turn++ % 2 === 0) drawSky(now);
drawView(now, dt);
drawChart(now);
requestAnimationFrame(frame);
}
addEventListener('resize', () => { viewDirty = true; drawSparks(); if (reduced) drawAll(performance.now()); });
/* ======================= start ======================= */
renderLink();
if (reduced) drawAll(performance.now()); else requestAnimationFrame(frame);
if (window.connectivitizer && window.connectivitizer.ready && typeof window.connectivitizer.ready.then === 'function') {
window.connectivitizer.ready.then(renderLink, () => {});
}
loop();
})();
</script>
</body>
</html>