Aquarium
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
demo-kit/ is what simulates the device for the demo on the start page. The device itself does not need it.
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="dark">
<title>Aquarium</title>
<style>
:root {
--bg: #04121c; --panel: #0a1f2c; --panel2: #0d2736; --line: rgba(160,220,235,.13); --ink: #e6f6f8; --muted: #8fb3bd;
--aqua: #5fd9e6; --coral: #ff8f70; --gold: #ffd27a; --moon: #cfe3ff;
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html { -webkit-text-size-adjust: 100%; }
body { margin: 0; background: var(--bg); color: var(--ink); font: 14px/1.4 var(--font); overflow-x: hidden;
-webkit-font-smoothing: antialiased; -webkit-tap-highlight-color: transparent; font-variant-numeric: tabular-nums; }
button, input { font: inherit; color: inherit; }
button { border: 0; background: none; padding: 0; cursor: pointer; }
:focus-visible { outline: 2px solid var(--aqua); outline-offset: 3px; }
main { max-width: 560px; margin: 0 auto; padding-bottom: calc(20px + env(safe-area-inset-bottom)); }
/* ---------- the tank: the whole upper part of the screen ---------- */
.tank { position: relative; height: clamp(340px, 58vh, 540px); overflow: hidden; border-radius: 0 0 30px 30px; background: #0a2c48;
box-shadow: 0 22px 40px -24px rgba(0,0,0,.9), inset 0 -1px 0 rgba(255,255,255,.14); transition: filter .6s; }
.tank canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: pan-y; }
.off-line .tank { filter: saturate(.4) brightness(.8); }
.top { position: absolute; left: 0; right: 0; top: 0; display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; pointer-events: none;
padding: calc(14px + env(safe-area-inset-top)) calc(18px + env(safe-area-inset-right)) 0 calc(20px + env(safe-area-inset-left)); text-shadow: 0 1px 10px rgba(0,20,40,.55); }
h1 { margin: 0; font-size: 12px; font-weight: 650; letter-spacing: .2em; text-transform: uppercase; opacity: .92; }
.temp { font-size: 68px; line-height: 1; font-weight: 250; letter-spacing: -.03em; margin: 6px 0 0 -3px; white-space: nowrap; }
.temp small { font-size: 24px; font-weight: 350; letter-spacing: 0; margin-left: 3px; opacity: .85; vertical-align: 26px; }
.sub { margin: 4px 0 0; font-size: 13px; font-weight: 500; white-space: nowrap; display: flex; align-items: center; gap: 7px; }
.sub i { width: 7px; height: 7px; border-radius: 50%; background: var(--tc, var(--aqua)); box-shadow: 0 0 8px var(--tc, var(--aqua)); transition: background .5s; }
.pill { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px 6px 9px; border-radius: 99px; background: rgba(3,22,36,.42);
border: 1px solid rgba(255,255,255,.16); font-size: 12px; font-weight: 600; white-space: nowrap; text-shadow: none; }
.pill i { width: 7px; height: 7px; border-radius: 50%; background: #6fe6a0; position: relative; }
.pill i::after { content: ""; position: absolute; inset: 0; border-radius: 50%; background: inherit; animation: ping 2.4s ease-out infinite; }
.pill.off i { background: #ffb347; } .pill.wait i { background: var(--muted); }
@keyframes ping { 0% { transform: scale(1); opacity: .6 } 70%, 100% { transform: scale(2.8); opacity: 0 } }
.phase { position: absolute; left: calc(20px + env(safe-area-inset-left)); bottom: 18px; pointer-events: none; display: inline-flex; align-items: center; gap: 8px;
padding: 7px 13px 7px 9px; border-radius: 99px; background: rgba(3,22,36,.5); border: 1px solid rgba(255,255,255,.16); font-size: 12.5px; font-weight: 600; white-space: nowrap; }
.phase svg { width: 18px; height: 18px; flex: none; }
.phase span span { color: var(--muted); font-weight: 500; margin-left: 5px; }
/* ---------- feeding ---------- */
.feed { display: flex; align-items: flex-start; gap: 12px; padding: 14px calc(20px + env(safe-area-inset-right)) 0 calc(20px + env(safe-area-inset-left)); }
.next { flex: 1; min-width: 0; padding-top: 2px; }
.lbl { font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: var(--muted); font-weight: 600; }
.next b { display: block; font-size: 30px; line-height: 1.1; font-weight: 300; letter-spacing: -.01em; margin-top: 3px; white-space: nowrap; }
.next b small { font-size: 14px; font-weight: 500; color: var(--muted); margin-left: 8px; letter-spacing: 0; }
.next p { margin: 3px 0 0; font-size: 12.5px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
#feed { position: relative; flex: none; width: 88px; height: 88px; margin-top: -46px; border-radius: 50%; color: #3a1206; font-weight: 700; font-size: 13px; letter-spacing: .04em;
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 1px;
background: radial-gradient(circle at 34% 26%, #ffd0bd, rgba(255,208,189,0) 50%), linear-gradient(160deg, #ffa385, #f4694a);
box-shadow: 0 0 0 6px var(--bg), 0 14px 26px -8px rgba(244,105,74,.6), inset 0 -6px 12px rgba(120,30,10,.28), inset 0 1px 0 rgba(255,255,255,.6);
transition: transform .15s, filter .3s; }
#feed svg { width: 30px; height: 30px; }
#feed:active { transform: scale(.94); }
#feed:disabled { cursor: default; }
#feed::after { content: ""; position: absolute; inset: -6px; border-radius: 50%; border: 3px solid transparent; border-top-color: var(--coral); border-right-color: var(--coral); opacity: 0; transition: opacity .3s; }
#feed.on::after { opacity: 1; animation: spin .9s linear infinite; }
#feed.on svg { animation: shake .45s ease-in-out infinite; }
@keyframes spin { to { transform: rotate(360deg) } }
@keyframes shake { 25% { transform: rotate(-14deg) translateY(1px) } 75% { transform: rotate(12deg) translateY(2px) } }
/* ---------- panels ---------- */
.panel { margin: 16px calc(14px + env(safe-area-inset-right)) 0 calc(14px + env(safe-area-inset-left)); padding: 15px 16px 16px; border-radius: 24px;
background: linear-gradient(170deg, var(--panel2), var(--panel)); border: 1px solid var(--line); box-shadow: inset 0 1px 0 rgba(255,255,255,.05); }
.phead { display: flex; justify-content: space-between; align-items: center; gap: 10px; }
h2 { margin: 0; font-size: 17px; font-weight: 600; letter-spacing: -.01em; white-space: nowrap; }
.seg { display: flex; gap: 2px; padding: 3px; border-radius: 99px; background: rgba(0,0,0,.28); border: 1px solid var(--line); }
.seg button { padding: 5px 13px; border-radius: 99px; font-size: 12.5px; font-weight: 600; color: var(--muted); transition: background .25s, color .25s; }
.seg button[aria-selected="true"] { background: var(--aqua); color: #04222c; }
.psub { margin: 3px 0 0; font-size: 12.5px; color: var(--muted); min-height: 18px; }
/* the day: 24 hours with the light curve, and one handle each for sunrise and sunset */
.day { position: relative; height: 72px; margin-top: 12px; transition: opacity .3s; }
.day svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; overflow: visible; }
.day input { position: absolute; left: 0; top: 0; width: 100%; height: 72px; margin: 0; background: none; pointer-events: none; -webkit-appearance: none; appearance: none; }
.day input::-webkit-slider-runnable-track { height: 72px; background: none; }
.day input::-moz-range-track { height: 72px; background: none; }
.day input::-webkit-slider-thumb { -webkit-appearance: none; pointer-events: auto; width: 30px; height: 30px; margin-top: 21px; border-radius: 50%; cursor: grab; }
.day input::-moz-range-thumb { pointer-events: auto; width: 26px; height: 26px; border-radius: 50%; cursor: grab; }
#rise::-webkit-slider-thumb { border: 2px solid #fff; background: radial-gradient(circle, #fff7d6 0 28%, #ffc34a 32%); box-shadow: 0 0 16px 2px rgba(255,200,90,.7), 0 3px 8px rgba(0,0,0,.5); }
#rise::-moz-range-thumb { border: 2px solid #fff; background: radial-gradient(circle, #fff7d6 0 28%, #ffc34a 32%); box-shadow: 0 0 16px 2px rgba(255,200,90,.7); }
#set::-webkit-slider-thumb { border: 2px solid var(--moon); background: #14304c; box-shadow: inset -7px -3px 0 0 var(--moon), 0 0 14px 1px rgba(150,190,255,.55), 0 3px 8px rgba(0,0,0,.5); }
#set::-moz-range-thumb { border: 2px solid var(--moon); background: #14304c; box-shadow: inset -7px -3px 0 0 var(--moon), 0 0 14px 1px rgba(150,190,255,.55); }
.manual .day { opacity: .38; } .manual .day input { visibility: hidden; }
.hours { display: flex; justify-content: space-between; padding: 5px 9px 0; font-size: 10.5px; color: var(--muted); }
.times { display: flex; justify-content: space-between; gap: 10px; margin-top: 10px; font-size: 12.5px; color: var(--muted); }
.times b { color: var(--ink); font-size: 15px; font-weight: 600; margin-left: 6px; }
.times span { display: inline-flex; align-items: center; white-space: nowrap; }
.times i { width: 9px; height: 9px; border-radius: 50%; margin-right: 7px; background: var(--gold); }
.times span + span i { background: var(--moon); }
.row { display: flex; justify-content: space-between; align-items: baseline; margin-top: 14px; font-size: 13px; }
.row output { font-size: 15px; font-weight: 600; }
#lvl { -webkit-appearance: none; appearance: none; width: 100%; height: 32px; margin: 2px 0 0; background: none; display: block; }
#lvl::-webkit-slider-runnable-track { height: 8px; border-radius: 99px; background: linear-gradient(90deg, #2b6f8a, var(--gold) var(--p, 50%), rgba(255,255,255,.1) var(--p, 50%)); }
#lvl::-moz-range-track { height: 8px; border-radius: 99px; background: linear-gradient(90deg, #2b6f8a, var(--gold) var(--p, 50%), rgba(255,255,255,.1) var(--p, 50%)); }
#lvl::-webkit-slider-thumb { -webkit-appearance: none; width: 26px; height: 26px; margin-top: -9px; border-radius: 50%; background: #fff; border: 0; box-shadow: 0 0 0 4px rgba(255,210,122,.25), 0 2px 6px rgba(0,0,0,.5); }
#lvl::-moz-range-thumb { width: 24px; height: 24px; border-radius: 50%; background: #fff; border: 0; box-shadow: 0 0 0 4px rgba(255,210,122,.25); }
/* ---------- chart ---------- */
.stats { display: flex; gap: 14px; font-size: 12px; color: var(--muted); white-space: nowrap; }
.stats b { color: var(--ink); font-weight: 600; margin-left: 4px; }
.plot { position: relative; height: 150px; margin-top: 10px; touch-action: pan-y; }
.plot svg { position: absolute; inset: 0; width: 100%; height: 100%; display: block; overflow: visible; }
.plot .gr { stroke: var(--line); stroke-width: 1; } .plot text, .day text { fill: var(--muted); font-size: 10.5px; font-family: var(--font); }
.plot .ln { fill: none; stroke: url(#tl); stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; }
.plot .ln.draw { stroke-dasharray: 1; stroke-dashoffset: 1; animation: draw 1.1s cubic-bezier(.4,0,.2,1) forwards; }
@keyframes draw { to { stroke-dashoffset: 0 } }
.plot .ar { fill: url(#ta); } .plot .dot { fill: #fff; stroke: var(--panel); stroke-width: 2; }
.plot .halo { fill: var(--aqua); opacity: .3; transform-box: fill-box; transform-origin: center; animation: ping 2.4s ease-out infinite; }
.plot .cx { stroke: var(--muted); stroke-width: 1; opacity: .6; }
.tip { position: absolute; top: 0; padding: 4px 9px; border-radius: 10px; background: var(--ink); color: var(--bg); font-size: 12px; font-weight: 600;
white-space: nowrap; pointer-events: none; transform: translateX(-50%); opacity: 0; transition: opacity .15s; }
.tip small { font-weight: 400; opacity: .75; margin-left: 5px; }
footer { display: flex; justify-content: center; align-items: center; gap: 6px 16px; flex-wrap: wrap; color: var(--muted); font-size: 12px; padding: 16px 16px 0; }
footer span { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
footer svg { width: 16px; height: 16px; } footer rect { fill: var(--muted); opacity: .3; } footer rect.on { opacity: 1; }
#sim { color: var(--gold); }
#toast { position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom)); transform: translate(-50%, 20px); background: var(--ink); color: var(--bg);
padding: 9px 16px; border-radius: 99px; font-size: 13px; font-weight: 600; opacity: 0; pointer-events: none; transition: opacity .3s, transform .3s; z-index: 9; max-width: 90vw; }
#toast.show { opacity: 1; transform: translate(-50%, 0); }
@media (max-width: 359px) { .temp { font-size: 58px; } .next b { font-size: 26px; } }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; }
.plot .ln.draw { stroke-dasharray: none; }
}
</style>
</head>
<body>
<main id="app">
<section class="tank" id="tank" aria-label="The tank">
<canvas id="sea" role="img" aria-label="The aquarium: fish, plants and bubbles in the light of the current time of day."></canvas>
<div class="top">
<div>
<h1>Aquarium</h1>
<div class="temp"><span id="tV">–</span><small>°C</small></div>
<p class="sub"><i id="tI"></i><span id="tS">Reading the water</span></p>
</div>
<div class="pill wait" id="link" role="status"><i></i><span id="linkT">Connecting</span></div>
</div>
<div class="phase"><svg viewBox="0 0 18 18" aria-hidden="true" id="phI"></svg><span><b id="phT">Light</b><span id="phS"></span></span></div>
</section>
<section class="feed" aria-label="Feeding">
<div class="next">
<div class="lbl">Next feeding</div>
<b><span id="nfT">–</span><small id="nfIn"></small></b>
<p id="fed"></p>
</div>
<button id="feed" type="button" disabled aria-label="Feed now">
<svg viewBox="0 0 30 30" aria-hidden="true"><path d="M9 4h12l-1.4 4H10.4z" fill="currentColor"/><path d="M10 9h10l1.6 13.5a3 3 0 0 1-3 3.5h-7.2a3 3 0 0 1-3-3.5z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><circle cx="13" cy="16" r="1.3" fill="currentColor"/><circle cx="17" cy="19" r="1.3" fill="currentColor"/><circle cx="14" cy="21.5" r="1.1" fill="currentColor"/></svg>
<span id="feedT">Feed</span>
</button>
</section>
<section class="panel" id="lightP" aria-label="Light">
<div class="phead"><h2>Light</h2>
<div class="seg" role="tablist">
<button role="tab" data-m="auto" aria-selected="true">Schedule</button>
<button role="tab" data-m="manual" aria-selected="false">Manual</button>
</div></div>
<p class="psub" id="lSub">Drag the sun and the moon to set the day.</p>
<div class="day" id="day"><svg id="dayS" aria-hidden="true"></svg>
<input id="rise" type="range" min="0" max="1440" step="15" value="480" aria-label="Sunrise">
<input id="set" type="range" min="0" max="1440" step="15" value="1200" aria-label="Sunset">
</div>
<div class="hours" aria-hidden="true"><span>00</span><span>06</span><span>12</span><span>18</span><span>24</span></div>
<div class="times"><span><i></i>Sunrise<b id="riseV">–</b></span><span><i></i>Sunset<b id="setV">–</b></span></div>
<div class="row"><label for="lvl" id="lvlL">Brightness by day</label><output id="lvlV" for="lvl">–</output></div>
<input id="lvl" type="range" min="10" max="100" step="1" value="85">
</section>
<section class="panel" aria-label="Water temperature, last 24 hours">
<div class="phead"><h2>Water, last 24 hours</h2></div>
<div class="stats psub" id="cSub"></div>
<div class="plot" id="plot"><svg id="cv" aria-hidden="true"></svg><div class="tip" id="tip"></div></div>
</section>
<footer>
<span><svg viewBox="0 0 16 16" aria-hidden="true"><rect x="1" y="11" width="2.5" height="4" rx="1"/><rect x="5" y="8" width="2.5" height="7" rx="1"/><rect x="9" y="5" width="2.5" height="10" rx="1"/><rect x="13" y="2" width="2.5" height="13" rx="1"/></svg><span id="rssi">Wi-Fi</span></span>
<span id="up"></span>
<span id="sim" hidden>Simulated hardware</span>
</footer>
</main>
<div id="toast" role="alert"></div>
<script>
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
var NS = 'http://www.w3.org/2000/svg';
var RM = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
var clamp = function (v, a, b) { return Math.max(a, Math.min(b, v)); };
var num = function (v) { return typeof v === 'number' && isFinite(v); };
var rnd = function (a, b) { return a + Math.random() * (b - a); };
function el(name, attrs, parent) {
var e = document.createElementNS(NS, name);
for (var k in attrs) e.setAttribute(k, attrs[k]);
if (parent) parent.appendChild(e);
return e;
}
function text(node, value) { if (node.textContent !== value) node.textContent = value; }
function mix(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; }
function hhmm(minutes) {
var m = ((Math.round(minutes) % 1440) + 1440) % 1440, h = Math.floor(m / 60);
return (h < 10 ? '0' : '') + h + ':' + (m % 60 < 10 ? '0' : '') + (m % 60);
}
function span(minutes) {
var h = Math.floor(minutes / 60), m = Math.round(minutes % 60);
return h > 0 ? h + ' h ' + m + ' min' : m + ' min';
}
// ---------- the device ----------
function api(path, body) {
var init = body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : undefined;
var late = new Promise(function (_, reject) { setTimeout(function () { reject(new Error('No answer')); }, 7000); });
return Promise.race([fetch(path, init), late]).then(function (r) {
return r.text().then(function (body) {
var data = null;
try { data = JSON.parse(body); } catch (e) { /* not JSON */ }
if (!r.ok || data === null) { var err = new Error((data && data.error) || 'The device answered ' + r.status); err.status = r.status; throw err; }
return data;
});
});
}
// =====================================================================================================
// The tank. Everything in it is drawn on one canvas, every frame. Three numbers decide its look: how
// bright the light is, and how far into a dawn or a dusk it is. They glide towards what the device says.
// =====================================================================================================
var cv = $('sea'), g = cv.getContext('2d'), W = 0, H = 0, sandY = 0;
var look = { L: .7, dawn: 0, dusk: 0 }, lookTo = { L: .7, dawn: 0, dusk: 0 }, vis = .8;
var amb = [1, 1, 1], waterMid = [20, 112, 170];
var NIGHT = [[9, 26, 62], [5, 16, 42], [3, 9, 24]], DAY = [[40, 154, 198], [20, 112, 170], [9, 62, 112]];
var DAWN = [[250, 164, 142], [196, 108, 140], [72, 50, 100]], DUSK = [[255, 128, 58], [176, 70, 120], [52, 34, 90]];
// A colour of a thing in the water, as the light of this moment shows it; `haze` moves it towards the
// colour of the water, for things further back.
function lit(rgb, alpha, haze) {
var r = rgb[0] * amb[0], gr = rgb[1] * amb[1], b = rgb[2] * amb[2];
if (haze) { r += (waterMid[0] - r) * haze; gr += (waterMid[1] - gr) * haze; b += (waterMid[2] - b) * haze; }
return 'rgba(' + (r | 0) + ',' + (gr | 0) + ',' + (b | 0) + ',' + (alpha === undefined ? 1 : alpha) + ')';
}
function rgba(rgb, alpha) { return 'rgba(' + (rgb[0] | 0) + ',' + (rgb[1] | 0) + ',' + (rgb[2] | 0) + ',' + alpha + ')'; }
function sandAt(x) { return sandY + Math.sin(x * .013 + 1) * 5 + Math.sin(x * .031) * 3; }
var blades = [], pebbles = [], bubbles = [], motes = [], fish = [], pellets = [], school = { x: 0, y: 0, next: 0 };
var toDrop = 0, dropAt = 0, poke = null;
// What grows where: [place across the tank, blades, lowest and highest (share of the tank's height), colour, in front]
var BEDS = [[.05, 6, .34, .6, [38, 130, 78], 0], [.17, 4, .16, .3, [70, 160, 84], 1], [.33, 5, .22, .42, [150, 62, 70], 0], [.5, 3, .1, .2, [86, 170, 92], 1],
[.66, 6, .3, .52, [44, 140, 96], 0], [.8, 4, .4, .68, [30, 118, 70], 0], [.93, 6, .2, .44, [78, 168, 80], 1], [.42, 4, .12, .2, [56, 140, 80], 0]];
function plant() {
blades = [];
BEDS.forEach(function (bed) {
for (var i = 0; i < bed[1]; i++) {
var red = bed[4][0] > 120;
blades.push({ x: W * bed[0] + (i - bed[1] / 2) * rnd(7, 11), h: H * rnd(bed[2], bed[3]), w: red ? rnd(5, 7) : rnd(3, 5.2), lean: rnd(-.16, .16),
ph: rnd(0, 6.3), sp: rnd(.6, 1.05), col: mix(bed[4], [200, 220, 120], rnd(0, .22)), front: bed[5] });
}
});
pebbles = [];
for (var p = 0; p < 16; p++) pebbles.push({ x: rnd(0, 1), dy: rnd(8, 34), r: rnd(2, 5.5), shade: rnd(.55, .95) });
}
function newFish(kind, size, cruise) {
return { kind: kind, size: size, cruise: cruise, x: rnd(.15, .85) * W, y: rnd(.35, .75) * H, vx: rnd(-1, 1) * cruise, vy: 0, face: Math.random() < .5 ? -1 : 1,
tx: 0, ty: 0, pick: 0, tp: rnd(0, 6), ph: rnd(0, 6), agile: kind === 'tetra' ? 2.6 : 1.5, v: 0 };
}
function stock() {
fish = [];
for (var i = 0; i < 7; i++) fish.push(newFish('tetra', rnd(21, 26), rnd(34, 44)));
fish.push(newFish('gold', 58, 24), newFish('koi', 50, 27));
var cory = newFish('cory', 34, 16);
cory.y = sandY - 5;
fish.push(cory);
school.x = W * .6; school.y = H * .5;
// Without motion the fish are a still picture, so each gets a place of its own.
if (RM) [[.5, .5], [.57, .46], [.6, .55], [.66, .49], [.7, .58], [.76, .5], [.8, .43], [.3, .4], [.62, .74], [.4, .9]].forEach(function (spot, n) {
fish[n].x = W * spot[0]; fish[n].y = n === 9 ? sandY - 6 : H * spot[1]; fish[n].face = n === 8 ? -1 : 1; fish[n].vx = fish[n].face * 20;
});
for (var b = 0; b < 14; b++) bubbles.push(newBubble(rnd(0, sandY)));
for (var m = 0; m < 26; m++) motes.push({ x: rnd(0, 1), y: rnd(0, 1), r: rnd(.5, 1.4), ph: rnd(0, 6) });
}
function newBubble(y) {
return { x0: W * .235 + rnd(-5, 5), y: y === undefined ? sandY - 4 : y, r: rnd(1, 3.2), vy: rnd(34, 62), ph: rnd(0, 6) };
}
function resize() {
var box = cv.getBoundingClientRect(), dpr = Math.min(2, window.devicePixelRatio || 1), first = W === 0;
if (box.width < 10 || (Math.abs(box.width - W) < 1 && Math.abs(box.height - H) < 1)) return;
var sx = box.width / (W || box.width), sy = box.height / (H || box.height);
W = box.width; H = box.height; sandY = H - Math.max(48, H * .13);
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
g.setTransform(dpr, 0, 0, dpr, 0, 0);
plant();
if (first) stock();
else fish.forEach(function (f) { f.x *= sx; f.y = f.kind === 'cory' ? sandY - 5 : f.y * sy; f.pick = 0; });
if (RM) drawTank(0, 0);
}
// ---------- how the fish move ----------
function pickTarget(f, t) {
var top = H * .22 + H * .3 * (1 - vis), bottom = sandY - 16; // in the dark they stay low
if (f.kind === 'cory') { f.tx = W * rnd(.08, .92); f.ty = sandY - 5; f.pick = t + rnd(3, 8); return; }
if (f.kind === 'tetra') {
f.tx = clamp(school.x + rnd(-52, 52), 16, W - 16); f.ty = clamp(school.y + rnd(-30, 30), top, bottom); f.pick = t + rnd(1.2, 3.4);
return;
}
f.tx = W * rnd(.1, .9); f.ty = rnd(top, bottom); f.pick = t + rnd(4, 9);
}
function moveFish(f, t, dt) {
var speed = f.cruise * (.4 + .6 * vis), eager = 1, tx, ty, food = null, i;
// Food first: the nearest piece this fish can reach. The catfish takes what lies on the sand.
var best = 1e9;
for (i = 0; i < pellets.length; i++) {
var p = pellets[i];
if ((f.kind === 'cory' ? !(p.rest || p.y > sandY - 46) : p.rest) || (p.by && p.by !== f)) continue;
var d2 = (p.x - f.x) * (p.x - f.x) + (p.y - f.y) * (p.y - f.y) * 1.6;
if (d2 < best) { best = d2; food = p; }
}
if (f.food && f.food !== food) f.food.by = null;
f.food = food;
if (food) { food.by = f; tx = food.x; ty = f.kind === 'cory' ? sandY - 5 : food.y; eager = f.kind === 'cory' ? 1.9 : 2.3; f.pick = 0; }
else if (poke && t < poke.until && f.kind !== 'cory') { tx = poke.x + Math.cos(f.ph) * 26; ty = poke.y + Math.sin(f.ph) * 18; eager = 1.5; f.pick = 0; }
else {
if (t > f.pick || (Math.abs(f.tx - f.x) < 12 && Math.abs(f.ty - f.y) < 12 && t > f.pick - 2)) pickTarget(f, t);
tx = f.tx; ty = f.ty;
}
var dx = tx - f.x, dy = ty - f.y, d = Math.sqrt(dx * dx + dy * dy) || 1;
var want = speed * eager * (d < 34 ? .2 + d / 42 : 1);
var ease = Math.min(1, dt * f.agile * (food ? 1.6 : 1));
f.vx += (dx / d * want - f.vx) * ease;
f.vy += (dy / d * want * .75 - f.vy) * ease;
// Keep a little room between neighbours.
for (i = 0; i < fish.length; i++) {
var o = fish[i];
if (o === f) continue;
var ox = f.x - o.x, oy = f.y - o.y, room = (f.size + o.size) * (f.kind === 'tetra' || o.kind === 'tetra' ? .34 : .6), od = ox * ox + oy * oy;
if (od < room * room && od > .01) { od = Math.sqrt(od); f.vx += ox / od * (room - od) * 7 * dt; f.vy += oy / od * (room - od) * 7 * dt; }
}
f.x += f.vx * dt;
f.y += f.vy * dt + (f.kind === 'cory' ? 0 : Math.sin(t * 1.3 + f.ph) * 2.4 * dt);
f.y = f.kind === 'cory' ? sandAt(f.x) - 6 : clamp(f.y, 14, sandAt(f.x) - 9);
f.v = Math.sqrt(f.vx * f.vx + f.vy * f.vy);
if (Math.abs(f.vx) > 5) f.face += ((f.vx > 0 ? 1 : -1) - f.face) * Math.min(1, dt * 5.5);
f.tp += dt * (4.5 + f.v * .17);
if (food && d < f.size * .42 + 3) { pellets.splice(pellets.indexOf(food), 1); f.food = null; f.tp += 1.2; }
}
// ---------- how the fish look ----------
// Each is drawn facing right in a box one unit long; the caller turns, tilts and scales it.
function tail(x, swing, draw) { g.save(); g.translate(x, 0); g.rotate(swing); g.beginPath(); draw(); g.fill(); g.restore(); }
function eye(x, y, r) {
g.fillStyle = lit([250, 250, 245]); g.beginPath(); g.arc(x, y, r, 0, 6.3); g.fill();
g.fillStyle = lit([14, 18, 24]); g.beginPath(); g.arc(x + r * .2, y, r * .58, 0, 6.3); g.fill();
}
function drawTetra(f) {
var wag = Math.sin(f.tp) * .5;
g.fillStyle = lit([226, 236, 240], .6);
tail(-.42, wag, function () { g.moveTo(.05, 0); g.quadraticCurveTo(-.12, -.05, -.3, -.2); g.lineTo(-.2, 0); g.lineTo(-.3, .2); g.quadraticCurveTo(-.12, .05, .05, 0); });
g.beginPath(); g.moveTo(.1, -.16); g.lineTo(-.08, -.3); g.lineTo(-.16, -.13); g.fill();
var body = g.createLinearGradient(0, -.2, 0, .2);
body.addColorStop(0, lit([96, 124, 110])); body.addColorStop(.45, lit([196, 214, 214])); body.addColorStop(1, lit([240, 240, 232]));
g.fillStyle = body;
g.beginPath(); g.moveTo(.5, 0); g.bezierCurveTo(.3, -.21, -.2, -.2, -.46, -.035); g.lineTo(-.46, .045); g.bezierCurveTo(-.2, .2, .3, .18, .5, 0); g.fill();
g.fillStyle = lit([232, 58, 48], .92);
g.beginPath(); g.moveTo(-.46, .04); g.bezierCurveTo(-.3, .15, -.1, .14, .04, .08); g.lineTo(-.06, 0); g.lineTo(-.46, -.01); g.fill();
// The stripe shines by itself: in moonlight it is what is left of the fish.
var glow = 1 - vis * .7, stripe = mix([60 * amb[0], 214 * amb[1], 255 * amb[2]], [70, 226, 255], .25 + glow * .7);
g.lineCap = 'round';
g.beginPath(); g.moveTo(-.4, -.03); g.quadraticCurveTo(0, -.105, .36, -.04);
g.strokeStyle = rgba(stripe, .22 + glow * .2); g.lineWidth = .17; g.stroke();
g.strokeStyle = rgba(stripe, 1); g.lineWidth = .06; g.stroke();
eye(.36, -.035, .04);
}
function drawGold(f) {
var koi = f.kind === 'koi', wag = Math.sin(f.tp) * .32, lag = Math.sin(f.tp - .9) * .09, fin = koi ? [250, 236, 226] : [255, 164, 72];
g.fillStyle = lit(fin, .72);
tail(-.34, wag, function () {
g.moveTo(.02, 0); g.bezierCurveTo(-.14, -.1, -.3, -.38 + lag, -.56, -.36 + lag); g.quadraticCurveTo(-.4, -.06, -.43, 0);
g.quadraticCurveTo(-.4, .06, -.56, .36 - lag); g.bezierCurveTo(-.3, .38 - lag, -.14, .1, .02, 0);
});
g.beginPath(); g.moveTo(.2, -.22); g.quadraticCurveTo(-.02, -.52 + lag, -.3, -.2 + lag * .5); g.lineTo(-.24, -.1); g.fill();
g.beginPath(); g.moveTo(-.02, .24); g.quadraticCurveTo(-.14, .44 - lag, -.26, .16); g.fill();
var body = g.createLinearGradient(0, -.3, 0, .3);
if (koi) { body.addColorStop(0, lit([236, 232, 226])); body.addColorStop(1, lit([255, 252, 246])); }
else { body.addColorStop(0, lit([236, 104, 28])); body.addColorStop(.55, lit([255, 150, 50])); body.addColorStop(1, lit([255, 206, 122])); }
g.fillStyle = body;
g.beginPath(); g.moveTo(.5, .02); g.bezierCurveTo(.42, -.27, -.05, -.34, -.38, -.06); g.lineTo(-.38, .08); g.bezierCurveTo(-.05, .34, .4, .27, .5, .02);
g.fill();
if (koi) {
g.save(); g.clip();
g.fillStyle = lit([226, 62, 40]);
g.beginPath(); g.ellipse(.3, -.2, .2, .17, .3, 0, 6.3); g.fill();
g.beginPath(); g.ellipse(-.1, -.16, .17, .2, -.2, 0, 6.3); g.fill();
g.beginPath(); g.ellipse(-.34, .06, .1, .1, 0, 0, 6.3); g.fill();
g.restore();
} else {
g.strokeStyle = lit([255, 226, 160], .35); g.lineWidth = .02;
g.beginPath(); g.moveTo(.26, .04); g.quadraticCurveTo(0, .1, -.3, .02); g.stroke();
}
g.save(); g.translate(.14, .1); g.rotate(.7 + Math.sin(f.tp * .6) * .4);
g.fillStyle = lit(fin, .7); g.beginPath(); g.ellipse(-.09, 0, .12, .05, 0, 0, 6.3); g.fill(); g.restore();
eye(.36, -.06, .048);
}
function drawCory(f) {
var wag = Math.sin(f.tp) * .4;
g.fillStyle = lit([150, 132, 104], .85);
tail(-.38, wag, function () { g.moveTo(.04, 0); g.lineTo(-.26, -.2); g.lineTo(-.18, 0); g.lineTo(-.26, .16); });
g.beginPath(); g.moveTo(.1, -.2); g.lineTo(-.04, -.42); g.lineTo(-.16, -.16); g.fill();
var body = g.createLinearGradient(0, -.24, 0, .14);
body.addColorStop(0, lit([116, 100, 80])); body.addColorStop(1, lit([214, 196, 160]));
g.fillStyle = body;
g.beginPath(); g.moveTo(.5, .08); g.bezierCurveTo(.42, -.2, 0, -.27, -.4, -.02); g.lineTo(-.4, .1); g.quadraticCurveTo(0, .16, .5, .13); g.fill();
g.fillStyle = lit([70, 58, 46], .7);
[[.1, -.1], [-.06, -.06], [-.2, -.04], [.22, -.02], [0, .03]].forEach(function (s) { g.beginPath(); g.arc(s[0], s[1], .028, 0, 6.3); g.fill(); });
g.strokeStyle = lit([150, 132, 104]); g.lineWidth = .025; g.lineCap = 'round';
g.beginPath(); g.moveTo(.48, .11); g.lineTo(.54, .2); g.moveTo(.44, .12); g.lineTo(.46, .21); g.stroke();
eye(.34, -.04, .045);
}
function drawFish(f) {
g.save();
g.translate(f.x, f.y);
var turn = Math.abs(f.face) < .14 ? (f.face < 0 ? -.14 : .14) : f.face; // mid-turn the fish is seen from the front: short, never gone
g.scale(turn * f.size, f.size);
if (f.kind !== 'cory') g.rotate(clamp(Math.atan2(f.vy, Math.abs(f.vx) + 12), -.45, .45) + Math.sin(f.tp) * .035);
if (f.kind === 'tetra') drawTetra(f); else if (f.kind === 'cory') drawCory(f); else drawGold(f);
g.restore();
}
function drawBlade(b, t, haze) {
var n = 9, reach = b.h * .11, baseY = sandAt(b.x) + (b.front ? 16 : 5), xs = [], ys = [], i, s;
for (i = 0; i <= n; i++) {
s = i / n;
xs.push(b.x + b.lean * b.h * s * s + (RM ? 0 : Math.sin(t * b.sp + b.ph - s * 2.4) * reach * s * s + Math.sin(t * b.sp * .43 + b.ph * 2) * reach * .6 * s));
ys.push(baseY - b.h * s);
}
g.beginPath(); g.moveTo(xs[0] - b.w, ys[0]);
for (i = 1; i <= n; i++) g.lineTo(xs[i] - b.w * (1 - Math.pow(i / n, 1.6)), ys[i]);
for (i = n; i >= 0; i--) g.lineTo(xs[i] + b.w * (1 - Math.pow(i / n, 1.6)), ys[i]);
g.fillStyle = lit(b.col, 1, haze); g.fill();
g.beginPath(); g.moveTo(xs[0], ys[0]);
for (i = 1; i < n; i++) g.lineTo(xs[i], ys[i]);
g.strokeStyle = lit([230, 255, 200], .16, haze); g.lineWidth = 1; g.stroke();
}
function rock(x, y, w, h, shade, haze) {
g.beginPath(); g.moveTo(x - w, y + 8);
g.bezierCurveTo(x - w * .9, y - h * .9, x - w * .2, y - h * 1.15, x + w * .15, y - h);
g.bezierCurveTo(x + w * .7, y - h * .8, x + w, y - h * .2, x + w * 1.05, y + 8);
var fill = g.createLinearGradient(0, y - h, 0, y + 8);
fill.addColorStop(0, lit([shade + 34, shade + 40, shade + 44], 1, haze)); fill.addColorStop(1, lit([shade - 10, shade - 6, shade], 1, haze));
g.fillStyle = fill; g.fill();
}
function drawTank(t, dt) {
if (W === 0) return;
var i, k = RM ? 1 : Math.min(1, dt * 1.3);
look.L += (lookTo.L - look.L) * k; look.dawn += (lookTo.dawn - look.dawn) * k; look.dusk += (lookTo.dusk - look.dusk) * k;
vis = Math.pow(clamp(look.L, 0, 1), .6);
var tint = Math.max(look.dawn, look.dusk), warm = look.dawn >= look.dusk ? DAWN : DUSK;
var water = [0, 1, 2].map(function (n) { return mix(mix(NIGHT[n], DAY[n], vis), warm[n], tint * .72); });
waterMid = water[1];
amb = mix(mix([.2, .28, .5], [1, 1, 1], vis), look.dawn >= look.dusk ? [1, .84, .8] : [1, .76, .6], tint * .8);
var sea = g.createLinearGradient(0, 0, 0, H);
sea.addColorStop(0, rgba(water[0], 1)); sea.addColorStop(.5, rgba(water[1], 1)); sea.addColorStop(1, rgba(water[2], 1));
g.globalCompositeOperation = 'source-over';
g.fillStyle = sea; g.fillRect(0, 0, W, H);
// Light from above: rays by day, one pale beam and a glow where the moon stands at night.
g.globalCompositeOperation = 'lighter';
var rayCol = mix([255, 248, 214], warm[0], tint * .7), night = 1 - vis;
for (i = 0; i < 6; i++) {
var rx = W * (.04 + .19 * i) + Math.sin(t * .17 + i * 1.9) * 22, rw = 16 + (i % 3) * 12, slant = H * .32;
var ra = (.05 + .045 * Math.sin(t * .5 + i * 2.3)) * vis * vis * (RM ? .8 : 1);
if (ra <= .003) continue;
var ray = g.createLinearGradient(0, 0, 0, H * .92);
ray.addColorStop(0, rgba(rayCol, ra * 1.7)); ray.addColorStop(1, rgba(rayCol, 0));
g.fillStyle = ray;
g.beginPath(); g.moveTo(rx, 0); g.lineTo(rx + rw, 0); g.lineTo(rx + rw * 2.6 - slant, H * .92); g.lineTo(rx - rw * 1.2 - slant, H * .92); g.fill();
}
if (night > .25) {
var mg = g.createRadialGradient(W * .74, -30, 10, W * .74, -30, H * .7);
mg.addColorStop(0, 'rgba(170,200,255,' + (.34 * (night - .25)).toFixed(3) + ')'); mg.addColorStop(1, 'rgba(170,200,255,0)');
g.fillStyle = mg; g.fillRect(0, 0, W, H);
g.fillStyle = 'rgba(180,205,255,' + ((.05 + .015 * Math.sin(t * .4)) * (night - .25)).toFixed(3) + ')';
g.beginPath(); g.moveTo(W * .66, 0); g.lineTo(W * .84, 0); g.lineTo(W * .62, H); g.lineTo(W * .26, H); g.fill();
}
g.globalCompositeOperation = 'source-over';
// Far back: rocks and the taller plants, pale with distance.
rock(W * .84, sandY + 4, W * .2, H * .2, 70, .5);
rock(W * .12, sandY + 4, W * .16, H * .11, 60, .55);
for (i = 0; i < blades.length; i++) if (!blades[i].front) drawBlade(blades[i], t, .38);
for (i = 0; i < motes.length; i++) {
var m = motes[i], mx = ((m.x + t * .004 * (RM ? 0 : 1) + Math.sin(t * .3 + m.ph) * .01) % 1) * W, my = ((m.y + Math.sin(t * .21 + m.ph) * .02 + 1) % 1) * sandY;
g.fillStyle = 'rgba(255,255,240,' + ((.1 + .12 * Math.sin(t + m.ph)) * (.25 + vis * .75)).toFixed(3) + ')';
g.beginPath(); g.arc(mx, my, m.r, 0, 6.3); g.fill();
}
// The sand, with the light that the ripples of the surface throw on it.
g.beginPath(); g.moveTo(0, H);
for (var x = 0; x <= W + 8; x += 8) g.lineTo(x, sandAt(x));
g.lineTo(W, H);
var sand = g.createLinearGradient(0, sandY - 8, 0, H);
sand.addColorStop(0, lit([232, 210, 160])); sand.addColorStop(1, lit([160, 130, 92]));
g.fillStyle = sand; g.fill();
g.save(); g.clip(); g.globalCompositeOperation = 'lighter';
for (i = 0; i < 6; i++) {
g.fillStyle = 'rgba(255,250,220,' + (.07 * vis * vis).toFixed(3) + ')';
g.beginPath(); g.ellipse(((i * .19 + .06 + Math.sin(t * .23 + i * 2) * .05) % 1) * W, sandY + 16 + (i % 3) * 12, 30 + 14 * Math.sin(t * .6 + i), 5 + (i % 2) * 3, -.1, 0, 6.3); g.fill();
}
g.restore(); g.globalCompositeOperation = 'source-over';
for (i = 0; i < pebbles.length; i++) {
var pb = pebbles[i], px = pb.x * W, py = sandAt(px) + pb.dy;
g.fillStyle = lit([150 * pb.shade, 140 * pb.shade, 130 * pb.shade]);
g.beginPath(); g.ellipse(px, py, pb.r * 1.5, pb.r, 0, 0, 6.3); g.fill();
}
rock(W * .61, sandY + 14, W * .085, H * .055, 86, 0);
// The air stone the bubbles come from.
g.fillStyle = lit([70, 84, 96]);
g.beginPath(); g.ellipse(W * .235, sandAt(W * .235) + 1, 11, 4.5, 0, 0, 6.3); g.fill();
// Food, fish, and the plants in front of them.
if (!RM) {
if (toDrop > 0 && t >= dropAt) {
toDrop--; dropAt = t + .1;
pellets.push({ x: clamp(W * .62 + rnd(-1, 1) * rnd(0, 1) * W * .2, 12, W - 12), y: -3, vy: rnd(17, 30), ph: rnd(0, 6), r: rnd(1.7, 2.6), rest: false, born: t });
}
if (t > school.next) { school.next = t + rnd(5, 9); school.x = W * rnd(.14, .86); school.y = rnd(H * .26 + H * .3 * (1 - vis), sandY - 30); }
for (i = pellets.length - 1; i >= 0; i--) {
var pe = pellets[i];
if (!pe.rest) {
pe.y += pe.vy * dt; pe.x += Math.sin(t * 2 + pe.ph) * 7 * dt;
if (pe.y >= sandAt(pe.x) + 2) { pe.rest = true; pe.born = t; }
} else if (t - pe.born > 16) pellets.splice(i, 1);
}
for (i = 0; i < fish.length; i++) moveFish(fish[i], t, dt);
}
for (i = 0; i < pellets.length; i++) {
var q = pellets[i];
g.fillStyle = lit([196, 118, 56], q.rest ? clamp((16 - (t - q.born)) / 3, 0, 1) : 1);
g.beginPath(); g.arc(q.x, q.y, q.r, 0, 6.3); g.fill();
}
for (i = 0; i < fish.length; i++) drawFish(fish[i]);
for (i = 0; i < blades.length; i++) if (blades[i].front) drawBlade(blades[i], t, 0);
for (i = 0; i < bubbles.length; i++) {
var b = bubbles[i];
if (!RM) { b.y -= b.vy * dt * (.7 + b.r * .18); if (b.y < -6) bubbles[i] = b = newBubble(); }
var bx = b.x0 + Math.sin(t * 3.1 + b.ph) * (1.5 + b.r) + (sandY - b.y) * .03, shine = .3 + vis * .45;
g.strokeStyle = 'rgba(225,245,255,' + shine.toFixed(2) + ')'; g.lineWidth = 1;
g.beginPath(); g.arc(bx, b.y, b.r, 0, 6.3); g.stroke();
g.fillStyle = 'rgba(255,255,255,' + (shine * .9).toFixed(2) + ')';
g.beginPath(); g.arc(bx - b.r * .35, b.y - b.r * .35, b.r * .28, 0, 6.3); g.fill();
}
if (poke && t < poke.at + .9) {
var age = (t - poke.at) / .9;
g.strokeStyle = 'rgba(255,255,255,' + (.5 * (1 - age)).toFixed(2) + ')'; g.lineWidth = 1.5;
g.beginPath(); g.arc(poke.x, poke.y, 6 + age * 30, 0, 6.3); g.stroke();
}
// The shade of the hood at the top, where the readings stand, and darker corners.
var hood = g.createLinearGradient(0, 0, 0, H * .46);
hood.addColorStop(0, 'rgba(2,22,40,' + ((.2 + .42 * vis) * (1 - .45 * tint)).toFixed(2) + ')'); hood.addColorStop(1, 'rgba(2,22,40,0)');
g.fillStyle = hood; g.fillRect(0, 0, W, H * .46);
var edge = g.createRadialGradient(W / 2, H * .5, H * .3, W / 2, H * .5, H * .85);
edge.addColorStop(0, 'rgba(0,10,24,0)'); edge.addColorStop(1, 'rgba(0,10,24,.38)');
g.fillStyle = edge; g.fillRect(0, 0, W, H);
}
cv.addEventListener('pointerdown', function (event) {
if (RM || W === 0) return;
var box = cv.getBoundingClientRect(), now = performance.now() / 1000;
poke = { x: event.clientX - box.left, y: clamp(event.clientY - box.top, 20, sandY - 10), at: now, until: now + 3.2 };
});
// ---------- values that glide to their target ----------
var shownTemp = null, tempTo = null;
function showTemp() { text($('tV'), shownTemp === null ? '–' : shownTemp.toFixed(1)); }
// ---------- what the state looks like ----------
var state = null, history = null, editingUntil = 0, busy = false, wasFeeding = false;
var plan = { sunrise: 480, sunset: 1200, ramp: 45, dayLevel: 85, moonLevel: 4 }, mode = 'auto';
var PHASES = { dawn: 'Dawn', day: 'Day', dusk: 'Dusk', moon: 'Moonlight' };
var ICONS = {
day: '<circle cx="9" cy="9" r="3.6" fill="#ffd27a"/><path d="M9 1.5v2M9 14.5v2M1.5 9h2M14.5 9h2M3.7 3.7l1.4 1.4M12.9 12.9l1.4 1.4M3.7 14.3l1.4-1.4M12.9 5.1l1.4-1.4" stroke="#ffd27a" stroke-width="1.5" stroke-linecap="round"/>',
dawn: '<path d="M4.4 12a4.6 4.6 0 0 1 9.2 0z" fill="#ffb08f"/><path d="M1.5 12h15M9 3v2.2M3.6 6.2l1.5 1.5M14.4 6.2l-1.5 1.5M5 15h8" stroke="#ffb08f" stroke-width="1.5" stroke-linecap="round"/>',
dusk: '<path d="M4.4 12a4.6 4.6 0 0 1 9.2 0z" fill="#ff9a5a"/><path d="M1.5 12h15M5 15h8M9 2.6v3M7.6 4.4L9 5.8l1.4-1.4" stroke="#ff9a5a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"/>',
moon: '<path d="M13.6 11.6A6 6 0 0 1 6.4 4.4a6 6 0 1 0 7.2 7.2z" fill="#cfe3ff"/>',
manual: '<path d="M6.2 11.5a4.5 4.5 0 1 1 5.6 0v1.6H6.2zM7 15.5h4" fill="none" stroke="#ffd27a" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>'
};
var shownIcon = '';
function ago(seconds) {
if (seconds < 90) return 'just now';
if (seconds < 3600) return Math.round(seconds / 60) + ' min ago';
if (seconds < 172800) return Math.round(seconds / 3600) + ' h ago';
return Math.round(seconds / 86400) + ' d ago';
}
function uptime(seconds) {
var d = Math.floor(seconds / 86400), h = Math.floor(seconds % 86400 / 3600), m = Math.floor(seconds % 3600 / 60);
return d > 0 ? d + ' d ' + h + ' h' : h > 0 ? h + ' h ' + m + ' min' : m + ' min';
}
// The brightness the schedule asks for at a minute of the day, in percent. The device computes the same.
function levelAt(minute) {
var p = plan;
if (minute < p.sunrise || minute >= p.sunset + p.ramp) return p.moonLevel;
if (minute < p.sunrise + p.ramp) return p.moonLevel + (p.dayLevel - p.moonLevel) * (minute - p.sunrise) / p.ramp;
if (minute < p.sunset) return p.dayLevel;
return p.dayLevel - (p.dayLevel - p.moonLevel) * (minute - p.sunset) / p.ramp;
}
function showControls() {
var manual = mode === 'manual';
$('lightP').classList.toggle('manual', manual);
Array.prototype.forEach.call(document.querySelectorAll('.seg button'), function (b) { b.setAttribute('aria-selected', b.getAttribute('data-m') === mode ? 'true' : 'false'); });
text($('lSub'), manual ? 'Stays this bright until you switch back.' : 'Drag the sun and the moon to set the day.');
text($('lvlL'), manual ? 'Brightness' : 'Brightness by day');
text($('riseV'), hhmm(plan.sunrise)); text($('setV'), hhmm(plan.sunset));
var lvl = $('lvl');
lvl.min = manual ? '0' : '10';
text($('lvlV'), Math.round(Number(lvl.value)) + ' %');
lvl.style.setProperty('--p', ((Number(lvl.value) - Number(lvl.min)) / (100 - Number(lvl.min)) * 100).toFixed(1) + '%');
drawDay();
}
// The day as a curve: night, the ramp up, the day, the ramp down. The handles of the two range inputs
// stand on it, so the picture uses the same 15 px inset that a 30 px handle has at either end.
function drawDay() {
var svg = $('dayS'), Wd = $('day').clientWidth || 320, Hd = 72, p = plan;
while (svg.firstChild) svg.removeChild(svg.firstChild);
svg.setAttribute('viewBox', '0 0 ' + Wd + ' ' + Hd);
var x = function (minute) { return 15 + (Wd - 30) * minute / 1440; };
var y = function (level) { return Hd - 10 - (Hd - 22) * level / 100; };
var defs = el('defs', {}, svg), fill = el('linearGradient', { id: 'dg', x1: 0, y1: 0, x2: 0, y2: 1 }, defs);
el('stop', { offset: 0, 'stop-color': '#ffd27a', 'stop-opacity': .5 }, fill);
el('stop', { offset: 1, 'stop-color': '#ffd27a', 'stop-opacity': .03 }, fill);
el('rect', { x: 0, y: 0, width: Wd, height: Hd, rx: 16, fill: 'rgba(0,8,20,.42)', stroke: 'rgba(160,220,235,.1)' }, svg);
for (var h = 6; h < 24; h += 6) el('path', { d: 'M' + x(h * 60) + ' 8V' + (Hd - 8), stroke: 'rgba(160,220,235,.09)' }, svg);
var line = 'M' + x(0) + ' ' + y(p.moonLevel) + 'L' + x(p.sunrise) + ' ' + y(p.moonLevel) + 'L' + x(p.sunrise + p.ramp) + ' ' + y(p.dayLevel) +
'L' + x(p.sunset) + ' ' + y(p.dayLevel) + 'L' + x(Math.min(1440, p.sunset + p.ramp)) + ' ' + y(p.moonLevel) + 'L' + x(1440) + ' ' + y(p.moonLevel);
el('path', { d: line + 'V' + (Hd - 6) + 'H' + x(0) + 'z', fill: 'url(#dg)' }, svg);
el('path', { d: line, fill: 'none', stroke: '#ffd27a', 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }, svg);
if (state && Array.isArray(state.feedTimes)) state.feedTimes.forEach(function (minute) {
if (num(minute)) el('circle', { cx: x(minute), cy: Hd - 7, r: 3, fill: '#ff8f70' }, svg);
});
if (state && num(state.minuteOfDay)) {
var nx = x(state.minuteOfDay), ny = y(num(state.light) ? state.light : levelAt(state.minuteOfDay));
el('path', { d: 'M' + nx.toFixed(1) + ' 6V' + (Hd - 6), stroke: '#fff', 'stroke-width': 1.2, opacity: .7 }, svg);
el('circle', { cx: nx.toFixed(1), cy: ny.toFixed(1), r: 4, fill: '#fff', stroke: '#0a1f2c', 'stroke-width': 1.5 }, svg);
}
}
function apply(s) {
state = s;
tempTo = num(s.temperature) ? s.temperature : null;
if (shownTemp === null || tempTo === null || RM) { shownTemp = tempTo; showTemp(); }
var cold = tempTo !== null && tempTo < 23, hot = tempTo !== null && tempTo > 28;
text($('tS'), tempTo === null ? 'No reading from the sensor' : cold ? 'Too cold for tropical fish' : hot ? 'Too warm' : 'Comfortable');
$('tI').style.setProperty('--tc', tempTo === null ? '#8fb3bd' : cold ? '#7fb6ff' : hot ? '#ff8f70' : '#6fe6a0');
var auto = s.mode !== 'manual', sched = s.schedule || plan, light = num(s.light) ? s.light : 0;
lookTo.L = light / 100; lookTo.dawn = 0; lookTo.dusk = 0;
if (auto && (s.phase === 'dawn' || s.phase === 'dusk') && sched.dayLevel > sched.moonLevel) {
lookTo[s.phase] = Math.pow(Math.sin(Math.PI * clamp((light - sched.moonLevel) / (sched.dayLevel - sched.moonLevel), 0, 1)), .7);
}
var icon = auto ? (PHASES[s.phase] ? s.phase : 'moon') : 'manual';
if (icon !== shownIcon) { shownIcon = icon; $('phI').innerHTML = ICONS[icon]; }
text($('phT'), auto ? (PHASES[s.phase] || 'Waiting for the time') : 'Manual');
text($('phS'), Math.round(light) + ' %' + (num(s.minuteOfDay) ? ' · ' + hhmm(s.minuteOfDay) : ''));
if (num(s.nextFeedMinutes) && num(s.minuteOfDay)) {
text($('nfT'), hhmm(s.minuteOfDay + s.nextFeedMinutes));
text($('nfIn'), 'in ' + span(s.nextFeedMinutes));
} else {
text($('nfT'), '–');
text($('nfIn'), num(s.minuteOfDay) ? 'no feeding times set' : 'the device has no time yet');
}
text($('fed'), s.feeding ? 'Feeding now' : num(s.lastFedSecondsAgo) ? 'Last fed ' + ago(s.lastFedSecondsAgo) : 'Not fed since the device started');
if (s.feeding && !wasFeeding && !RM) { toDrop = 16; dropAt = 0; }
wasFeeding = s.feeding === true;
$('feed').classList.toggle('on', wasFeeding);
$('feed').disabled = busy || wasFeeding;
text($('feedT'), wasFeeding ? 'Feeding' : 'Feed');
if (Date.now() > editingUntil) {
mode = auto ? 'auto' : 'manual';
if (s.schedule) ['sunrise', 'sunset', 'ramp', 'dayLevel', 'moonLevel'].forEach(function (key) { if (num(s.schedule[key])) plan[key] = s.schedule[key]; });
$('rise').value = String(plan.sunrise); $('set').value = String(plan.sunset);
$('lvl').min = auto ? '10' : '0';
$('lvl').value = String(Math.round(auto ? plan.dayLevel : light));
showControls();
} else drawDay();
var bars = !num(s.rssi) ? 0 : s.rssi >= -55 ? 4 : s.rssi >= -67 ? 3 : s.rssi >= -78 ? 2 : 1;
Array.prototype.forEach.call(document.querySelectorAll('footer rect'), function (r, n) { r.setAttribute('class', n < bars ? 'on' : ''); });
text($('rssi'), num(s.rssi) ? 'Wi-Fi ' + Math.round(s.rssi) + ' dBm' : 'Wi-Fi');
text($('up'), num(s.uptimeSeconds) ? 'Running for ' + uptime(s.uptimeSeconds) : '');
$('sim').hidden = s.simulated !== true;
if (RM) drawTank(0, 0);
}
var toastTimer = 0;
function toast(message) {
var t = $('toast');
t.textContent = message;
t.classList.add('show');
clearTimeout(toastTimer);
toastTimer = setTimeout(function () { t.classList.remove('show'); }, 3200);
}
function online(ok) {
$('link').className = 'pill' + (ok ? '' : ' off');
text($('linkT'), ok ? 'Live' : 'Offline, retrying');
$('app').classList.toggle('off-line', !ok);
}
// ---------- the chart: the water over 24 hours, with the light of the tank behind it ----------
var chart = null;
function smooth(points) {
// A monotone curve: it never swings past a sample.
var n = points.length, d = 'M' + points[0][0].toFixed(1) + ' ' + points[0][1].toFixed(1), slope = [], m = [], i;
if (n < 3) return d + points.slice(1).map(function (p) { return 'L' + p[0].toFixed(1) + ' ' + p[1].toFixed(1); }).join('');
for (i = 0; i < n - 1; i++) slope.push((points[i + 1][1] - points[i][1]) / (points[i + 1][0] - points[i][0]));
m.push(slope[0]);
for (i = 1; i < n - 1; i++) m.push(slope[i - 1] * slope[i] <= 0 ? 0 : 2 * slope[i - 1] * slope[i] / (slope[i - 1] + slope[i]));
m.push(slope[n - 2]);
for (i = 0; i < n - 1; i++) {
var h = (points[i + 1][0] - points[i][0]) / 3;
d += 'C' + (points[i][0] + h).toFixed(1) + ' ' + (points[i][1] + m[i] * h).toFixed(1) + ' ' + (points[i + 1][0] - h).toFixed(1) + ' ' +
(points[i + 1][1] - m[i + 1] * h).toFixed(1) + ' ' + points[i + 1][0].toFixed(1) + ' ' + points[i + 1][1].toFixed(1);
}
return d;
}
function drawChart(animate) {
var svg = $('cv'), box = $('plot'), sub = $('cSub');
while (svg.firstChild) svg.removeChild(svg.firstChild);
chart = null;
var all = history && Array.isArray(history.temperature) ? history.temperature : [], lights = history && Array.isArray(history.light) ? history.light : [];
var first = 0;
while (first < all.length && !num(all[first])) first++;
var values = all.slice(first).filter(num);
if (values.length < 2 || values.length !== all.length - first) values = all.filter(num), lights = [];
else lights = lights.slice(first);
if (values.length < 2) { sub.textContent = history ? 'Collecting the first readings' : ''; return; }
var Wc = box.clientWidth || 320, Hc = box.clientHeight || 150, L = 30, R = 8, T = 10, B = 20;
svg.setAttribute('viewBox', '0 0 ' + Wc + ' ' + Hc);
var min = Math.min.apply(null, values), max = Math.max.apply(null, values), sum = 0;
values.forEach(function (v) { sum += v; });
var lo = Math.floor((min - .15) * 2) / 2, hi = Math.ceil((max + .15) * 2) / 2;
if (hi - lo < 1) hi = lo + 1;
var step = history.intervalSeconds > 0 ? history.intervalSeconds : 900, n = values.length, slots = Math.max(n - 1, Math.round(86400 / step) - 1);
var x = function (i) { return L + (Wc - L - R) * (slots - (n - 1 - i)) / slots; };
var y = function (v) { return T + (Hc - T - B) * (1 - (v - lo) / (hi - lo)); };
var defs = el('defs', {}, svg);
var stroke = el('linearGradient', { id: 'tl', gradientUnits: 'userSpaceOnUse', x1: 0, y1: T, x2: 0, y2: Hc - B }, defs);
el('stop', { offset: 0, 'stop-color': '#ff8f70' }, stroke); el('stop', { offset: 1, 'stop-color': '#5fd9e6' }, stroke);
var area = el('linearGradient', { id: 'ta', x1: 0, y1: 0, x2: 0, y2: 1 }, defs);
el('stop', { offset: 0, 'stop-color': '#5fd9e6', 'stop-opacity': .26 }, area); el('stop', { offset: 1, 'stop-color': '#5fd9e6', 'stop-opacity': 0 }, area);
// Behind the curve: where the light of the tank was on.
if (lights.length === n && lights.every(num)) {
var lamp = el('linearGradient', { id: 'tb', gradientUnits: 'userSpaceOnUse', x1: x(0), y1: 0, x2: x(n - 1), y2: 0 }, defs);
lights.forEach(function (level, i) { el('stop', { offset: (i / (n - 1)).toFixed(4), 'stop-color': '#ffd27a', 'stop-opacity': (clamp(level, 0, 100) / 100 * .13).toFixed(3) }, lamp); });
el('rect', { x: x(0).toFixed(1), y: T, width: (x(n - 1) - x(0)).toFixed(1), height: Hc - T - B, rx: 6, fill: 'url(#tb)' }, svg);
}
for (var gI = 0; gI <= 2; gI++) {
var gv = lo + (hi - lo) * gI / 2, gy = y(gv);
el('path', { 'class': 'gr', d: 'M' + L + ' ' + gy + 'H' + (Wc - R) }, svg);
el('text', { x: L - 6, y: gy + 3.5, 'text-anchor': 'end' }, svg).textContent = gv.toFixed((hi - lo) % 1 ? 2 : 1).replace(/(.d)0$/, '$1');
}
[[24, 'start'], [18, 'middle'], [12, 'middle'], [6, 'middle'], [0, 'end']].forEach(function (tick) {
el('text', { x: L + (Wc - L - R) * (1 - tick[0] / 24), y: Hc - 4, 'text-anchor': tick[1] }, svg).textContent = tick[0] === 0 ? 'now' : '−' + tick[0] + ' h';
});
var points = values.map(function (v, k) { return [x(k), y(v)]; });
var line = smooth(points);
el('path', { 'class': 'ar', d: line + 'V' + (Hc - B) + 'H' + points[0][0].toFixed(1) + 'z' }, svg);
el('path', { 'class': 'ln' + (animate ? ' draw' : ''), d: line, pathLength: 1 }, svg);
var end = points[n - 1];
el('circle', { 'class': 'halo', cx: end[0], cy: end[1], r: 5 }, svg);
el('circle', { 'class': 'dot', cx: end[0], cy: end[1], r: 4 }, svg);
var cross = el('g', { style: 'display:none' }, svg);
el('path', { 'class': 'cx', d: 'M0 ' + T + 'V' + (Hc - B) }, cross);
el('circle', { 'class': 'dot', r: 4.5 }, cross);
while (sub.firstChild) sub.removeChild(sub.firstChild);
[['Low', min], ['Average', sum / n], ['High', max]].forEach(function (item) {
var s = document.createElement('span'), b = document.createElement('b');
s.textContent = item[0]; b.textContent = item[1].toFixed(1) + ' °C'; s.appendChild(b); sub.appendChild(s);
});
chart = { points: points, values: values, cross: cross, step: step, W: Wc };
}
function probe(event) {
if (!chart) return;
var rect = $('plot').getBoundingClientRect(), px = (event.clientX - rect.left) * chart.W / rect.width, best = 0;
chart.points.forEach(function (p, i) { if (Math.abs(p[0] - px) < Math.abs(chart.points[best][0] - px)) best = i; });
var p = chart.points[best], back = (chart.points.length - 1 - best) * chart.step, tip = $('tip');
chart.cross.style.display = '';
chart.cross.setAttribute('transform', 'translate(' + p[0].toFixed(1) + ' 0)');
chart.cross.lastChild.setAttribute('cy', p[1].toFixed(1));
tip.textContent = chart.values[best].toFixed(1) + ' °C';
var when = document.createElement('small');
when.textContent = back < 450 ? 'now' : back < 3600 ? Math.round(back / 60) + ' min ago' : (back / 3600).toFixed(back % 3600 ? 1 : 0) + ' h ago';
tip.appendChild(when);
tip.style.left = clamp(p[0] * rect.width / chart.W, 56, rect.width - 56) + 'px';
tip.style.top = (p[1] > 46 ? p[1] - 36 : p[1] + 14) + 'px';
tip.style.opacity = '1';
}
function unprobe() { if (chart) chart.cross.style.display = 'none'; $('tip').style.opacity = '0'; }
$('plot').addEventListener('pointermove', probe);
$('plot').addEventListener('pointerdown', probe);
['pointerleave', 'pointerup', 'pointercancel'].forEach(function (name) { $('plot').addEventListener(name, unprobe); });
var resizeTimer = 0;
window.addEventListener('resize', function () { clearTimeout(resizeTimer); resizeTimer = setTimeout(function () { resize(); drawChart(false); drawDay(); }, 150); });
// ---------- controls ----------
$('feed').addEventListener('click', function () {
if (!state || busy) return;
busy = true;
this.disabled = true;
api('/feed', {}).then(apply, function (error) { toast(error.message); }).then(function () { busy = false; if (state) $('feed').disabled = state.feeding === true; });
});
var sendTimer = 0;
function send(path, body) {
editingUntil = Date.now() + 2500;
clearTimeout(sendTimer);
sendTimer = setTimeout(function () {
editingUntil = Date.now() + 2500;
api(path, body()).then(function (s) { editingUntil = 0; apply(s); }, function (error) { editingUntil = 0; toast(error.message); });
}, 350);
}
function sendPlan() { send('/schedule', function () { return { sunrise: plan.sunrise, sunset: plan.sunset, dayLevel: plan.dayLevel }; }); }
function sendLight() { send('/light', function () { return mode === 'manual' ? { mode: 'manual', level: Number($('lvl').value) } : { mode: 'auto' }; }); }
// The day keeps its order: a dawn, at least an hour of day, a dusk that ends before midnight.
$('rise').addEventListener('input', function () {
plan.sunrise = clamp(Number(this.value), 0, plan.sunset - plan.ramp - 60);
this.value = String(plan.sunrise);
showControls(); sendPlan();
});
$('set').addEventListener('input', function () {
plan.sunset = clamp(Number(this.value), plan.sunrise + plan.ramp + 60, 1425 - plan.ramp);
this.value = String(plan.sunset);
showControls(); sendPlan();
});
$('lvl').addEventListener('input', function () {
if (mode === 'manual') { lookTo.L = Number(this.value) / 100; showControls(); sendLight(); }
else { plan.dayLevel = Number(this.value); showControls(); sendPlan(); }
});
Array.prototype.forEach.call(document.querySelectorAll('.seg button'), function (button) {
button.addEventListener('click', function () {
var wanted = button.getAttribute('data-m');
if (wanted === mode) return;
mode = wanted;
$('lvl').min = mode === 'manual' ? '0' : '10';
$('lvl').value = String(Math.round(mode === 'manual' && state && num(state.light) ? state.light : plan.dayLevel));
showControls(); sendLight();
});
});
// ---------- running ----------
function loadHistory() {
api('/history').then(function (h) { var first = !history; history = h; drawChart(first); }, function () { /* the next round asks again */ });
}
function poll() {
api('/state').then(function (s) { online(true); apply(s); if (!history) loadHistory(); }, function () { online(false); })
.then(function () { setTimeout(poll, 1000); });
}
var before = 0;
function frame(now) {
var dt = Math.min(.05, (now - before) / 1000 || 0);
before = now;
if (shownTemp !== null && tempTo !== null && shownTemp !== tempTo) {
shownTemp += (tempTo - shownTemp) * Math.min(1, dt * 3);
if (Math.abs(tempTo - shownTemp) < .02) shownTemp = tempTo;
showTemp();
}
resize();
drawTank(now / 1000, dt);
requestAnimationFrame(frame);
}
resize();
showControls();
if (RM) drawTank(0, 0); else requestAnimationFrame(frame);
poll();
setInterval(loadHistory, 15000);
})();
</script>
</body>
</html>